我们是否在每批LSTM中使用不同的权重?

时间:2018-08-16 08:01:41

标签: python tensorflow lstm rnn

例如,这是我们需要为每个批次调用的功能之一。在这里看起来每个批次使用了不同的参数。那是对的吗?如果是的话,为什么呢?我们不应该对整个训练集使用相同的参数吗?

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)

1 个答案:

答案 0 :(得分:1)

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

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

将成为

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

现在,每个批次使用相同的图层。