【问题标题】:The mathematical formulation of LSTM in Keras?Keras 中 LSTM 的数学公式?
【发布时间】:2019-11-10 13:12:22
【问题描述】:

根据wikipedia-lstm-math-equation的数学公式,如下图,

应该只有隐藏状态h_t 和单元状态c_t。但是,当我尝试在 Keras 上编写 RNN 代码时,出现了三个:lstm_output、state_h 和state_c。

我现在想知道lstm_output 的数学公式是什么? 这是我的代码:

from keras.layers import Input, LSTM

lstm_input = Input(shape=(28, 10))

lstm_output, state_h, state_c = LSTM(units=32,
                                     return_sequences=True,
                                     return_state=True,
                                     unroll=True)(lstm_input)
print(lstm_output, state_h, state_c)

它给了

Using TensorFlow backend.

(<tf.Tensor 'lstm_1/transpose_1:0' shape=(?, 28, 32) dtype=float32>, <tf.Tensor 'lstm_1/mul_167:0' shape=(?, 32) dtype=float32>, <tf.Tensor 'lstm_1/add_221:0' shape=(?, 32) dtype=float32>)

【问题讨论】:

    标签: keras lstm keras-layer


    【解决方案1】:

    让我们分解一下,从源代码中查看this line - return h, [h, c]:

    • lstm_output: 是每个时间步的h。所以它的形状是(batch_size, sequence_length, hidden_size),在你的例子中是(?, 28, 32)。正如documentation 所说,它作为一个序列返回,因为您设置了return_sequences=True。
    • state_h: 是 last 时间步的h,如果可以检查,它应该等于lstm_output[:,-1]。注意为什么它的形状是(?, 32),因为它是最后一个时间步的输出,而不是每个时间步的输出。
    • state_c: 是 last 时间步的c。

    方程通常以不同的方式实现以优化某些功能,但它们都遵循original paper。请注意,激活可能会有所不同,例如使用hard_sigmoid 进行循环激活,这些应在文档中明确注明。

    【讨论】:

    • 当然不是因为return_sequences,所以总是返回层的输出。这是每一层所做的。 --- return_sequences 将定义输出是包含整个序列还是仅包含最后一步。
    • 感谢您的有用回答和评论。我试过两种情况。首先,return_sequences=True, return_state=True,它将给出lstm_output(3D)、state_h(2D)、state_c(2D) 和lstm_output[:, -1, :] 等于state_h。第二,return_sequences=False, return_state=True,它给出lstm_output(2D)、state_h(2D)、state_c(2D)和lstm_output等于state_h。
    猜你喜欢
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多