Skip to main content
 首页 » 编程设计

python之没有嵌入的 TensorFlow 中的 Seq2Seq

2024年09月07日34三少

我正在尝试创建一个非常基本的多变量时间序列自动编码器。 我希望能够准确地重建我传入的两个信号。

我正在查看的大多数引用资料都使用旧版本的 API 或使用嵌入。 我正在尝试使用最新的更高级别的 API,但不清楚如何将它们拼凑在一起。

class Seq2SeqConfig(): 
 
     def __init__(self): 
          self.sequence_length = 15 # num of time steps 
          self.hidden_units = 64 # ? 
          self.num_features = 2 
          self.batch_size = 10  
 
# Expect input as batch major.  
encoder_inputs = tf.placeholder(shape=(None, config.sequence_length, config.num_features), dtype=tf.float32) 
decoder_inputs = tf.placeholder(shape=(None, config.sequence_length, config.num_features), dtype=tf.float32)) 
 
# Convert inputs to time major 
encoder_inputs_tm = tf.transpose(encoder_inputs, [1, 0, 2]) 
decoder_inputs_tm = tf.transpose(decoder_inputs, [1, 0, 2]) 
 
# setup encoder 
encoder_cell = tf.contrib.rnn.LSTMCell(config.hidden_units) 
encoder_outputs, encoder_final_state = tf.nn.dynamic_rnn( 
    cell=encoder_cell, 
    inputs=encoder_inputs_tm, 
    time_major=True) 
 
# setup decoder 
decoder_cell = tf.contrib.rnn.LSTMCell(config.hidden_units) 
 
# The sequence length is mandatory. Not sure what the expectation is here?  
helper = tf.contrib.seq2seq.TrainingHelper( 
     decoder_inputs_tm,  
     sequence_length=tf.constant(config.sequence_length, dtype=tf.int32, shape=[config.batch_size]), 
     time_major=True) 
decoder = tf.contrib.seq2seq.BasicDecoder(decoder_cell, helper, encoder_final_state) 
decoder_outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder, output_time_major=True) 
 
# loss calculation 
loss_op = tf.reduce_mean(tf.square(decoder_outputs.rnn - decoder_targets_tm) 

损失操作失败,因为形状不同。 decoder_targets 是 (?, 15, 2) 和 decoder_outputs.rnn 是 (?, ?, 64)。

问题 1: 我是否错过了 reshape 解码器输出的某处操作? 我松散地遵循了这个 tensorflow 教程:https://www.tensorflow.org/tutorials/seq2seq

有一个 projection_layer 操作传递到基本解码器中。这是这样做的目的吗? projection_layer = layers_core.Dense(tgt_vocab_size, use_bias=False)

我在任何地方都看不到 layers_core.Dense() 函数。我假设它已弃用或内部。

问题 2: 不使用嵌入时,使用哪个助手进行推理?

问题 3: 隐藏单元的理想大小是多少? 我假设因为我们想要减少潜在空间的维度,所以它需要小于输入的大小。当您输入序列长度 = 15 且特征数 = 2 时,这将如何转换。

隐藏单元的数量应该是 < 15、< 2 还是 < 15 *2?

请您参考如下方法:

找出问题 1 的答案

from tensorflow.python.layers.core import Dense 
output_layer = Dense(config.num_features) 
decoder = tf.contrib.seq2seq.BasicDecoder(decoder_cell, helper, encoder_final_state, output_layer) 

引用:https://github.com/udacity/deep-learning/blob/master/seq2seq/sequence_to_sequence_implementation.ipynb

另外两个问题仍然存在。