当前位置:   article > 正文

单变量时间序列预测,可控输入输出步长

单变量时间序列预测,可控输入输出步长

我有一列数据想做时间序列预测,有30000+行,用pytorch框架完成,输入是(input_length)时间步,输出是(ouput_length)时间步,数据是csv文件,请帮我写一个框架,完成训练。

  1. import pandas as pd
  2. import torch
  3. import torch.nn as nn
  4. import torch.optim as optim
  5. from torch.utils.data import Dataset, DataLoader
  6. class TimeSeriesDataset(Dataset):
  7. def __init__(self, csv_file, input_length, output_length):
  8. self.data = pd.read_csv(csv_file)
  9. self.input_length = input_length
  10. self.output_length = output_length
  11. def __len__(self):
  12. return len(self.data) - self.input_length - self.output_length + 1
  13. def __getitem__(self, idx):
  14. input_data = self.data.iloc[idx:idx+self.input_length].values
  15. output_data = self.data.iloc[idx+self.input_length:idx+self.input_length+self.output_length].values
  16. return torch.tensor(input_data, dtype=torch.float), torch.tensor(output_data, dtype=torch.float)
  17. class TimeSeriesModel(nn.Module):
  18. def __init__(self, input_size, output_size, hidden_size, num_layers):
  19. super(TimeSeriesModel, self).__init__()
  20. self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
  21. self.fc = nn.Linear(hidden_size, output_size)
  22. def forward(self, x):
  23. lstm_out, _ = self.lstm(x)
  24. output = self.fc(lstm_out[:, -1, :])
  25. return output
  26. def train(model, train_loader, optimizer, criterion, device):
  27. model.train()
  28. train_loss = 0.0
  29. for inputs, targets in train_loader:
  30. inputs, targets = inputs.to(device), targets.to(device)
  31. optimizer.zero_grad()
  32. outputs = model(inputs)
  33. loss = criterion(outputs, targets)
  34. loss.backward()
  35. optimizer.step()
  36. train_loss += loss.item()
  37. return train_loss / len(train_loader)
  38. def validate(model, val_loader, criterion, device):
  39. model.eval()
  40. val_loss = 0.0
  41. with torch.no_grad():
  42. for inputs, targets in val_loader:
  43. inputs, targets = inputs.to(device), targets.to(device)
  44. outputs = model(inputs)
  45. loss = criterion(outputs, targets)
  46. val_loss += loss.item()
  47. return val_loss / len(val_loader)
  48. def main():
  49. # Hyperparameters
  50. input_length = 10
  51. output_length = 5
  52. batch_size = 32
  53. hidden_size = 64
  54. num_layers = 2
  55. learning_rate = 0.001
  56. num_epochs = 100
  57. # Load the data
  58. train_dataset = TimeSeriesDataset('train.csv', input_length, output_length)
  59. val_dataset = TimeSeriesDataset('val.csv', input_length, output_length)
  60. train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
  61. val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
  62. # Initialize the model
  63. input_size = train_dataset[0][0].shape[-1]
  64. output_size = train_dataset[0][1].shape[-1]
  65. model = TimeSeriesModel(input_size, output_size, hidden_size, num_layers)
  66. # Use GPU if available
  67. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  68. model.to(device)
  69. # Set up the optimizer and loss function
  70. optimizer = optim.Adam(model.parameters(), lr=learning_rate)
  71. criterion = nn.MSELoss()
  72. # Train the model
  73. for epoch in range(num_epochs):
  74. train_loss = train(model, train_loader, optimizer, criterion, device)
  75. val_loss = validate(model, val_loader, criterion, device)
  76. print('Epoch [{}/{}], Train Loss: {:.4f}, Validation Loss: {:.4f}'.format(epoch+1, num_epochs, train_loss, val_loss))
  77. # Save the model
  78. torch.save(model.state_dict(), 'model.pth')
  79. if __name__ == '__main__':
  80. main()

此框架使用pandas加载CSV文件,并创建了一个TimeSeriesDataset类来处理数据,该类将一系列时间步作为输入,并将接下来的一系列时间步作为输出,以便进行时间序列预测。TimeSeriesModel类定义了一个LSTM模型,其输入和输出大小取决于数据集中的输入长度和输出长度。训练和验证功能被定义为trainvalidate函数,它们分别计算给定数据集上的平均损失。最后,在main函数中,我们使用训练数据集和验证数据集来训练模型,并保存训练后的模型。

请完成加载训练结束保存的模型,进行推理部分的代码

  1. import torch
  2. from torch import nn
  3. # 定义模型结构
  4. class Model(nn.Module):
  5. def __init__(self):
  6. super(Model, self).__init__()
  7. self.fc1 = nn.Linear(10, 5)
  8. self.relu = nn.ReLU()
  9. self.fc2 = nn.Linear(5, 1)
  10. def forward(self, x):
  11. x = self.fc1(x)
  12. x = self.relu(x)
  13. x = self.fc2(x)
  14. return x
  15. # 构建模型实例
  16. model = Model()
  17. # 加载保存的模型参数
  18. model.load_state_dict(torch.load('saved_model.pth'))
  19. # 设置模型为推理模式
  20. model.eval()
  21. # 构造一个输入样本
  22. input = torch.randn(1, 10)
  23. # 进行推理
  24. output = model(input)
  25. print(output)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/579672
推荐阅读
相关标签
  

闽ICP备14008679号