首页 > 解决方案 > Keras 中的 Seq2Seq 用于预测向量序列的下一个元素

问题描述

打扰一下。我是神经网络的初学者。我必须在 Keras 中使用 seq2seq 模型来预测向量序列x[0], x[1], ..., x[N-1]的下一个元素x[N ] 。

这个向量序列是可变长度的,即N不是固定数。序列的元素(向量)具有固定长度m。也就是说,我的数据x[0], x[1], ..., x[N-1]具有以下形式

[x[0,0], x[0,1], ..., x[0,m-1]], [x[1,0], x[1,1], ..., x[ 1,m-1]], ..., [x[N-1,0], x[N-1,1], ..., x[N-1,m-1]]

我必须预测下一个向量x[N]=[x[N,0], x[N,1], ..., x[N,m-1]]

我是否正确理解我需要的模型是在 Keras 中用这样的代码段描述的?

data_dim = m

model = Sequential()
model.add(LSTM(1, input_shape=(None, data_dim)))

非常感谢您!

标签: pythonkerasseq2seq

解决方案


To build a seq-to-seq model you'd need to use Keras's functional API instead of building a Sequential() model. There is a good example of how to do this on the Keras Blog: https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html

from keras.models import Model
from keras.layers import Input, LSTM, Dense

encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]
decoder_inputs = Input(shape=(None, num_decoder_tokens))
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
                                     initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

推荐阅读