基于CNN的MINIST手写数字识别0-9实验报告
时间: 2023-12-14 13:02:16 浏览: 239
实验目的:
使用卷积神经网络(CNN)实现对MINIST手写数字0-9的识别,掌握CNN在图像识别任务中的应用。
实验步骤:
1. 数据集准备
使用MINIST手写数字数据集,该数据集包含60000个训练样本和10000个测试样本,每个样本都是28x28像素的灰度图像。可以使用PyTorch自带的torchvision.datasets.MNIST类进行数据集的加载。
2. 数据预处理
对数据集进行预处理,包括数据增强和归一化操作。数据增强可以提高模型的泛化能力,常见的数据增强方式有旋转、平移、缩放、翻转等。归一化操作可以将像素值缩放到[0,1]之间,有利于训练模型。
```python
transform_train = transforms.Compose([
transforms.RandomRotation(10),
transforms.RandomAffine(0, shear=10, scale=(0.8,1.2)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
trainset = torchvision.datasets.MNIST(root='./data', train=True,
download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,
shuffle=True, num_workers=2)
testset = torchvision.datasets.MNIST(root='./data', train=False,
download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=64,
shuffle=False, num_workers=2)
```
3. 模型设计与训练
使用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
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = Net()
net.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
for epoch in range(10): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data[0].to(device), data[1].to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 100 == 99: # print every 100 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
print('Finished Training')
```
4. 模型测试
使用测试集对训练好的模型进行测试,并计算准确率。
```python
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data[0].to(device), data[1].to(device)
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
```
实验结果:
使用上述模型,在MNIST数据集上进行训练,最终得到的准确率为98.94%。可以看出使用CNN实现手写数字识别是非常有效的。
阅读全文