给出一段代码,使用pytorch,其中包含lstm模型用于预测股价
时间: 2023-03-29 19:02:24 浏览: 108
基于pytorch利用LSTM实现对股票价格预测源码+使用说明.zip
以下是使用 PyTorch 实现 LSTM 模型预测股价的代码示例:
```python
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# 加载数据
data = pd.read_csv('stock_data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(-1, 1))
data['Close'] = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
# 划分训练集和测试集
train_size = int(len(data) * .8)
train_data = data.iloc[:train_size]
test_data = data.iloc[train_size:]
# 定义 LSTM 模型
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
lstm_out, _ = self.lstm(x.view(len(x), 1, -1))
out = self.fc(lstm_out.view(len(x), -1))
return out[-1]
# 训练 LSTM 模型
input_size = 1
hidden_size = 32
output_size = 1
num_epochs = 100
learning_rate = .01
model = LSTM(input_size, hidden_size, output_size)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(num_epochs):
for i in range(len(train_data) - 1):
x = torch.Tensor(train_data['Close'].iloc[i:i+1].values)
y = torch.Tensor(train_data['Close'].iloc[i+1:i+2].values)
optimizer.zero_grad()
output = model(x)
loss = criterion(output, y)
loss.backward()
optimizer.step()
if (epoch+1) % 10 == :
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试 LSTM 模型
model.eval()
with torch.no_grad():
test_inputs = torch.Tensor(test_data['Close'].values)
test_outputs = []
for i in range(len(test_inputs)):
if i == :
model.hidden = (torch.zeros(1, 1, model.hidden_size),
torch.zeros(1, 1, model.hidden_size))
else:
model.hidden = (h.detach(), c.detach())
x = test_inputs[i]
output = model(x)
test_outputs.append(output.item())
# 反归一化
test_outputs = scaler.inverse_transform(np.array(test_outputs).reshape(-1, 1))
# 可视化预测结果
import matplotlib.pyplot as plt
plt.plot(data['Close'].values, label='True')
plt.plot(np.arange(train_size, len(data)), test_outputs, label='Predicted')
plt.legend()
plt.show()
```
希望这段代码能够帮助你实现 LSTM 模型预测股价。
阅读全文