TensorFlow 1.2 如何使用 Seq2Seq 在推理时设置时间序列预测

2024-01-05

我正在尝试使用玩具模型研究 TensorFlow 库的 tf.contrib.seq2seq 部分。目前,我的图表如下:

tf.reset_default_graph()

# Placeholders
enc_inp = tf.placeholder(tf.float32, [None, n_steps, n_input])
expect = tf.placeholder(tf.float32, [None, n_steps, n_output])
expect_length = tf.placeholder(tf.int32, [None])
keep_prob = tf.placeholder(tf.float32, [])

# Encoder
cells = [tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.BasicLSTMCell(n_hidden), output_keep_prob=keep_prob) for i in range(layers_stacked_count)]
cell = tf.contrib.rnn.MultiRNNCell(cells)
encoded_outputs, encoded_states = tf.nn.dynamic_rnn(cell, enc_inp, dtype=tf.float32)

# Decoder
de_cells = [tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.BasicLSTMCell(n_hidden), output_keep_prob=keep_prob) for i in range(layers_stacked_count)]
de_cell = tf.contrib.rnn.MultiRNNCell(de_cells)

training_helper = tf.contrib.seq2seq.TrainingHelper(expect, expect_length)

decoder = tf.contrib.seq2seq.BasicDecoder(cell=de_cell, helper=training_helper, initial_state=encoded_states)
final_outputs, final_state, final_sequence_lengths = tf.contrib.seq2seq.dynamic_decode(decoder)

decoder_logits = final_outputs.rnn_output

h = tf.contrib.layers.fully_connected(decoder_logits, n_output)

diff = tf.squared_difference(h, expect)
batch_loss = tf.reduce_sum(diff, axis=1)
loss = tf.reduce_mean(batch_loss)

optimiser = tf.train.AdamOptimizer(1e-3)
training_op = optimiser.minimize(loss)

该图训练得很好并且执行得很好。但是,我不确定在推理时要做什么,因为该图总是需要expect变量(我试图预测的值)。

据我了解,TrainingHelper 函数使用基本事实作为输入,所以我需要的是推理时的另一个辅助函数。

我似乎已经过时了 seq2seq 模型的大多数实现(tf.contrib.legacy_seq2seq)。一些最新的模型经常使用 GreddyEmbeddingHelper,我不确定它是否适合连续时间序列预测。

我发现的另一个可能的解决方案是使用 CustomHelper 函数。然而,可供我学习的材料并不多,我只能不断地用头撞墙。

如果我尝试实现用于时间序列预测的 seq2seq 模型,那么在推理时我应该做什么?

任何帮助或建议将不胜感激。提前致谢!


您是对的,您需要使用另一个辅助函数进行推理,但您需要在测试和推理之间共享权重。

您可以使用 tf.variable_scope() 来完成此操作

with tf.variable_scope("decode"):
    training_helper = ...

with tf.variable_scope("decode", reuse = True):
    inference_helper = ...

有关更完整的示例,请参阅以下两个示例之一:

  • https://github.com/pplantinga/tensorflow-examples/blob/master/TensorFlow%201.2%20seq2seq%20example.ipynb https://github.com/pplantinga/tensorflow-examples/blob/master/TensorFlow%201.2%20seq2seq%20example.ipynb
  • https://github.com/udacity/deep-learning/blob/master/seq2seq/sequence_to_sequence_implementation.ipynb https://github.com/udacity/deep-learning/blob/master/seq2seq/sequence_to_sequence_implementation.ipynb
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TensorFlow 1.2 如何使用 Seq2Seq 在推理时设置时间序列预测 的相关文章

随机推荐