给我写一个使用pytorch的LSTM模型代码
时间: 2023-02-08 19:52:48 浏览: 286
Python-在PyTorch中使用LSTM进行风速预测
3星 · 编辑精心推荐
好的,这里是使用 PyTorch 实现 LSTM 模型的简单代码示例:
```python
import torch
import torch.nn as nn
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(LSTM, 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, num_classes)
def forward(self, x):
# Set initial hidden and cell states
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
# Forward propagate LSTM
out, _ = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size)
# Decode the hidden state of the last time step
out = self.fc(out[:, -1, :])
return out
# Instantiate the model with hyperparameters
input_size = 1
hidden_size = 32
num_layers = 1
num_classes = 1
model = LSTM(input_size, hidden_size, num_layers, num_classes)
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# Loss and optimizer
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
for epoch in range(num_epochs):
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, targets)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
```
在上述代码中,我们首先定义了一个包含 LSTM 层的 PyTorch 模型。然后,我们将模型移动到 GPU 上(如果可用),并定义损失函数和优化器。最后,我们在循环中训练模型,每次迭代时都会执行
阅读全文