gorm 密码字段隐藏_【财富密码】第1期:《LSTM大战上证指数-PyTorch版》
前言: Hello大家好,我是瑟林洞仙人!這里是【財富密碼】系列第1期:《LSTM大戰上證指數-PyTorch版》。在這里,我將用我的“意識流”代碼,手把手教會大家如何在資本市場里被割韭菜。何為“意識流”代碼,簡單來說,就是忘掉內存管理、忘掉代碼規范、忘掉性能、忘掉測試,一路奔向需求的最終目標,逢山開路,遇水架橋。別問為啥,問就是:快!在線等!挺急的!
需求內容
一句話: 使用LSTM(長短期記憶網絡)模型對單變量時間序列進行多期預測。
使用方法
將數據文件(2020.csv)和代碼(lstm_series.py)放入同一位置下,在配置好的環境下使用IDE或CMD運行皆可。
鏈接:https://pan.baidu.com/s/1cjwRLoj6eJ0b0w0weTvGLQ 提取碼:l903
通過觀察源碼的參數調節區域:
torch.manual_seed(10086) # 為CPU設置隨機種子 model = LSTM(input_size=1, num_units=16, output_size=1, num_layers=1) max_epochs = 10000 train_window = 10 optimizer = torch.optim.Adam(model.parameters(), lr=1e-4) future_steps = 30 # 向后預測時間長度測試用例中為完全復現神經網絡的訓練結果,已設定了一個隨機種子(該樣例及種子需要訓練1327次達到誤差目標)。在該LSTM樣例模型中,輸入輸出特征維度數均為1。隱藏層數為1和單層節點數為16,除輸入輸出特征維度數外,其余參數均可調節。
至于訓練的“滑動窗口”大小、學習率等參數,乃至目標誤差等等我都是隨便選的,千萬別真拿去割韭菜,就這個模型,調參調得再好也不行,以后我會專門講原因。
環境配置
- Python3.6
Windows64位參考:https://www.python.org/ftp/python/3.6.8/python-3.6.8-amd64.exe
- numpy 1.19.0
這個隨便,pip install numpy即可
- pandas 0.25.3
pip install pandas==0.25.3
- torch 1.4.0+cpu & torchvision 0.5.0
玩具代碼CPU跑跑算了(主要是窮)。pip下載可能很慢,建議找鏡像。
win64位備份:https://pan.baidu.com/s/1yrGIhXHopkftBdR5qsTkAg 提取碼:d3sa
- matplotlib 3.2.2
畫圖,pip install matplotlib即可
- scikit-learn 0.23.1
用于數據歸一化處理,pip install scikit-learn即可
- openpyxl 3.0.3
用于將預測結果寫入Excel,pip install openyxl即可
- 其他
其他依賴環境scipy、Pillow等等,已在上述pip過程包含,無需重復安裝。
完整代碼
import os import sys import numpy as np import pandas as pd import torch from torch import nn import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScalerpath = os.chdir(sys.path[0]) sys.path.append(path)# 定義LSTM神經網絡模型 class LSTM(nn.Module):"""Parameters:- input_size: 輸入特征數- num_units: 單個隱藏層的節點數- output_size: 輸出特征數- num_layers: 隱藏層數"""def __init__(self, input_size=1, num_units=1, output_size=1, num_layers=1):super().__init__()self.input_size = input_sizeself.num_units = num_unitsself.num_layers = num_layersself.output_size = output_sizeself.lstm = nn.LSTM(input_size, num_units, num_layers)self.forwardCalculation = nn.Linear(num_units, output_size)self.hidden_cell = (torch.zeros(self.num_layers,self.output_size,self.num_units),torch.zeros(self.num_layers,self.output_size,self.num_units))def forward(self, input_seq):L = len(input_seq)lstm_out, self.hidden_cell = self.lstm(input_seq.view(L, 1, -1),self.hidden_cell)predictions = self.forwardCalculation(lstm_out.view(len(input_seq), -1))return predictions[-1]# 用于從表格文件導入數據 def excel_import(input_file, col):"""Parameters:- input_file: 導入文件名(例如'data.csv')- col: 導入列名"""if '.xls' in input_file:in_df = pd.read_excel(input_file, sheet_name=0, header=0, encoding='gbk')elif '.csv' in input_file:in_df = pd.read_csv(input_file, sep=',', header=0, encoding='gbk')else:print('請確認文件格式或是否存在!')exit()data_import = in_df.as_matrix(columns=col)return data_import# 構造訓練數據集 def create_inout_sequences(input_data, tw):"""Parameters:- input_data: 訓練數據源- tw: 訓練窗口大小"""inout_seq = []L = len(input_data)for i in range(L-tw):train_seq = input_data[i:i+tw]train_label = input_data[i+tw:i+tw+1]inout_seq.append((train_seq ,train_label))return inout_seq# 程序運行入口 if __name__ == '__main__':# --------------------------- 數據導入 ----------------------------- #input_file = "2020.csv" # 表文件名col = ['price'] # 列字段名dataset = excel_import(input_file, col).astype('float16')# ----------------------------------------------------------------- #data_len = len(dataset)t = range(data_len)scaler = MinMaxScaler(feature_range=(-1, 1))dataset_lst = scaler.fit_transform(dataset .reshape(-1, 1))# 序列觀察"""plt.figure()plt.plot(t, dataset_lst, label="y = "+col[-1])plt.legend(loc='upper right')plt.show()"""# ---------------------------- 調參區 ------------------------------ #torch.manual_seed(10086) # 為CPU設置隨機種子model = LSTM(input_size=1, num_units=16, output_size=1, num_layers=1)max_epochs = 10000train_window = 10optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)future_steps = 30 # 向后預測時間長度print('LSTM model:', model)# ----------------------------------------------------------------- #dataset_n = torch.FloatTensor(dataset_lst).view(-1) # To Tensortrain_inout_seq = create_inout_sequences(dataset_n, train_window)loss_function = nn.MSELoss()t_test = range(train_window, data_len)ts, ys = [], []for epoch in range(max_epochs):yhat = []for seq, labels in train_inout_seq:optimizer.zero_grad()model.hidden_cell=(torch.zeros(model.num_layers,model.output_size,model.num_units),torch.zeros(model.num_layers,model.output_size,model.num_units))output = model(seq)loss = loss_function(output, labels)loss.backward()optimizer.step()yhat.extend(output.view(-1, 1).data.numpy())if loss.item() < 1e-6:print('Epoch [{}/{}], Loss: {:.6f}'.format(epoch+1, max_epochs, loss.item()))print("The loss value is reached")breakelse:ts.append(epoch+1)ys.append(loss.item())print('Epoch [{}/{}], Loss: {:.6f}'.format(epoch+1, max_epochs, loss.item()))"""# GIF-LOSSplt.ion()plt.figure(1)plt.clf()plt.plot(ts, ys,'-r')plt.draw()plt.pause(0.01)# GIF-MODELplt.figure(2)plt.clf()plt.plot(t, dataset_lst, 'b', label='y')plt.plot(t_test, yhat, 'm--', label='yhat')plt.legend(loc='upper left')plt.pause(0.01)"""torch.save(model.state_dict(), 'model.pkl') # 模型保存# model.load_state_dict(torch.load('model.pkl')) # 模型載入# ---------------------------- 預測區 ------------------------------ #predict_base = dataset_n[-train_window:].tolist()model = model.eval()for i in range(future_steps):seq = torch.FloatTensor(predict_base[-train_window:])with torch.no_grad():predict_base.append(model(seq).item())t_future = range(data_len, data_len+future_steps)future = predict_base[-future_steps:]actual_predictions = scaler.inverse_transform(np.array(future).reshape(-1, 1))# ----------------------------------------------------------------- #plt.figure(3)plt.plot(t, dataset_lst, 'b', label='y')plt.plot(t_future, future, 'm--', label='predictions')plt.savefig('figure_results.png')plt.figure(4)plt.plot(ts, ys,'-r')plt.savefig('figure_loss.png')future_results = pd.DataFrame(actual_predictions)excelwriter = pd.ExcelWriter('prediction.xlsx')future_results.to_excel(excelwriter,'Sheet1',encoding='gbk')excelwriter.save() 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的gorm 密码字段隐藏_【财富密码】第1期:《LSTM大战上证指数-PyTorch版》的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言 | 内存对齐01 - 什么是内存
- 下一篇: thinkphp跨库操作代码实例