2017-03-06 174 views
1

我想要做的是在当前时间步将LSTM的输出作为下一个时间步的LSTM输入。所以我希望LSTM能够在当前时间步预测单词,并将这个单词作为下一个时间步的输入。是否可以这样做:在Keras的每个时间步获得输出LSTM

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

+0

只是作为附加信息:我还试图用一个经常性的网络的输出作为下一个输入。事实证明,错误累积并且输出总是趋于一些目标值。请参阅https://stackoverflow.com/questions/37971667/time-series-forecast-with-recurrent-elman-network-in-neurolab – wehnsdaefflae

回答

2

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