【发布时间】:2016-11-06 10:37:45
【问题描述】:
我正在尝试使用 Keras 使用 LSTM 进行一些普通模式识别,以预测序列中的下一个元素。
我的数据如下所示:
其中训练序列的标签是列表中的最后一个元素:X_train['Sequence'][n][-1]。
因为我的Sequence 列可以在序列中包含可变数量的元素,我相信 RNN 是最好的模型。以下是我在 Keras 中构建 LSTM 的尝试:
# Build the model
# A few arbitrary constants...
max_features = 20000
out_size = 128
# The max length should be the length of the longest sequence (minus one to account for the label)
max_length = X_train['Sequence'].apply(len).max() - 1
# Normal LSTM model construction with sigmoid activation
model = Sequential()
model.add(Embedding(max_features, out_size, input_length=max_length, dropout=0.2))
model.add(LSTM(128, dropout_W=0.2, dropout_U=0.2))
model.add(Dense(1))
model.add(Activation('sigmoid'))
# try using different optimizers and different optimizer configs
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
以下是我尝试训练模型的方式:
# Train the model
for seq in X_train['Sequence']:
print("Length of training is {0}".format(len(seq[:-1])))
print("Training set is {0}".format(seq[:-1]))
model.fit(np.array([seq[:-1]]), [seq[-1]])
我的输出是这样的:
Length of training is 13
Training set is [1, 3, 13, 87, 1053, 28576, 2141733, 508147108, 402135275365, 1073376057490373, 9700385489355970183, 298434346895322960005291, 31479360095907908092817694945]
但是,我收到以下错误:
Exception: Error when checking model input: expected embedding_input_1 to have shape (None, 347) but got array with shape (1, 13)
我相信我的训练步骤设置正确,所以我的模型构建一定是错误的。请注意,347 是max_length。
如何在 Keras 中正确构建可变长度输入 LSTM?我不想填充数据。不确定它是否相关,但我正在使用 Theano 后端。
【问题讨论】:
-
我设法通过指定 input_shape 并使用 None 作为任意长度来完成这项工作。
-
也许我自己的问题对你有用:stackoverflow.com/questions/38265922/…
标签: python-3.x keras lstm recurrent-neural-network variable-length