pytorch 建立lstm预测价格
时间: 2023-06-29 16:04:51 浏览: 104
以下是使用 PyTorch 建立 LSTM 模型预测价格的示例代码:
```python
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 加载数据
data = pd.read_csv('data.csv', usecols=[1])
dataset = data.values
dataset = dataset.astype('float32')
# 划分训练集和测试集
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train_data, test_data = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
# 创建数据集函数,用于将时间序列数据转化为有监督学习数据
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
# 定义超参数
look_back = 3
hidden_size = 4
learning_rate = 0.01
epochs = 1000
# 转化为有监督学习数据集
trainX, trainY = create_dataset(train_data, look_back)
testX, testY = create_dataset(test_data, look_back)
# 转化为张量
trainX = torch.from_numpy(trainX)
trainY = torch.from_numpy(trainY)
testX = torch.from_numpy(testX)
testY = torch.from_numpy(testY)
# 定义 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.linear = nn.Linear(hidden_size, output_size)
def forward(self, input):
lstm_out, _ = self.lstm(input.view(len(input), 1, -1))
predictions = self.linear(lstm_out.view(len(input), -1))
return predictions[-1]
# 实例化模型
input_size = 1
output_size = 1
lstm = LSTM(input_size, hidden_size, output_size)
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(lstm.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(epochs):
outputs = lstm(trainX.float())
optimizer.zero_grad()
loss = criterion(outputs, trainY.float())
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
# 测试模型
lstm.eval()
train_predict = lstm(trainX.float())
test_predict = lstm(testX.float())
# 反归一化
train_predict = train_predict.detach().numpy()
test_predict = test_predict.detach().numpy()
trainY = trainY.numpy()
testY = testY.numpy()
train_predict = train_predict * 100
trainY = trainY * 100
test_predict = test_predict * 100
testY = testY * 100
# 绘制预测结果
plt.plot(trainY)
plt.plot(train_predict)
plt.plot(range(train_size,len(dataset)),testY)
plt.plot(range(train_size,len(dataset)),test_predict)
plt.show()
```
在上述代码中,我们首先加载数据并将其划分为训练集和测试集。然后,我们创建了一个函数,用于将时间序列数据转化为有监督学习数据。接着,我们定义了超参数,包括往前看的时间步数、LSTM 隐藏层大小、学习率和训练轮数。我们使用了 PyTorch 的 nn.Module 类创建 LSTM 模型,其中包含一个 LSTM 层和一个线性层。然后,我们定义了损失函数和优化器,并使用训练数据训练模型。最后,我们使用测试数据测试模型,并将预测结果可视化。
阅读全文