March 2, 2019

使用卷积网络做手写数字识别

版权声明:本文为博主原创文章,转载请注明原文出处!

写作时间:2019-03-02 22:24:22

使用卷积网络做手写数字识别

思路分析

上篇博文《使用循环神经网络做手写数字识别》介绍了利用LSTM做手写数字的识别,想着好事成双,也写一个姊妹篇卷积网络实现手写数字的识别。

博文主要通过最简单的代码量展示一个入门级别的识别案例。需要注意的几点:

PyTorch实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import torch
from torch import nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms

torch.manual_seed(2019)

# 超参设置
EPOCH = 1 # 训练EPOCH次,这里为了测试方便只跑一次
BATCH_SIZE = 32
INIT_LR = 1e-3 # 初始学习率
DOWNLOAD_MNIST = True # 设置是否需要下载数据集

# 使用DataLoader加载训练数据,为了演示方便,对于测试数据只取出2000个样本进行测试
train_data = datasets.MNIST(root='mnist', train=True, transform=transforms.ToTensor(), download=DOWNLOAD_MNIST)
train_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
test_data = datasets.MNIST(root='mnist', train=False)
test_x = test_data.test_data.type(torch.FloatTensor)[:2000] / 255.
test_x.unsqueeze_(1) # 调整test_x的尺寸为四维,添加了一个channel维度
test_y = test_data.test_labels.numpy()[:2000]


class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(1, 32, 5), # 图像输出大小为24*24
nn.MaxPool2d(2), # 图像输出大小为12*12
nn.ReLU(True),
nn.Conv2d(32, 64, 5), # 图像输出大小为8*8
nn.Dropout2d(),
nn.MaxPool2d(2), # 图像输出大小为4*4
nn.ReLU(True)
)

self.linear = nn.Sequential(
nn.Linear(4 * 4 * 64, 128),
nn.ReLU(True),
nn.Dropout2d(),
nn.Linear(128, 10),
nn.Softmax(1)
)

def forward(self, x):
x = self.conv(x)
x = x.view(-1, 4 * 4 * 64)
out = self.linear(x)
return out


model = ConvNet()
print(model)

optimizer = torch.optim.Adam(model.parameters(), lr=INIT_LR)
loss_func = nn.CrossEntropyLoss()

# RNN训练
for epoch in range(EPOCH):
for index, (b_x, b_y) in enumerate(train_loader):
model.train()
# 输入尺寸为(batch_size, channels, height, width)
output = model(b_x) # (64, 1, 28, 28)
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()

if index % 50 == 0:
model.eval()
prediction = model(test_x) # 输出为(2000, 10)
pred_y = torch.max(prediction, 1)[1].data.numpy()
accuracy = (pred_y == test_y).sum() / float(test_y.size)
print(f'Epoch: [{index}/{epoch}]', f'| train loss: {loss.item()}', f'| test accuracy: {accuracy}')

# 打印测试数据集中的后20个结果
model.eval()
prediction = model(test_x[:20])
pred_y = torch.max(prediction, 1)[1].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:20], 'real number')

训练结果如下,可以看到对于这种不太复杂的问题,CNN和RNN都可以得到比较高的精度。

使用卷积网络做手写数字识别