首页 > 解决方案 > 我们是否在双向 LSTM 中为每个批次使用不同的权重?

问题描述

例如,这是我们需要为每个批次调用的函数之一。在这里,每个批次似乎使用了不同的参数。那是对的吗?如果是这样,为什么?我们不应该对整个训练集使用相同的参数吗?

def bidirectional_lstm(input_data, num_layers=3, rnn_size=200, keep_prob=0.6):

    output = input_data
    for layer in range(num_layers):
        with tf.variable_scope('encoder_{}'.format(layer)):

            cell_fw = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
            cell_fw = tf.contrib.rnn.DropoutWrapper(cell_fw, input_keep_prob = keep_prob)

            cell_bw = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
            cell_bw = tf.contrib.rnn.DropoutWrapper(cell_bw, input_keep_prob = keep_prob)

            outputs, states = tf.nn.bidirectional_dynamic_rnn(cell_fw, 
                                                              cell_bw, 
                                                              output,
                                                              dtype=tf.float32)
            output = tf.concat(outputs,2)

    return output

for batch_i, batch in enumerate(get_batches(X_train, batch_size)):
    embeddings = tf.nn.embedding_lookup(word_embedding_matrix, batch)
    output = bidirectional_lstm(embeddings)
    print(output.shape)

标签: pythontensorflowlstmrnn

解决方案


我已经弄清楚了那里的问题。事实证明,我们确实使用了相同的参数,上面的代码会在第二次迭代中给出一个错误,说明bidirectional kernel已经存在。为了解决这个问题,我们需要设置,reuse=AUTO_REUSE同时定义范围变量。因此,线

with tf.variable_scope('encoder_{}'.format(layer)):

会变成

with tf.variable_scope('encoder_{}'.format(layer),reuse=AUTO_REUSE):

现在我们为每个批次使用相同的层。


推荐阅读