Skip to main content
 首页 » 编程设计

python之在 Keras LSTM 中获取每个时间步的输出

2024年10月01日10Free-Thinker

我想做的是将 LSTM 在当前时间步的输出作为下一个时间步 LSTM 的输入。所以我想让 LSTM 在当前时间步预测单词 at 并将这个单词作为下一个时间步的输入。那么可以这样做吗:

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

请您参考如下方法:

您不能直接在 keras 中执行此操作,但您可以使用 for 循环和 stateful 网络来执行此操作。它是这样工作的(假设您将句子存储为具有 size=vocabulary_size 的整数序列:

  1. 定义一个接受一个单词并返回以下单词的有状态网络:

    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") 
    
  2. 假设您有一个 numpy array_of_samples 示例 (preceding_word, next_word),您可以通过以下方式来适应它:

    model.fit(array_of_samples[:,0], array_of_samples[:,1]) 
    
  3. 现在您可以尝试以下列方式进行预测:

    sentence = [starting_word] 
    for i in range(len_of_sequence - 1): 
        sentence.append(model.predict(numpy.array([[sentence[i]]).argmax()) 
    

现在 sentence 存储你新创建的句子