用pytorch实现lstm模型预测单时间序列,输入为序列,输出为预测值
时间: 2023-06-14 19:03:56 浏览: 175
好的,以下是一个使用 PyTorch 实现 LSTM 模型进行单时间序列预测的示例代码:
```python
import torch
import torch.nn as nn
import numpy as np
# 定义 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]
# 准备数据
def prepare_data(seq, input_size):
X, Y = [], []
for i in range(len(seq)-input_size-1):
x = seq[i:i+input_size]
y = seq[i+input_size]
X.append(x)
Y.append(y)
return torch.tensor(X, dtype=torch.float32), torch.tensor(Y, dtype=torch.float32)
# 定义超参数
input_size = 7 # 输入序列长度,这里设置为7
hidden_size = 32 # 隐藏层大小
output_size = 1 # 输出序列长度,这里设置为1
lr = 0.01 # 学习率
num_epochs = 100 # 训练轮数
# 加载数据
data = np.loadtxt('data.csv', delimiter=',')
train_data = data[:100]
test_data = data[100:]
train_X, train_Y = prepare_data(train_data, input_size)
test_X, test_Y = prepare_data(test_data, input_size)
# 初始化模型和优化器
model = LSTM(input_size, hidden_size, output_size)
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
criterion = nn.MSELoss()
# 开始训练
for epoch in range(num_epochs):
# 将模型切换到训练模式
model.train()
# 计算训练损失
train_loss = 0.0
for i in range(len(train_X)):
optimizer.zero_grad()
output = model(train_X[i])
loss = criterion(output, train_Y[i])
loss.backward()
optimizer.step()
train_loss += loss.item()
# 将模型切换到评估模式
model.eval()
# 计算测试损失
test_loss = 0.0
with torch.no_grad():
for i in range(len(test_X)):
output = model(test_X[i])
loss = criterion(output, test_Y[i])
test_loss += loss.item()
# 打印训练和测试损失
print('Epoch [{}/{}], Train Loss: {:.4f}, Test Loss: {:.4f}'.format(epoch+1, num_epochs, train_loss/len(train_X), test_loss/len(test_X)))
# 使用模型进行预测
with torch.no_grad():
prediction = []
inputs = torch.tensor(test_data[:input_size], dtype=torch.float32)
for i in range(len(test_data)-input_size):
output = model(inputs)
prediction.append(output.item())
inputs = torch.cat((inputs[1:], output))
# 打印预测结果
print('Prediction: ', prediction)
```
这个示例代码中,我们使用了一个 LSTM 模型,将输入序列的长度设置为 7,隐藏层大小为 32,输出序列长度为 1。在训练过程中,我们使用均方误差作为损失函数,Adam 优化器进行优化。在训练结束后,我们使用训练好的模型进行预测,并将预测结果打印出来。
阅读全文