这是我训练完整模型并保存它的代码:
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')
在那之后,我看到大多数时候人们建议使用测试数据集来检查我也尝试过的预测并获得了良好的结果。
但问题出在我创建的模型的使用上。我想获得 future 30 天或每一分钟的预测。现在我有了训练有素的模型,但我不知道我能做什么或我使用什么代码来使用该模型并预测接下来 30 天或一分钟的价格。
请告诉我出路。一个星期以来,我一直被这个问题困住,无法做出任何成功的尝试。
这是存储库的链接,您可以在其中找到完整的可运行代码、模型和数据集:My repository link
最佳答案
那么,您需要一个 stateful=True
模型,这样您就可以一个接一个地为它提供一个预测以获得下一个预测,并让模型认为每个输入不是新序列,而是续集到上一个。
修复代码和训练
我在代码中看到有人试图让您的 y
成为一个 shifte 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
具有步进长度的唯一方法。此外,为了获得良好的预测,您可能需要一个更复杂的模型(因为现在它将是真正的学习)。
完成后,您将训练您的模型,直到获得满意的结果。
预测 future
为了预测 future ,您将需要 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 特征序列、移动的 future 步骤预测以及与此答案略有不同但基于相同原理的方法来执行此操作。
我创建了两个模型(一个 stateful=False
,用于训练而无需每次都重置状态 - 永远不要忘记在开始新序列时重置状态 - 另一个 stateful=True
,从训练好的模型中复制权重,用于预测 future )
https://github.com/danmoller/TestRepo/blob/master/TestBookLSTM.ipynb
关于python - 如何使用 Keras RNN 模型预测 future 的日期或事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760472/