【发布时间】:2018-12-03 01:43:33
【问题描述】:
我正在学习如何在 Keras 中使用 LSTM 模型。我看过这个answer 和这个answer,并想以多对多的方式训练模型,但在测试时使用 stateful=True 的一对多进行预测。我不确定我是否走在正确的轨道上。
我有一个包含 10,000 个人的数据集,每个人都有 20 个时间步长和 10 个特征的序列。我想训练一个 LSTM 模型来预测下一个时间步的 5 个特征,使用 90-10 的训练和测试拆分,我的 train_x 的形状为 (9,000, 20, 10),我的 train_y 的形状为 (9,000, 20, 5 ) 其中 y 中的值是下一个时间步中所选特征的值。我的 test_x 的形状为 (1,000, 20, 10)。
在测试时,我想使用经过训练的模型在序列的最开始(时间步 0)仅使用 10 个特征进行预测。首先在下一个时间步预测所选 5 个特征的值。下一个时间步长中其他 5 个特征的值是已知的,因此我想将它们与预测的 5 个特征结合起来,并再次使用它作为输入来预测下一个时间步长中的 5 个特征,依此类推 20 个步骤。
是否可以使用 Keras 库来做到这一点?
我的训练代码看起来像
t_model = Sequential()
t_model.add(LSTM(100, return_sequence=True,
input_shape=(train_x.shape[1],
train_x.shape[2])))
t_model.add(TimeDistributed(Dense(5))
t_modle.compile(loss='mean_squared_error',
optimizer='adam')
checkpointer = ModelCheckpoint(filepath='weights.hdf5',
verbose=1,
save_best_only=True)
history = t_model.fit(train_x, train_y, epochs=50,
validation_split=0.1, callbacks=[checkpointer],
verbose=2, shuffle=False)
这似乎训练好。如果我构建模型的方式有任何误解,请告诉我。
我的测试代码看起来像
p_model = Sequential()
p_model.add(LSTM(100, stateful=True,
return_sequences=True,
batch_input_shape=(1, 1,
test_x.shape[2])))
p_model.add(TimeDistributed(Dense(5)))
p_model.load_weights('weights.hdf5')
complete_yhat = np.empty([0, 5])
for i in range(len(test_x):
ind = test_x[i]
x = ind[0]
x = x.reshape(1, 1, x.shape[0])
for j in range(20):
yhat = p_model.predict(x)
complete_yhat = np.append(complete_yhat, yhat[0], axis=0)
if j < 19:
x = ind[j+1]
x = np.append([x[:-5]], yhat[0], axis=1)
x = x.reshape(1, x.shape[0], x.shape[1])
p_model.reset_states()
这运行正常,但我很难获得良好的预测准确性。有人可以让我知道我是否正确使用 Keras LSTM 吗?
感谢您的帮助
【问题讨论】:
标签: python tensorflow keras