我正在建立一个玩具编解码模型,机器翻译使用Tensorflow。
我使用Tensorflow 1.8.0 cpu版本。嵌入层采用300维的FastText预训练字向量。然后,该批训练数据经过编解码器,并带有注意机制。在训练阶段,译码器使用TrainHelper,在推理阶段使用GreedyEmbeddingHelper。
我已经使用双向LSTM编码器成功地运行了该模型。然而,当我试图通过使用多层LSTM来进一步改进我的模型时,就会出现错误。建立培训阶段模型的代码如下:
def BuildTrainModel(train_iterator):
((source, source_lengths), (target, target_lengths)) = train_iterator.get_next()
encoder_inputs = tf.transpose(source, [1,0]) # to time major
decoder_inputs = tf.transpose(target, [1,0])
decoder_outputs = tf.pad(decoder_inputs[1:], tf.constant([[0,1],[0,0]]), constant_values=tar_eos_id)
embedding_encoder = tf.Variable(embedding_matrix_src, name='embedding_encoder')
embedding_decoder = tf.Variable(embedding_matrix_tar, name='embedding_decoder')
# Embedding layer
encoder_emb_inp = tf.nn.embedding_lookup(embedding_encoder, encoder_inputs)
decoder_emb_inp = tf.nn.embedding_lookup(embedding_decoder, decoder_inputs)
# Encoder
# Construct forward and backward cells
forward_cell = tf.nn.rnn_cell.BasicLSTMCell(num_units)
backward_cell = tf.nn.rnn_cell.BasicLSTMCell(num_units)
encoder_outputs, encoder_states_fw, encoder_states_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(
[forward_cell] * num_layers, [backward_cell] * num_layers, encoder_emb_inp, dtype=tf.float64,
sequence_length=source_lengths, time_major=True)这里我只展示编码器部分。有关完整的代码和超级参数,请参见my:https://github.com/nkjsy/Neural-Machine-Translation/blob/master/nmt3.ipynb
错误信息是:
InvalidArgumentError: Dimensions must be equal, but are 96 and 332 for 'stack_bidirectional_rnn/cell_0/bidirectional_rnn/fw/fw/while/basic_lstm_cell/MatMul_1' (op: 'MatMul') with input shapes: [?,96], [332,128].我尝试将输入设置为forward_cell和backward_cell,没有问题,这意味着我以前只设置了一个层。一旦我添加了更多的层,问题就出现了。
发布于 2018-06-16 10:28:41
使用以下方法定义单元格实例的列表,
forward_cell = [tf.contrib.rnn.BasicLSTMCell(num_units),tf.contrib.rnn.BasicLSTMCell(num_units)]当你打印两个列表时,你可以看到不同之处,
num_units =128
num_layers =2
#Method1
forward_cell = [tf.contrib.rnn.BasicLSTMCell( num_units),tf.contrib.rnn.BasicLSTMCell(num_units)]
print(forward_cell)
#Method2
forward_cell = [tf.contrib.rnn.BasicLSTMCell(num_units)]*num_layers
print(forward_cell)上面的代码片段打印出类似于以下内容的内容,
[<tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x00000087798E6EF0>, <tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x0000008709AE72E8>]
[<tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x0000008709AFDC50>, <tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x0000008709AFDC50>]如您所见,#Method2输出相同单元格实例的列表,这是不需要的。
希望这能有所帮助。
https://stackoverflow.com/questions/50886684
复制相似问题