手写数字识别综合实践
时间: 2025-01-08 14:03:05 浏览: 1
### 手写数字识别实践项目教程
#### 使用MNIST数据集进行手写数字识别的完整流程
对于手写数字识别的任务,通常采用经典的MNIST数据集作为训练和测试的基础。该数据集由28×28像素的手写数字图像组成,共包含60,000张训练图片以及10,000张测试图片[^1]。
为了确保模型能够有效学习并具备良好的泛化能力,在构建模型之前应当合理划分数据集。当有足够的数据量时,建议按照大约60%、20%、20%的比例分配给训练集、验证集和测试集;然而如果数据有限,则可以考虑使用交叉验证方法来充分利用现有资源。
下面是一个基于PyTorch框架实现简单卷积神经网络(CNN)对手写数字分类的例子:
```python
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
def load_data(batch_size=64):
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_loader = DataLoader(
datasets.MNIST('./data', train=True, download=True,
transform=transform),
batch_size=batch_size, shuffle=True)
test_loader = DataLoader(
datasets.MNIST('./data', train=False,
transform=transform),
batch_size=batch_size, shuffle=False)
return train_loader, test_loader
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
self.fc1 = torch.nn.Linear(320, 50)
self.fc2 = torch.nn.Linear(50, 10)
def forward(self, x):
x = torch.relu(torch.max_pool2d(self.conv1(x), 2))
x = torch.relu(torch.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 320)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return torch.log_softmax(x, dim=1)
train_loader, test_loader = load_data()
model = Net()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = torch.nn.CrossEntropyLoss()
for epoch in range(10):
model.train()
running_loss = 0.0
for images, labels in train_loader:
optimizer.zero_grad()
output = model(images)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f'Finished Training')
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print(f'Test Accuracy of the network on {total} test images: {accuracy:.2f}%')
```
这段代码展示了如何加载MNIST数据集,并定义了一个简单的CNN架构用于处理这些图像。通过调整超参数如批次大小(`batch_size`)、迭代次数(`epoch`)等可进一步提升性能表现[^2]。
阅读全文