手写数字识别(MNIST数据集)的项目的代码(用pytorch写)
时间: 2024-09-20 20:14:55 浏览: 44
基于Python和PyTorch框架的手写数字识别实验源码+MNIST手写数字数据集.zip
手写数字识别项目通常使用深度学习框架PyTorch来实现,特别是卷积神经网络(Convolutional Neural Networks,CNN)。这里是一个简单的使用PyTorch和MNIST数据集训练LeNet模型的示例:
```python
import torch
import torchvision
from torchvision import transforms
from torch import nn, optim
# 数据预处理
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=64, shuffle=False)
# 定义LeNet模型
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10) # 输出层有10个节点对应0-9的分类
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
model = LeNet()
criterion = nn.CrossEntropyLoss() # 使用交叉熵损失函数
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练过程
num_epochs = 10
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}")
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Test Accuracy of the model on the 10000 test images: {100 * correct / total}%")
```
这个代码首先导入必要的库,然后加载和预处理MNIST数据,接着定义LeNet网络结构并初始化,之后设置损失函数和优化器。在训练循环中更新权重,并在每个epoch结束后打印损失。最后,测试模型并计算准确率。
阅读全文