0

## LSTM 如何做多步 預測

https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/

``````pip install FinMind

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

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

fig=plt.figure(figsize=(20,8))
plt.xticks(rotation = 90)
ax1.plot(data.close,color='red',label='close')
ax1.plot(data.open,color='green',label='open')
plt.legend()
# twin 為共享x軸
ax2= ax1.twinx()
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.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 檢舉

### 1 個回答

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

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

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

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

a26833765@gmail.com