TShopping

 找回密碼
 註冊
搜索
查看: 879|回復: 0

[轉帖] 使用 Keras 搭建一個 LSTM 魔法陣(模型)

[複製鏈接]
發表於 2021-7-2 16:10:08 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
模型任務
預測股票趨勢(上漲/下跌)

資料集
  • 訓練集:2012 年 ~ 2016 年的 Google stock price(共 1258 天)
  • 測試集:2017 年 1 月的 Google stock price(共 20 天)
  • 資料長相:

Keras LSTM python

Keras   LSTM python



執行環境版本
Keras 2.1.5
Python 3.6.4
Step 1: 資料前處理
  • Load Data:

  1. # Import the libraries
  2. import numpy as np
  3. import matplotlib.pyplot as plt  # for 畫圖用
  4. import pandas as pd

  5. # Import the training set
  6. dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')  # 讀取訓練集
  7. training_set = dataset_train.iloc[:, 1:2].values  # 取「Open」欄位值
複製代碼

  • 做 Normalization,將資料壓縮在 [0,1] 之間:

    Keras LSTM python

    Keras   LSTM python


圖片來源:《Feature Engineering for Machine Learning》一書
  1. # Feature Scaling
  2. from sklearn.preprocessing import MinMaxScaler

  3. sc = MinMaxScaler(feature_range = (0, 1))
  4. training_set_scaled = sc.fit_transform(training_set)
複製代碼

  • 準備進入訓練的資料格式:設定 Timestep
    Timesteps 設為 60 ,代表過去 60 天的資訊,嘗試過數值設置太少,將使 RNN 無法學習。


  1. X_train = []   #預測點的前 60 天的資料
  2. y_train = []   #預測點
  3. for i in range(60, 1258):  # 1258 是訓練集總數
  4.     X_train.append(training_set_scaled[i-60:i, 0])
  5.     y_train.append(training_set_scaled[i, 0])
  6. X_train, y_train = np.array(X_train), np.array(y_train)  # 轉成numpy array的格式,以利輸入 RNN
複製代碼
  • Reshape
    因為現在 X_train 是 2-dimension,將它 reshape 成 3-dimension: [stock prices, timesteps, indicators]
    1. X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
    複製代碼




Step 2: 搭建一個 LSTM 魔法陣
  • import Keras

  1. # Import the Keras libraries and packages
  2. from keras.models import Sequential
  3. from keras.layers import Dense
  4. from keras.layers import LSTM
  5. from keras.layers import Dropout

  6. # Initialising the RNN
  7. regressor = Sequential()
複製代碼

  • 搭建 LSTM layer:
    • units: 神經元的數目
    • 第一層的 LSTM Layer 記得要設定input_shape參數
    • 搭配使用dropout,這裡設為 0.2
    • 由於這邊的第四層 LSTM Layer 即將跟 Ouput Layer 做連接,因此注意這邊的 return_sequences 設為預設值 False (也就是不用寫上 return_sequences)


  1. # Adding the first LSTM layer and some Dropout regularisation
  2. regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))
  3. regressor.add(Dropout(0.2))

  4. # Adding a second LSTM layer and some Dropout regularisation
  5. regressor.add(LSTM(units = 50, return_sequences = True))
  6. regressor.add(Dropout(0.2))

  7. # Adding a third LSTM layer and some Dropout regularisation
  8. regressor.add(LSTM(units = 50, return_sequences = True))
  9. regressor.add(Dropout(0.2))

  10. # Adding a fourth LSTM layer and some Dropout regularisation
  11. regressor.add(LSTM(units = 50))
  12. regressor.add(Dropout(0.2))
複製代碼

  • Ouput Layer: units 設為 1

  1. # Adding the output layer
  2. regressor.add(Dense(units = 1))
複製代碼

  • Compiling & Fitting LSTM model
    • optimizer: 選擇 Adam
    • loss: 使用 MSE


  1. # Compiling
  2. regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')

  3. # 進行訓練
  4. regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)
複製代碼

Keras LSTM python

Keras   LSTM python
Step 3: 進行預測
  • 取測試集中 2017 年的股票資料(真實)

  1. dataset_test = pd.read_csv('Google_Stock_Price_Test.csv')
  2. real_stock_price = dataset_test.iloc[:, 1:2].values
複製代碼

  • 取模型所預測的 2017 年股票資料(預測)

  1. dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)
  2. inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values
  3. inputs = inputs.reshape(-1,1)
  4. inputs = sc.transform(inputs) # Feature Scaling

  5. X_test = []
  6. for i in range(60, 80):  # timesteps一樣60; 80 = 先前的60天資料+2017年的20天資料
  7.     X_test.append(inputs[i-60:i, 0])
  8. X_test = np.array(X_test)
  9. X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))  # Reshape 成 3-dimension
複製代碼

  • 進行預測


  1. predicted_stock_price = regressor.predict(X_test)
  2. predicted_stock_price = sc.inverse_transform(predicted_stock_price)  # to get the original scale
複製代碼

  • 視覺化結果

  1. # Visualising the results
  2. plt.plot(real_stock_price, color = 'red', label = 'Real Google Stock Price')  # 紅線表示真實股價
  3. plt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price')  # 藍線表示預測股價
  4. plt.title('Google Stock Price Prediction')
  5. plt.xlabel('Time')
  6. plt.ylabel('Google Stock Price')
  7. plt.legend()
  8. plt.show()
複製代碼

Keras LSTM python

Keras   LSTM python
本次模型的任務是預測股票趨勢,由視覺化結果可以看出模型的預測表現,如預測的趨勢雖大致上跟真實股價是一致但預測的較為平滑。

文章出處

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-3-29 13:07 , Processed in 0.049228 second(s), 26 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表