您如何使用LSTM模型预测未来的预测?

时间:2020-05-08 22:34:13

标签: python machine-learning deep-learning lstm recurrent-neural-network

您如何使用此模型预测未来价值?我尝试将时间步长窗口更改为大于股票数据库的更高值,但是我只得到一个错误,说元组索引超出范围。如何预测未来的价值,而不是对现有数据测试模型?这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset_train = pd.read_csv(r'/path', error_bad_lines = False)
training_set = dataset_train.iloc[:, 1:2].values

from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
sc_training_set = sc.fit_transform(training_set)

X_train = []
y_train = []
for i in range (1, 220):
    X_train.append(sc_training_set[i-1:i, 0])
    y_train.append(sc_training_set[i, 0])

X_train, y_train = np.array(X_train), np.array(y_train)

X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout

regressor = Sequential()

regressor.add(LSTM(units = 64, return_sequences = True, input_shape = (X_train.shape[1], 1)))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 128, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 256, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 512, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 256, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 128, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 64))
regressor.add(Dropout(0.2))

regressor.add(Dense(units = 1))

regressor.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics = ['accuracy'])

regressor.fit(X_train, y_train, epochs = 10, batch_size = 32)

dataset_test = []
X_test = []

for i in range(220, 500):
    X_test.append(sc_training_set[i-1:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

pred_stock = regressor.predict(X_test)
pred_stock = sc.inverse_transform(pred_stock)

2 个答案:

答案 0 :(得分:1)

以下是一些用于将来预测的伪代码。本质上,您需要将最新的预测不断添加到时间序列中。

您不能只是增加时间步长,否则最终将试图访问超出范围的索引。

predictions = []
last_x = (the last x value in your data)
while len(predictions) < #_of_predictions_you_want:
    p = model.predict(last_x)
    predictions.append(p)
    last_x = np.roll(x, -1)
    last_x[-1] = p

答案 1 :(得分:1)

也许您可以将其添加到肖恩的答案中

last_x = np.reshape(len(last_x),1,1)

为了完整起见,

 predictions = []
    last_x = (the last x value in your data)
    last_x=np.reshape(len(last_x),1,1)
    while len(predictions) < #_of_predictions_you_want:
        p = model.predict(last_x)
        predictions.append(p)
        last_x = np.roll(x, -1)
        last_x[-1] = p
        last_x=np.reshape(len(last_x),1,1)