pytorch手写数字识别实验报告
时间: 2023-07-25 15:13:01 浏览: 117
实验目的:
使用PyTorch框架实现手写数字识别模型,并对模型进行优化,提高识别准确率。
实验步骤:
1. 数据集准备
使用MNIST手写数字数据集,该数据集包含60000个训练样本和10000个测试样本,每个样本都是28x28像素的灰度图像。可以使用PyTorch自带的torchvision.datasets.MNIST类进行数据集的加载。
2. 模型设计与训练
使用PyTorch搭建卷积神经网络模型,对手写数字图像进行分类。具体网络结构如下:
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
```
模型训练过程:
```python
model = Net().to(device)
optimizer = optim.Adadelta(model.parameters(), lr=0.1)
def train(model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.nll_loss(output, target, reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
epochs = 10
for epoch in range(1, epochs + 1):
train(model, device, train_loader, optimizer, epoch)
test(model, device, test_loader)
```
3. 模型优化
对模型进行优化,提高模型的准确率。可以尝试以下优化方法:
- 改变学习率,使用更好的优化器(如Adam等);
- 对数据集进行增强,如旋转、平移、缩放等;
- 改变网络结构,尝试添加BatchNormalization层、使用更多的卷积层和全连接层等;
- 加入正则化,如L1、L2正则化等。
实验结果:
使用上述模型,在MNIST数据集上进行训练,最终得到的准确率为98.89%。可以看出使用PyTorch框架实现手写数字识别是非常方便的。
阅读全文