我正在尝试理解LSTM模型是如何工作的,特别是在keras的LSTM层中return_sequences参数的使用。作为一个简单的例子,参考下面的代码,我有点理解LSTM(1)
“为输入序列输出一个具有3个时间步长的隐藏状态”[1],LSTM(1, return_sequences=True)
“返回一个3个值的序列,每个输入时间步长一个隐藏状态输出”[1]。
然而,我对此的理解是,根据递归网络的功能,LSTM(1)
的单个输出与每个时间步长相关,这意味着LSTM(1, return_sequences=True)
的最终输出应该与LSTM(1)
的单个输出相同
例如,参考下面的代码,我不明白为什么模型2的预测的最终输出不等于模型1的输出?当运行下面的相同代码时,我进一步感到困惑,因为它只有一个值/时间步长,而且还产生了两个不同的结果。我想我的困惑来自于混合了多个具有多个时间步长的细胞,但它仍然没有在我的大脑中点击。任何关于这一点的澄清都将非常感谢!
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM
import numpy as np
# one feature per 3 time steps
data = np.array([0.1, 0.2, 0.3]).reshape((1,3,1))
# Input + a single LSTM (two versions)
input = Input(shape=(3,1))
lstm1 = LSTM(1)(input)
lstm2 = LSTM(1, return_sequences=True)(input)
model1 = Model(input, lstm1) # without return_sequences
model2 = Model(input, lstm2) # # with return_sequences
print(f'Model 1 without return_sequences:\n {model1.predict(data)}\n\n')
print(f'Model 2 with return_sequences:\n {model2.predict(data)}\n\n')
返回:
Model 1 without return_sequences:
[[-0.13452706]]
Model 2 with return_sequences:
[[[0.01917788] [0.05195162] [0.09362084]]]
发布于 2021-02-17 07:44:51
我终于想通了。我正确地假设了LSTM(1, return_sequences=True)
的最终输出应该与LSTM(1)
的单个输出相同,但由于随机种子,我得到了不同的结果!在每个LSTM层之前设置随机种子后,结果相等,如下所示:
# Input + a single LSTM (two versions)
input = Input(shape=(3,1))
tf.random.set_seed(2) # <-----
lstm1 = LSTM(1)(input)
tf.random.set_seed(2) # <-----
lstm2 = LSTM(1, return_sequences=True)(input)
仔细检查:
model1.predict(data)[0] == model2.predict(data)[0][-1] # returns: True
https://stackoverflow.com/questions/66237418
复制