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

Jaf*_*son 12 python keras

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

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')
Run Code Online (Sandbox Code Playgroud)

在那之后,我已经看到大多数时候人们建议测试数据集来检查我已经尝试过的预测并获得了良好的结果.

但问题在于我创建的模型的使用.我希望对未来30天或每分钟做出预测.现在我有经过训练的模型,但我没有得到我能做的或者我用什么代码来使用模型并预测未来30天或一分钟的价格.

请建议我出路.我被困在这个问题一个星期,并没有能够做任何成功的尝试.

这是存储库的链接,可以找到完整的可运行代码,模型和数据集: 我的存储库链接

Dan*_*ler 14

好吧,你需要一个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))
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

此代码使用2特征序列,移位的未来步骤预测和与此答案略有不同的方法,但基于相同的原理.

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

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