如何使用Keras RNN模型预测未来的日期或事件?

问题描述 投票:12回答:1

这是我训练完整模型并保存它的代码:

num_units = 2
activation_function = 'sigmoid'
optimizer = 'adam'
loss_function = 'mean_squared_error'
batch_size = 10
num_epochs = 100

# Initialize the RNN
regressor = Sequential()

# Adding the input layer and the LSTM layer
regressor.add(LSTM(units = num_units, activation = activation_function, input_shape=(None, 1)))

# Adding the output layer
regressor.add(Dense(units = 1))

# Compiling the RNN
regressor.compile(optimizer = optimizer, loss = loss_function)

# Using the training set to train the model
regressor.fit(x_train, y_train, batch_size = batch_size, epochs = num_epochs)
regressor.save('model.h5')

[之后,我看到人们大多数时候都建议使用测试数据集来检查我也尝试过并获得良好结果的预测。

但是问题在于我创建的模型的使用。我想对未来30天或每分钟的天气预报。现在,我拥有训练有素的模型,但是无法获得所能做的事情或使用什么代码来使用该模型并无法预测未来30天或一分钟的价格。

请给我建议出路。一个星期以来,我一直陷在这个问题上,无法进行任何成功的尝试。

这里是存储库的链接,可以在其中找到完整的可运行代码,模型和数据集:My repository link

python keras
1个回答
13
投票
嗯,您需要一个stateful=True模型,因此您可以一个接一个地预测它以得到下一个预测,并使模型始终认为每个输入不是新序列,而是前一个的后继。

修复代码和培训

我在代码中看到,有人试图使您的y成为班次x(这是预测下一步的一个不错的选择)。但是这里的预处理也有一个大问题:

training_set = df_train.values training_set = min_max_scaler.fit_transform(training_set) x_train = training_set[0:len(training_set)-1] y_train = training_set[1:len(training_set)] x_train = np.reshape(x_train, (len(x_train), 1, 1))

LSTM层的数据必须成形为(number_of_sequences, number_of_steps,features)

因此,您显然仅创建1个步骤的序列,这意味着LSTM根本不学习序列。 (没有一个步骤,只有一个步骤)。

假设您的数据是具有1个功能的单个唯一序列,则应将其绝对定形为(1, len(x_train), 1)

自然,y_train也应具有相同的形状。

依次,这将要求您的LSTM层为return_sequences=True-使y具有一定长度的唯一方法。另外,为了获得良好的预测,您可能需要一个更复杂的模型(因为现在这将是真正的学习)。

完成后,您将训练模型,直到获得满意的结果。


预测未来

为了预测未来,您将需要stateful=True个LSTM层。

在进行任何操作之前,您都要重置模型的状态:model.reset_states()-每次将新序列输入到有状态模型中时都是必要的。

然后,您首先预测整个X_train(模型需要用它来理解它在序列的哪一点,用技术术语来说:创建状态)。

predictions = model.predict(`X_train`) #this creates states

最后,您将创建一个循环,从上一个预测的最后一步开始:

future = [] currentStep = predictions[:,-1:,:] #last step from the previous prediction for i in range(future_pred_count): currentStep = model.predict(currentStep) #get the next step future.append(currentStep) #store the future steps #after processing a sequence, reset the states for safety model.reset_states()


示例

此代码使用2个特征的序列,移位的未来步长预测以及与此答案稍有不同但基于相同原理的方法来完成此任务。

我创建了两个模型(一个stateful=False,用于训练而无需每次都重置状态-永远不要忘记在开始新序列时重置状态-另一个stateful=True,从训练后的模型中复制权重,用于预测未来)

https://github.com/danmoller/TestRepo/blob/master/TestBookLSTM.ipynb

© www.soinside.com 2019 - 2024. All rights reserved.