【问题标题】:In Tensorflow, what is the difference between the returned 'output' and 'h' of state tuple (c, h) in LSTMCell?在Tensorflow中,LSTMCell中状态元组(c,h)返回的'output'和'h'有什么区别?
【发布时间】:2018-08-12 02:16:37
【问题描述】:

我搜索了许多教程/博客/指南和 Tensorflow 官方文档以了解这一点。例如,请参见以下几行:

lstm = tf.nn.rnn_cell.LSTMCell(512)
output, state_tuple = lstm(current_input, last_state_tuple)

现在如果我解压状态,

last_cell_memory, last_hidden_state =  state_tuple

output 和 last_hidden_​​state 都具有完全相同的维度 [batch_size, 512]。两者可以互换使用吗?我的意思是,我可以这样做吗? :

last_state_tuple= last_cell_memory, output 

然后在 lstm 中输入 last_state_tuple?

【问题讨论】:

    标签: python tensorflow machine-learning lstm rnn


    【解决方案1】:

    是的,状态的第二个元素与输出相同。

    来自https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/LSTMStateTuple

    按顺序存储两个元素:(c, h)。其中 c 是隐藏状态,h 是输出。

    还要进行实验验证:

    import tensorflow as tf
    from numpy import random as rng
    lstm = tf.nn.rnn_cell.LSTMCell(10)
    inp = tf.placeholder(tf.float32, shape=(1, 10))
    stt = tf.placeholder(tf.float32, shape=(1, 10))
    hdd = tf.placeholder(tf.float32, shape=(1, 10))
    out = lstm(inp, (stt, hdd))
    sess = tf.InteractiveSession()
    init = tf.global_variables_initializer()
    sess.run(init)
    a = rng.randn(1, 10)
    b = rng.randn(1, 10)
    c = rng.randn(1, 10)
    output = sess.run(out, {inp: a, stt: b, hdd: c})
    assert (output[0] == output[1][1]).all()
    

    【讨论】:

      【解决方案2】:

      Jacques 的回答是正确的,但没有提到一个重点:LSTM 层的状态几乎总是等于输出。当 LSTM 单元的链很长并且并非所有输入序列都具有相同的长度(因此被填充)时,这种差异就变得很重要。这时候就应该区分状态和输出了。

      查看my answer on a similar question 中的可运行示例(它使用BasicRNNCell,但使用LSTMCell 会得到相同的结果)。

      【讨论】:

      • 这很有趣,我的实现确实使用了用零填充的长的、可变长度的序列。这意味着应该始终提供最后一个“输出”以获取当前时间步长的输出,而不是最后一个“h”,因为这样做会为您提供“输出”之前的时间步长的输出 == ' H'。这不会传播零输出直到最大序列长度,这是需要的,也是填充序列的唯一原因。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2013-10-21
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      相关资源
      最近更新 更多