pytorch lstm实例
时间: 2023-05-27 20:07:23 浏览: 105
以下是基于PyTorch实现的LSTM实例:
```python
import torch
import torch.nn as nn
# 定义LSTM网络
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
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, output_size)
def forward(self, x):
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)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :])
return out
# 实例化网络
input_size = 28
hidden_size = 128
num_layers = 2
output_size = 10
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net = LSTM(input_size, hidden_size, num_layers, output_size).to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.001)
# 训练网络
num_epochs = 10
for epoch in range(num_epochs):
for i, (inputs, labels) in enumerate(train_loader):
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item()))
# 测试网络
with torch.no_grad():
correct = 0
total = 0
for inputs, labels in test_loader:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy: {} %'.format(100 * correct / total))
```
上述代码实现了一个LSTM网络,用于手写数字识别任务。其中,输入数据是28x28的图片,输出是10个数字的概率。在训练过程中,使用交叉熵损失函数和Adam优化器。在测试过程中,计算准确率来评估网络性能。
阅读全文