生活随笔
收集整理的這篇文章主要介紹了
LSTM股票价格预测
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
特征縮放:
1歸一化
X-Xmin/(Xmax-Xmin) (0,1)
2標(biāo)準(zhǔn)化
X-均值/期望
7個時間步 最后預(yù)測第八天的收盤價格 即圖中的y
def forward(self
, x
):h_0
= Variable
(torch
.zeros
(self
.num_layers
, x
.size
(0), self
.hidden_size
))c_0
= Variable
(torch
.zeros
(self
.num_layers
, x
.size
(0), self
.hidden_size
))'''送進來的每條樣本都生成記憶單元向 量(層數(shù),樣本數(shù)量,記憶單元長度)(1,724*0.7,5)'''_
, (h_out
, _
) = self
.lstm
(x
, (h_0
, c_0
)) h_out
= h_out
.view
(-1, self
.hidden_size
)out
= self
.fc
(h_out
)return out
'''_
, (h_out
, _
) = self
.lstm
(x
, (h_0
, c_0
)) h_out
= h_out
.view
(-1, self
.hidden_size
)out
= self
.fc
(h_out
)return out
'''
This script shows how to predict stock prices using a basic RNN
'''
import torch
import torch
.nn
as nn
from torch
.autograd
import Variable
import numpy
as nptorch
.manual_seed
(777) import matplotlib
.pyplot
as plt
def MinMaxScaler(data
):numerator
= data
- np
.min(data
, 0)denominator
= np
.max(data
, 0) - np
.min(data
, 0)return numerator
/ (denominator
+ 1e-7)
learning_rate
= 0.01
num_epochs
= 500
input_size
= 5
hidden_size
= 5
num_classes
= 1
timesteps
= seq_length
= 7
num_layers
= 1
xy
= np
.loadtxt
('data-02-stock_daily.csv', delimiter
=',')
xy
= xy
[::-1]
xy
= MinMaxScaler
(xy
)
x
= xy
y
= xy
[:, [-1]]
dataX
= []
dataY
= []
for i
in range(0, len(y
) - seq_length
):_x
= x
[i
:i
+ seq_length
] _y
= y
[i
+ seq_length
] print(_x
, "->", _y
)dataX
.append
(_x
)dataY
.append
(_y
)
train_size
= int(len(dataY
) * 0.7)
test_size
= len(dataY
) - train_size
trainX
= torch
.Tensor
(np
.array
(dataX
[0:train_size
]))
trainX
= Variable
(trainX
)
testX
= torch
.Tensor
(np
.array
(dataX
[train_size
:len(dataX
)]))
testX
= Variable
(testX
)
trainY
= torch
.Tensor
(np
.array
(dataY
[0:train_size
]))
trainY
= Variable
(trainY
)
testY
= torch
.Tensor
(np
.array
(dataY
[train_size
:len(dataY
)]))
testY
= Variable
(testY
)class LSTM(nn
.Module
):def __init__(self
, num_classes
, input_size
, hidden_size
, num_layers
):super(LSTM
, self
).__init__
()self
.num_classes
= num_classesself
.num_layers
= num_layersself
.input_size
= input_sizeself
.hidden_size
= hidden_sizeself
.seq_length
= seq_lengthself
.lstm
= nn
.LSTM
(input_size
=input_size
, hidden_size
=hidden_size
,num_layers
=num_layers
, batch_first
=True)self
.fc
= nn
.Linear
(hidden_size
, num_classes
)def forward(self
, x
):h_0
= Variable
(torch
.zeros
(self
.num_layers
, x
.size
(0), self
.hidden_size
))c_0
= Variable
(torch
.zeros
(self
.num_layers
, x
.size
(0), self
.hidden_size
))'''送進來的每條樣本都生成記憶單元向 量(層數(shù),樣本數(shù)量,記憶單元長度)(1,724*0.7,5)'''_
, (h_out
, _
) = self
.lstm
(x
, (h_0
, c_0
)) h_out
= h_out
.view
(-1, self
.hidden_size
)out
= self
.fc
(h_out
)return out
lstm
= LSTM
(num_classes
, input_size
, hidden_size
, num_layers
)
criterion
= torch
.nn
.MSELoss
()
optimizer
= torch
.optim
.Adam
(lstm
.parameters
(), lr
=learning_rate
)
for epoch
in range(num_epochs
):outputs
= lstm
(trainX
)optimizer
.zero_grad
()loss
= criterion
(outputs
, trainY
)loss
.backward
()optimizer
.step
()print("Epoch: %d, loss: %1.5f" % (epoch
, loss
.item
()))print("Learning finished!")
lstm
.eval()
t est_predict
= lstm
(testX
)
test_predict
= test_predict
.data
.numpy
()
testY
= testY
.data
.numpy
()
plt
.plot
(testY
,c
='y')
plt
.plot
(test_predict
,c
='b')
print(testY
.shape
)
print(test_predict
.shape
)
plt
.xlabel
("Time Period")
plt
.ylabel
("Stock Price")
plt
.show
()
總結(jié)
以上是生活随笔為你收集整理的LSTM股票价格预测的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。