在PyTorch中處理時間序列數據任務通常需要使用torch.nn.RNN
, torch.nn.LSTM
, torch.nn.GRU
等遞歸神經網絡模塊,以及torch.utils.data.Dataset
和torch.utils.data.DataLoader
等數據加載工具。
以下是一個簡單的示例,演示如何使用PyTorch處理一個時間序列數據任務:
Dataset
類,用于加載時間序列數據:import torch
from torch.utils.data import Dataset
class TimeSeriesDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
import torch.nn as nn
class RNNModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super(RNNModel, self).__init__()
self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
out, _ = self.rnn(x)
out = self.fc(out[:, -1, :])
return out
# 定義超參數
input_size = 1
hidden_size = 64
num_layers = 1
output_size = 1
num_epochs = 100
learning_rate = 0.001
# 準備數據
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
dataset = TimeSeriesDataset(data)
dataloader = DataLoader(dataset, batch_size=1, shuffle=True)
# 初始化模型
model = RNNModel(input_size, hidden_size, num_layers, output_size)
# 定義損失函數和優化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# 訓練模型
for epoch in range(num_epochs):
for i, batch in enumerate(dataloader):
inputs = batch.float().unsqueeze(2)
targets = inputs.clone()
outputs = model(inputs)
loss = criterion(outputs, targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 10 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, len(dataloader), loss.item()))
在上述示例中,我們首先創建了一個自定義的Dataset
類來加載時間序列數據,然后定義了一個包含RNN的模型RNNModel
,最后準備數據并訓練模型。在訓練過程中,我們使用了均方誤差損失函數和Adam優化器來優化模型。