利用循环神经网络和pytorch实现手写体数字识别
时间: 2023-12-16 19:49:46 浏览: 108
好的,首先我们可以使用PyTorch搭建一个基于循环神经网络的手写数字识别模型。下面是一个简单的代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
# 定义超参数
batch_size = 64
learning_rate = 0.01
epochs = 10
# 加载MNIST数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor())
# 定义数据加载器
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
# 定义循环神经网络模型
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
h0 = torch.zeros(1, x.size(0), self.hidden_size).to(device)
out, _ = self.rnn(x, h0)
out = self.fc(out[:, -1, :])
return out
# 定义设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 实例化模型并移动到设备上
model = RNN(input_size=28, hidden_size=128, num_classes=10).to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(epochs):
for i, (images, labels) in enumerate(train_loader):
# 将数据移动到设备上
images = images.reshape(-1, 28, 28).to(device)
labels = labels.to(device)
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每100个批次打印一次训练信息
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, i+1, len(train_loader), loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
# 将数据移动到设备上
images = images.reshape(-1, 28, 28).to(device)
labels = labels.to(device)
# 前向传播
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
```
在这个例子中,我们使用了一个单层的循环神经网络(RNN),它接受28x28像素的图像作为输入,并输出10个数字类别的概率分布。我们使用了交叉熵损失函数和Adam优化器进行训练,并在测试集上评估了模型的准确率。
希望这个简单的例子能够帮助你理解如何使用PyTorch实现基于循环神经网络的手写数字识别模型。
阅读全文