用PyTorch实现MNIST手写数字识别
时间: 2024-09-30 07:11:42 浏览: 39
用PyTorch实现MNIST手写数字识别对应源码文件
5星 · 资源好评率100%
使用PyTorch实现MNIST手写数字识别是一个常见的深度学习入门示例,它通常涉及几个步骤:
1. **导入库**:
```python
import torch
from torchvision import datasets, transforms
import torch.nn as nn
import torch.optim as optim
```
2. **数据预处理**:
```python
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
```
3. **创建数据加载器**:
```python
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
```
4. **定义模型结构**,这里我们用经典的卷积神经网络(CNN)作为例子:
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(10 * 14 * 14, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = x.view(-1, 10 * 14 * 14)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
model = Net()
```
5. **选择损失函数和优化器**:
```python
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
```
6. **训练循环**:
```python
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# ... 进行前向传播、计算loss、反向传播以及优化操作
# 记录和可视化训练过程的指标(如准确率)
```
7. **评估模型**:
```python
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()
accuracy = 100 * correct / total
```
阅读全文