iT邦幫忙

0

LSTM 如何做多步 預測

  • 分享至 

  • xImage

想請問各位大神:
如果今天為t ,過去天數為t-1、t-2...t-n以此類推,想預測未來天數t+1、t+2...t+n該怎麼做呢?
是類似第一個網站這樣,監督式的概念呢
https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/

還是就像第二個網站,將LSTM的模型改成多對多的方式就是了呢?
https://medium.com/@daniel820710/%E5%88%A9%E7%94%A8keras%E5%BB%BA%E6%A7%8Blstm%E6%A8%A1%E5%9E%8B-%E4%BB%A5stock-prediction-%E7%82%BA%E4%BE%8B-1-67456e0a0b

以下是我練習的範例:
參考至
https://wenwender.wordpress.com/2019/10/18/%E5%AF%A6%E4%BD%9C%E9%80%8F%E9%81%8Elstm%E9%A0%90%E6%B8%AC%E8%82%A1%E7%A5%A8/

pip install FinMind

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

#2330:TSMC
from FinMind.Data import Load
TaiwanStockInfo = Load.FinData(dataset = 'TaiwanStockInfo')
data = Load.FinData(dataset = 'TaiwanStockPrice',select = '2330',date = '2020-01-01')

data.head()

fig=plt.figure(figsize=(20,8))
plt.xticks(rotation = 90)  
ax1 = fig.add_subplot(111)
ax1.plot(data.close,color='red',label='close')
ax1.plot(data.open,color='green',label='open')
plt.legend()
# twin 為共享x軸
ax2= ax1.twinx()
plt.bar(data.date,data.Trading_Volume.astype('int')//1000)
ax3 = ax1.twinx()
plt.savefig('2330_year.png')

#切分Test集
test = data[data.date>'2020-06-01']
train = data[:len(data)-len(test)]
#只要open high
train_set = train['open']
test_set = test['open']

from sklearn.preprocessing import MinMaxScaler 
sc = MinMaxScaler(feature_range = (0, 1))
#需將資料做reshape的動作,使其shape為(資料長度,1) 
train_set= train_set.values.reshape(-1,1)
training_set_scaled = sc.fit_transform(train_set)

#創建資料集
X_train = [] 
y_train = []
for i in range(10,len(train_set)):
    X_train.append(training_set_scaled[i-10:i-1, 0]) 
    y_train.append(training_set_scaled[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))
                         
print('第i天之前的股價')
print(X_train[0])
print('第i天的股價')
print(y_train[0])

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

keras.backend.clear_session()
regressor = Sequential()
regressor.add(LSTM(units = 100, input_shape = (X_train.shape[1], 1)))
regressor.add(Dense(units = 1))
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')

regressor.summary()

#只使用一層LSTM層
history = regressor.fit(X_train, y_train, epochs = 100, batch_size = 16)
plt.title('train_loss')
plt.ylabel('loss')
plt.xlabel('Epoch')
plt.plot( history.history["loss"])

dataset_total = pd.concat((train['open'], test['open']), axis = 0)
inputs = dataset_total[len(dataset_total) - len(test) - 10:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
X_test = []
for i in range(10, len(inputs)):
    X_test.append(inputs[i-10:i-1, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = regressor.predict(X_test)
#使用sc的 inverse_transform將股價轉為歸一化前
predicted_stock_price = sc.inverse_transform(predicted_stock_price)

plt.plot(test['open'].values, color = 'black', label = 'Real TSMC Stock Price')
plt.plot(predicted_stock_price, color = 'green', label = 'Predicted TSMC Stock Price')
plt.title('TATA Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
# plt.savefig('lstm_2330.png')
fillano iT邦超人 1 級 ‧ 2020-08-04 14:34:53 檢舉
...你練習的結果沒有預測出多步嗎?
liu1257cc iT邦新手 5 級 ‧ 2020-08-04 15:33:02 檢舉
這個範例 感覺應該是用t-n~t的數據,預測並劃出t+1的結果

應該就沒有說到,如何在往下推的樣子
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
a26833765
iT邦新手 5 級 ‧ 2020-08-04 15:53:34

之前回答過類似的問題
https://ithelp.ithome.com.tw/questions/10199357

這邊補充一下

  1. 第一個連結我看不出來有做到多步預測
  2. 第二個連結也沒看出來有多步預測,而且他還把資料順序打亂,我有點傻眼
  3. 第三個是多步預測,但沒有把你想要的代碼釋放出來,而且仔細看他最後兩張圖的結果,這已經是無效預測了,預測曲線只是在模仿目標曲線。多步預測最怕的就是預測結果只是在延遲性的模仿時係曲線,還有就是直接炸掉。

提供下面四個資料給你參考,希望對你有幫助
https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/
https://machinelearningmastery.com/multi-step-time-series-forecasting/
https://www.sciencedirect.com/science/article/abs/pii/S0960148117310364
https://ieeexplore.ieee.org/document/6137274

a26833765 iT邦新手 5 級 ‧ 2020-08-04 15:56:14 檢舉

最後兩個連結是採遞迴式多步預測,重點是文章內的圖,很清楚的說明遞迴式多步預測的概念。

還有,多步預測不拘泥在神經網路,任何預測模型都能用於多步預測

liu1257cc iT邦新手 5 級 ‧ 2020-08-04 16:44:22 檢舉

好的我去了解一下,不好意思剛學習,如有疑問能再問你嗎a26833765

a26833765 iT邦新手 5 級 ‧ 2020-08-04 16:49:05 檢舉

可以,再發信給我
a26833765@gmail.com

我要發表回答

立即登入回答