首页 文章

在Keras LSTM的每个时间步长获得输出

提问于
浏览
1

我想要做的是在当前时间步长将LSTM的输出作为下一个时间步的LSTM的输入 . 所以我希望LSTM在当前时间步骤预测单词at并将该单词作为输入提供给下一个时间步 . 这可以做到:

如何在训练期间指定输入和目标数据,即在 model.fit() 函数中?

1 回答

  • 2

    您不能直接在 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 存储您新创建的句子

相关问题