【问题标题】:Obtain output at each timestep in Keras LSTM获取 Keras LSTM 中每个时间步的输出
【发布时间】:2017-07-26 13:16:51
【问题描述】:
我想要做的是在当前时间步将 LSTM 的输出作为下一个时间步的 LSTM 的输入。所以我希望 LSTM 在当前时间步预测单词 at 并将这个单词作为下一个时间步的输入。那么这样可以吗:
如何在训练期间(即在model.fit() 函数中)指定输入和目标数据?
【问题讨论】:
标签:
python
deep-learning
keras
lstm
recurrent-neural-network
【解决方案1】:
您不能直接在keras 中执行此操作,但您可以使用for 循环和stateful 网络执行此操作。这就像这样(假设您将句子存储为带有size=vocabulary_size的整数序列:
-
定义一个接受一个单词并返回以下单词的有状态网络:
model = Input(batch_size=(batch_size, 1, 1))
model = Embedding(size_of_vocabulary, output_size, input_length=1)(input)
model = LSTM(lstm_1st_layer_size, return_sequences=True, stateful=True)(model)
....
model = LSTM(lstm_nth_layer_size, return_sequences=True, stateful=True)(model)
model = Dense(vocabulary_size, activation="softmax")
model.compile(loss="sparse_categorical_crossentropy", optimizer="rmsprop")
-
假设你有一个 numpy array_of_samples 的例子 (preceding_word, next_word) 你可以通过:
model.fit(array_of_samples[:,0], array_of_samples[:,1])
-
现在您可以尝试通过以下方式预测事物:
sentence = [starting_word]
for i in range(len_of_sequence - 1):
sentence.append(model.predict(numpy.array([[sentence[i]]).argmax())
现在sentence 存储你新创建的句子