mnist手写数字识别pytorch的代码
时间: 2023-09-16 21:13:10 浏览: 118
下面是一个简单的 PyTorch 实现 MNIST 手写数字识别的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# 定义超参数
batch_size = 64
learning_rate = 0.01
num_epochs = 10
# 下载和加载数据集
train_dataset = datasets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = datasets.MNIST(root='./data',
train=False,
transform=transforms.ToTensor(),
download=True)
# 创建数据加载器
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 Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.pool = nn.MaxPool2d(2)
self.fc = nn.Linear(320, 10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 320)
x = self.fc(x)
return x
# 实例化模型和损失函数
model = Net()
criterion = nn.CrossEntropyLoss()
# 使用随机梯度下降优化器
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 将数据加载到 GPU 中
images = images.cuda()
labels = labels.cuda()
# 前向传播和计算损失
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, num_epochs, i + 1, len(train_loader), loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
# 将数据加载到 GPU 中
images = images.cuda()
labels = labels.cuda()
# 计算输出并获取预测结果
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))
```
这个代码使用了一个简单的卷积神经网络,包括两个卷积层、两个最大池化层和一个全连接层。训练过程中使用随机梯度下降优化器,测试过程中计算模型的准确率。
阅读全文