有没有pytorch 架构的多步预测例子
时间: 2023-08-30 17:10:29 浏览: 76
基于pytorch的LSTM多变量多输出时间序列预测使用例
5星 · 资源好评率100%
当涉及到时间序列预测时,多步预测是一项重要的任务。以下是一个基于PyTorch框架的多步预测的例子:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# 定义模型类
class MultiStepPredictor(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers=1):
super(MultiStepPredictor, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x, future=0):
# x: (batch_size, seq_len, input_size)
batch_size = x.size(0)
seq_len = x.size(1)
h0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(x.device)
output, _ = self.lstm(x, (h0, c0))
output = output[:, -1, :]
predictions = []
for i in range(future):
output = output.unsqueeze(1)
output, (h0, c0) = self.lstm(output, (h0, c0))
output = self.fc(output[:, -1, :])
predictions.append(output)
return torch.cat(predictions, dim=1)
# 定义超参数
input_size = 1
hidden_size = 64
output_size = 1
num_layers = 2
learning_rate = 0.01
num_epochs = 1000
future = 10
# 定义数据集
data = np.sin(np.arange(1000) * (np.pi / 50))
data = data.reshape(-1, 1)
data = torch.from_numpy(data).float().to(torch.device('cuda'))
# 划分训练集和测试集
train_data = data[:-100]
test_data = data[-100:]
# 定义模型、损失函数和优化器
model = MultiStepPredictor(input_size, hidden_size, output_size, num_layers).to(torch.device('cuda'))
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
optimizer.zero_grad()
x_train = train_data[:-future]
y_train = train_data[future:]
y_pred = model(x_train, future=future)
loss = criterion(y_pred, y_train)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print("Epoch [{}/{}], Loss: {:.4f}".format(epoch, num_epochs, loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
x_test = test_data[:-future]
y_test = test_data[future:]
y_pred = model(x_test, future=future)
loss = criterion(y_pred, y_test)
print("Test Loss: {:.4f}".format(loss.item()))
# 可视化结果
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
plt.plot(y_test.cpu().numpy().flatten(), label='True Data')
plt.plot(y_pred.cpu().numpy().flatten(), label='Predictions')
plt.legend()
plt.show()
```
在此示例中,我们使用`nn.LSTM`来构建LSTM模型,使用`nn.Linear`来构建全连接层,使用`nn.MSELoss`作为损失函数,使用`optim.Adam`作为优化器。我们使用`sine`函数作为我们的数据,并将其转换为PyTorch张量。我们将前900个值用于训练,后100个值用于测试。最后,我们将训练和测试结果可视化。
阅读全文