skka3134

skka3134

email
telegram

機器學習和量化投資:2.處理資料

  1. 加載訓練的數據
import pandas as pd
data=pd.read_csv('data.csv')
  1. 特徵工程,我們需要其中的 Time 和 Close
data = data[['Time', 'Close']]
  1. 安裝 matplotlib
sudo /home/skka3134/folder/bot/bin/python -m pip install matplotlib
  1. 使用 matplotlib,根據日期和收盤價繪製曲線圖,matplotlib 是一個 2D 繪圖庫。
import matplotlib.pyplot as plt
plt.plot(data['Time'],data['Close'])
plt.show()

image
5. 為神經網絡 LSTM 準備一個數據框。RNN 是一種使用序列數據或時序數據的人工神經網絡。 LSTM 是一種特殊的 RNN,主要是為了解決長序列訓練過程中的梯度消失和梯度爆炸問題。

from copy import deepcopy as dc
def prepare_dataframe_for_lstm(df, n_steps):
    df = dc(df)
    
    df.set_index('Time', inplace=True)
    
    for i in range(1, n_steps+1):
        df[f'Close(t-{i})'] = df['Close'].shift(i)
        
    df.dropna(inplace=True)
    
    return df

lookback = 7
shifted_df = prepare_dataframe_for_lstm(data, lookback)

image
6. 將其轉換成 numpy

shifted_df = prepare_dataframe_for_lstm(data, lookback)
shifted_df_as_np = shifted_df.to_numpy()

image
7. 安裝 sklearn,我們需要用到 sklearn 裡面的 MinMaxScaler 進行數據縮放,減小誤差。

sudo /home/skka3134/folder/bot/bin/python -m pip install Scikit-Learn
  1. 縮放到 - 1 到 1 之間,再反縮放回去
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(-1, 1))
shifted_df_as_np = scaler.fit_transform(shifted_df_as_np)

image
9. 製作輸入 X,和輸出 Y

X = shifted_df_as_np[:, 1:]
y = shifted_df_as_np[:, 0]
X = dc(np.flip(X, axis=1))

image
10. 分割 X,用前百分之 95 進行訓練,後百分之幾 5 進行測試

split_index = int(len(X) * 0.95)
  1. 重塑
X_train = X[:split_index]
X_test = X[split_index:]
y_train = y[:split_index]
y_test = y[split_index:]

X_train = X_train.reshape((-1, lookback, 1))
X_test = X_test.reshape((-1, lookback, 1))
y_train = y_train.reshape((-1, 1))
y_test = y_test.reshape((-1, 1))

X_train = torch.tensor(X_train).float()
y_train = torch.tensor(y_train).float()
X_test = torch.tensor(X_test).float()
y_test = torch.tensor(y_test).float()
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。