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

Posted 卡尔曼和玻尔兹曼谁曼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用卷积网络做手写数字识别相关的知识,希望对你有一定的参考价值。

文章目录

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

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

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

思路分析

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

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

  • 卷积网络的输入大小为(batch_sizenum_channelsimage_widthimage_height
  • 本文中的模型使用了卷积层和线性连接层。Linear层的输入大小为(*num_input_feature),所以在卷积层输出流入线性层的时候,需要转化一下张量的尺寸大小
  • 综合使用MaxPooling层和Dropout层可以提高识别准确率

PyTorch实现

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都可以得到比较高的精度。

以上是关于使用卷积网络做手写数字识别的主要内容,如果未能解决你的问题,请参考以下文章

卷积神经网络CNN实现mnist手写数字识别

用PyTorch构建基于卷积神经网络的手写数字识别模型

基于 Tensorflow 2.x 实现多层卷积神经网络,实践 MNIST 手写数字识别

基于 Tensorflow 2.x 实现多层卷积神经网络,实践 MNIST 手写数字识别

基于 Tensorflow 2.x 实现多层卷积神经网络,实践 MNIST 手写数字识别

第2例 基于卷积神经网络LeNet的手写体数字识别