lstm时间序列预测pytorch代码
时间: 2023-09-22 08:05:58 浏览: 115
下面是一个基于PyTorch的LSTM时间序列预测代码示例:
```
import torch
import torch.nn as nn
import numpy as np
# 数据准备
data = np.sin(np.arange(0, 1000, 0.1))
train_data = data[:800]
test_data = data[800:]
# 定义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, input):
lstm_out, _ = self.lstm(input.view(len(input), 1, -1))
out = self.fc(lstm_out.view(len(input), -1))
return out[-1]
# 模型训练
input_size = 1
hidden_size = 10
output_size = 1
lr = 0.01
epochs = 100
model = LSTM(input_size, hidden_size, output_size)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
for epoch in range(epochs):
inputs = torch.from_numpy(train_data[:-1]).float()
labels = torch.from_numpy(train_data[1:]).float()
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print(f'Epoch: {epoch}, Loss: {loss.item()}')
# 模型测试
model.eval()
test_inputs = torch.from_numpy(test_data[:-1]).float()
test_labels = torch.from_numpy(test_data[1:]).float()
test_outputs = model(test_inputs)
# 可视化结果
import matplotlib.pyplot as plt
plt.plot(test_data[1:])
plt.plot(test_outputs.detach().numpy())
plt.legend(['True', 'Predicted'])
plt.show()
```
在这个示例中,我们首先准备了一组正弦波数据,然后定义了一个LSTM模型,并使用均方误差作为损失函数和Adam优化器进行训练。最后,我们使用模型对测试数据进行预测,并使用matplotlib进行可视化。
阅读全文