代码之家  ›  专栏  ›  技术社区  ›  betelgeuse

我们是否对每批产品在双向LSTM中使用不同的权重?

  •  1
  • betelgeuse  · 技术社区  · 8 年前

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

    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 回复  |  直到 8 年前
        1
  •  1
  •   betelgeuse    8 年前

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

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

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

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