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

2024-04-24 23:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我在训练和保存完整模型之前的代码:

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


Tags: the代码模型layersizebatchfunctiontrain
1条回答
网友
1楼 · 发布于 2024-04-24 23:31:22

好吧,你需要一个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)

所以,很明显,您只创建了一个步骤的序列,这意味着您的LSTM根本没有学习序列。(没有只有一步的顺序)。

假设您的数据是一个具有1个特性的唯一序列,那么它的形状肯定应该是(1, len(x_train), 1)

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

反过来,这就要求LSTM层是return_sequences=True这是使y具有步长的唯一方法。此外,为了有一个好的预测,你可能需要一个更复杂的模型(因为现在它将是真正的学习)。

这样做,你训练你的模型,直到你得到一个满意的结果。


预测未来

为了预测未来,需要stateful=TrueLSTM层。

在任何事情之前,您都要重置模型的状态: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

相关问题 更多 >