HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验

目录

  • 写在前面的一些内容
  • 一、基于LeNet实现手写体数字识别实验
    • 1. 数据
      • 数据预处理
    • 2. 模型构建
    • 3. 模型训练
    • 4. 模型评价
    • 5. 模型预测
  • 二、基于残差网络的手写体数字识别实验
  • 三、实验Q&A


写在前面的一些内容

  1. 本文为HBU_神经网络与深度学习实验(2022年秋)实验7的实验报告,此文的基本内容参照 [1]Github/卷积神经网络-上.ipynb 的基于LeNet实现手写体数字识别实验基于残差网络的手写体数字识别实验两小节,检索时请按对应序号进行检索。
  2. 本实验编程语言为Python 3.10,使用Pycharm进行编程。
  3. 本实验报告目录标题级别顺序:一、 1. (1)
  4. 水平有限,难免有误,如有错漏之处敬请指正。

一、基于LeNet实现手写体数字识别实验

在本节中,我们实现经典卷积网络LeNet-5,并进行手写体数字识别任务。


1. 数据

手写体数字识别是计算机视觉中最常用的图像分类任务,让计算机识别出给定图片中的手写体数字(0-9共10个数字)。由于手写体风格差异很大,因此手写体数字识别是具有一定难度的任务。

我们采用常用的手写数字识别数据集:MNIST数据集。MNIST数据集是计算机视觉领域的经典入门数据集,包含了60,000个训练样本和10,000个测试样本。这些数字已经过尺寸标准化并位于图像中心,图像是固定大小( 28 × 28 28\times 28 28×28像素)。图12给出了部分样本的示例。
HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验_第1张图片

图12 MNIST数据集示例

为了节省训练时间,本节选取MNIST数据集的一个子集进行后续实验,数据集的划分为:

  • 训练集:1,000条样本
  • 验证集:200条样本
  • 测试集:200条样本

MNIST数据集分为train_set、dev_set和test_set三个数据集,每个数据集含两个列表分别存放了图片数据以及标签数据。比如train_set包含:

  • 图片数据:[1 000, 784]的二维列表,包含1 000张图片。每张图片用一个长度为784的向量表示,内容是 28 × 28 28\times 28 28×28 尺寸的像素灰度值(黑白图片)。
  • 标签数据:[1 000, 1]的列表,表示这些图片对应的分类标签,即0~9之间的数字。

观察数据集分布情况,代码实现如下:

import struct
import numpy as np

# 读取标签数据集
with open('./MNIST/raw/train-labels-idx1-ubyte', 'rb') as lbpath:
    labels_magic, labels_num = struct.unpack('>II', lbpath.read(8))
    labels = np.fromfile(lbpath, dtype=np.uint8)

# 读取图片数据集
with open('./MNIST/raw/train-images-idx3-ubyte', 'rb') as imgpath:
    images_magic, images_num, rows, cols = struct.unpack('>IIII', imgpath.read(16))
    images = np.fromfile(imgpath, dtype=np.uint8).reshape(images_num, rows * cols)

# 打印并观察数据集分布情况
train_images, train_labels = images[:1000], labels[:1000]
dev_images, dev_labels = images[1000:1200], labels[1000:1200]
test_images, test_labels = images[1200:1400], labels[1200:1400]
train_set, dev_set, test_set = [train_images, train_labels], [dev_images, dev_labels], [test_images, test_labels]
print('Length of train/dev/test set:{}/{}/{}'.format(len(train_set[0]), len(dev_set[0]), len(test_set[0])))

代码执行结果:

Length of train/dev/test set:1000/200/200

可视化观察其中的一张样本以及对应的标签,代码如下所示:

import matplotlib.pyplot as plt
from PIL import Image

image, label = train_set[0][0], train_set[1][0]
image, label = np.array(image).astype('float32'), int(label)
# 原始图像数据为长度784的行向量,需要调整为[28,28]大小的图像
image = np.reshape(image, [28,28])
image = Image.fromarray(image.astype('uint8'), mode='L')
print("The number in the picture is {}".format(label))
plt.figure(figsize=(5, 5))
plt.imshow(image)
plt.savefig('conv-number5.pdf')
plt.show()

代码执行结果:

The number in the picture is 5

执行代码后得到下图:
HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验_第2张图片

数据预处理

图像分类网络对输入图片的格式、大小有一定的要求,数据输入模型前,需要对数据进行预处理操作,使图片满足网络训练以及预测的需要。本实验主要应用了如下方法:

  • 调整图片大小:LeNet网络对输入图片大小的要求为 32 × 32 32\times 32 32×32 ,而MNIST数据集中的原始图片大小却是 28 × 28 28\times 28 28×28 ,这里为了符合网络的结构设计,将其调整为 32 × 32 32\times 32 32×32
  • 规范化: 通过规范化手段,把输入图像的分布改变成均值为0,标准差为1的标准正态分布,使得最优解的寻优过程明显会变得平缓,训练过程更容易收敛。

代码实现如下:

from torchvision.transforms import Compose, Resize, ToTensor, Normalize

# 数据预处理
transforms = Compose([Resize(32), ToTensor(), Normalize(mean=[127.5], std=[127.5])])

将原始的数据集封装为Dataset类,以便DataLoader调用。

import torch
import torch.utils.data as io

class MNIST_dataset(io.Dataset):
    def __init__(self, dataset, transforms, mode='train'):
        self.mode = mode
        self.transforms =transforms
        self.dataset = dataset

    def __getitem__(self, idx):
        # 获取图像和标签
        image, label = self.dataset[0][idx], self.dataset[1][idx]
        image, label = np.array(image).astype('float32'), int(label)
        image = np.reshape(image, [28,28])
        image = Image.fromarray(image.astype('uint8'), mode='L')
        image = self.transforms(image)

        return image, label

    def __len__(self):
        return len(self.dataset[0])
# 固定随机种子
torch.random.manual_seed(0)
# 加载 mnist 数据集
train_dataset = MNIST_dataset(dataset=train_set, transforms=transforms, mode='train')
test_dataset = MNIST_dataset(dataset=test_set, transforms=transforms, mode='test')
dev_dataset = MNIST_dataset(dataset=dev_set, transforms=transforms, mode='dev')

2. 模型构建

LeNet-5虽然提出的时间比较早,但它是一个非常成功的神经网络模型。基于LeNet-5的手写数字识别系统在20世纪90年代被美国很多银行使用,用来识别支票上面的手写数字。LeNet-5的网络结构如图13所示。
HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验_第3张图片

图13 LeNet-5网络结构

我们使用上面定义的卷积层算子和汇聚层算子构建一个LeNet-5模型。

网络共有7层,包含3个卷积层、2个汇聚层以及2个全连接层的简单卷积神经网络接,受输入图像大小为 32 × 32 = 1   024 32\times 32=1\,024 32×32=1024,输出对应10个类别的得分。 具体实现如下:

import torch.nn.functional as F

class Model_LeNet(nn.Module):
    def __init__(self, in_channels, num_classes=10):
        super(Model_LeNet, self).__init__()
        # 卷积层:输出通道数为6,卷积核大小为5×5
        self.conv1 = Conv2D(in_channels=in_channels, out_channels=6, kernel_size=5)
        # 汇聚层:汇聚窗口为2×2,步长为2
        self.pool2 = Pool2D(size=(2, 2), mode='max', stride=2)
        # 卷积层:输入通道数为6,输出通道数为16,卷积核大小为5×5,步长为1
        self.conv3 = Conv2D(in_channels=6, out_channels=16, kernel_size=5, stride=1)
        # 汇聚层:汇聚窗口为2×2,步长为2
        self.pool4 = Pool2D(size=(2, 2), mode='avg', stride=2)
        # 卷积层:输入通道数为16,输出通道数为120,卷积核大小为5×5
        self.conv5 = Conv2D(in_channels=16, out_channels=120, kernel_size=5, stride=1)
        # 全连接层:输入神经元为120,输出神经元为84
        self.linear6 = nn.Linear(120, 84)
        # 全连接层:输入神经元为84,输出神经元为类别数
        self.linear7 = nn.Linear(84, num_classes)

    def forward(self, x):
        # C1:卷积层+激活函数
        output = F.relu(self.conv1(x))
        # S2:汇聚层
        output = self.pool2(output)
        # C3:卷积层+激活函数
        output = F.relu(self.conv3(output))
        # S4:汇聚层
        output = self.pool4(output)
        # C5:卷积层+激活函数
        output = F.relu(self.conv5(output))
        # 输入层将数据拉平[B,C,H,W] -> [B,CxHxW]
        output = torch.squeeze(output, dim=3)
        output = torch.squeeze(output, dim=2)
        # F6:全连接层
        output = F.relu(self.linear6(output))
        # F7:全连接层
        output = self.linear7(output)
        return output

下面测试一下上面的LeNet-5模型,构造一个形状为 [1,1,32,32] 的输入数据送入网络,观察每一层特征图的形状变化。代码实现如下:

# 这里用np.random创建一个随机数组作为输入数据
inputs = np.random.randn(*[1, 1, 32, 32])
inputs = inputs.astype('float32')

# 创建Model_LeNet类的实例,指定模型名称和分类的类别数目
model = Model_LeNet(in_channels=1, num_classes=10)
# 通过调用LeNet从基类继承的sublayers()函数,查看LeNet中所包含的子层
model_modules = [layer for layer in model.modules()]
print(model_modules[1:])
x = torch.tensor(inputs)
for item in model_modules[1:]:
    # item是LeNet类中的一个子层
    # 查看经过子层之后的输出数据形状
    try:
        x = item(x)
    except:
        # 如果是最后一个卷积层输出,需要展平后才可以送入全连接层
        x = torch.reshape(x, [x.shape[0], -1])
        x = item(x)
    if len(list(item.parameters())) == 2:
        # 查看卷积和全连接层的数据和参数的形状,
        # 其中item.parameters()[0]是权重参数w,item.parameters()[1]是偏置参数b
        print(item, x.shape, list(item.parameters())[0].shape,
              list(item.parameters())[1].shape)
    else:
        # 汇聚层没有参数
        print(item, x.shape)

代码执行结果:

[Conv2D(), Pool2D(), Conv2D(), Pool2D(), Conv2D(), Linear(in_features=120, out_features=84, bias=True), Linear(in_features=84, out_features=10, bias=True)]
Conv2D() torch.Size([1, 6, 28, 28]) torch.Size([6, 1, 5, 5]) torch.Size([6, 1])
Pool2D() torch.Size([1, 6, 14, 14])
Conv2D() torch.Size([1, 16, 10, 10]) torch.Size([16, 6, 5, 5]) torch.Size([16, 1])
Pool2D() torch.Size([1, 16, 5, 5])
Conv2D() torch.Size([1, 120, 1, 1]) torch.Size([120, 16, 5, 5]) torch.Size([120, 1])
Linear(in_features=120, out_features=84, bias=True) torch.Size([1, 84]) torch.Size([84, 120]) torch.Size([84])
Linear(in_features=84, out_features=10, bias=True) torch.Size([1, 10]) torch.Size([10, 84]) torch.Size([10])

从输出结果看,

  • 对于大小为 32 × 32 32\times 32 32×32 的单通道图像,先用6个大小为 5 × 5 5\times 5 5×5 的卷积核对其进行卷积运算,输出为6个 28 × 28 28\times 28 28×28 大小的特征图;
  • 6个 28 × 28 28\times 28 28×28 大小的特征图经过大小为 2 × 2 2\times 2 2×2 ,步长为2的汇聚层后,输出特征图的大小变为 14 × 14 14\times 14 14×14
  • 6个 14 × 14 14\times 14 14×14 大小的特征图再经过16个大小为 5 × 5 5\times 5 5×5 的卷积核对其进行卷积运算,得到16个 10 × 10 10\times 10 10×10 大小的输出特征图;
  • 16个 10 × 10 10\times 10 10×10 大小的特征图经过大小为 2 × 2 2\times 2 2×2 ,步长为2的汇聚层后,输出特征图的大小变为 5 × 5 5\times 5 5×5
  • 16个 5 × 5 5\times 5 5×5 大小的特征图再经过120个大小为 5 × 5 5\times 5 5×5 的卷积核对其进行卷积运算,得到120个 1 × 1 1\times 1 1×1 大小的输出特征图;
  • 此时,将特征图展平成1维,则有120个像素点,经过输入神经元个数为120,输出神经元个数为84的全连接层后,输出的长度变为84。
  • 再经过一个全连接层的计算,最终得到了长度为类别数的输出结果。

考虑到自定义的Conv2DPool2D算子中包含多个for循环,所以运算速度比较慢。飞桨框架中,针对卷积层算子和汇聚层算子进行了速度上的优化,这里基于torch.nn.Conv2dtorch.nn.MaxPool2dtorch.nn.AvgPool2d构建LeNet-5模型,对比与上边实现的模型的运算速度。代码实现如下:

class Torch_LeNet(nn.Module):
    def __init__(self, in_channels, num_classes=10):
        super(Torch_LeNet, self).__init__()
        # 卷积层:输出通道数为6,卷积核大小为5*5
        self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=6, kernel_size=5)
        # 汇聚层:汇聚窗口为2*2,步长为2
        self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
        # 卷积层:输入通道数为6,输出通道数为16,卷积核大小为5*5
        self.conv3 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)
        # 汇聚层:汇聚窗口为2*2,步长为2
        self.pool4 = nn.AvgPool2d(kernel_size=2, stride=2)
        # 卷积层:输入通道数为16,输出通道数为120,卷积核大小为5*5
        self.conv5 = nn.Conv2d(in_channels=16, out_channels=120, kernel_size=5)
        # 全连接层:输入神经元为120,输出神经元为84
        self.linear6 = nn.Linear(in_features=120, out_features=84)
        # 全连接层:输入神经元为84,输出神经元为类别数
        self.linear7 = nn.Linear(in_features=84, out_features=num_classes)

    def forward(self, x):
        # C1:卷积层+激活函数
        output = F.relu(self.conv1(x))
        # S2:汇聚层
        output = self.pool2(output)
        # C3:卷积层+激活函数
        output = F.relu(self.conv3(output))
        # S4:汇聚层
        output = self.pool4(output)
        # C5:卷积层+激活函数
        output = F.relu(self.conv5(output))
        # 输入层将数据拉平[B,C,H,W] -> [B,CxHxW]
        output = torch.squeeze(output, dim=3)
        output = torch.squeeze(output, dim=2)
        # F6:全连接层
        output = F.relu(self.linear6(output))
        # F7:全连接层
        output = self.linear7(output)
        return output

测试两个网络的运算速度。

import time

# 这里用np.random创建一个随机数组作为测试数据
inputs = np.random.randn(*[1, 1, 32, 32])
inputs = inputs.astype('float32')
x = torch.tensor(inputs)

# 创建Model_LeNet类的实例,指定模型名称和分类的类别数目
model = Model_LeNet(in_channels=1, num_classes=10)
# 创建Torch_LeNet类的实例,指定模型名称和分类的类别数目
torch_model = Torch_LeNet(in_channels=1, num_classes=10)

# 计算Model_LeNet类的运算速度
model_time = 0
for i in range(60):
    strat_time = time.time()
    out = model(x)
    end_time = time.time()
    # 预热10次运算,不计入最终速度统计
    if i < 10:
        continue
    model_time += (end_time - strat_time)
avg_model_time = model_time / 50
print('Model_LeNet speed:', avg_model_time, 's')

# 计算Torch_LeNet类的运算速度
torch_model_time = 0
for i in range(60):
    strat_time = time.time()
    torch_out = torch_model(x)
    end_time = time.time()
    # 预热10次运算,不计入最终速度统计
    if i < 10:
        continue
    torch_model_time += (end_time - strat_time)
avg_torch_model_time = torch_model_time / 50

print('Torch_LeNet speed:', avg_torch_model_time, 's')

代码执行结果:

Model_LeNet speed: 0.878377799987793 s
Torch_LeNet speed: 0.0004801034927368164 s

这里还可以令两个网络加载同样的权重,测试一下两个网络的输出结果是否一致。

# 这里用np.random创建一个随机数组作为测试数据
inputs = np.random.randn(*[1, 1, 32, 32])
inputs = inputs.astype('float32')
x = torch.tensor(inputs)

# 创建Model_LeNet类的实例,指定模型名称和分类的类别数目
model = Model_LeNet(in_channels=1, num_classes=10)
# 获取网络的权重
params = model.state_dict()
# 自定义Conv2D算子的bias参数形状为[out_channels, 1]
# torch API中Conv2D算子的bias参数形状为[out_channels]
# 需要进行调整后才可以赋值
for key in params:
    if 'bias' in key:
        params[key] = params[key].squeeze()
# 创建Torch_LeNet类的实例,指定模型名称和分类的类别数目
torch_model = Torch_LeNet(in_channels=1, num_classes=10)
# 将Model_LeNet的权重参数赋予给Torch_LeNet模型,保持两者一致
torch_model.load_state_dict(params)

# 打印结果保留小数点后6位
torch.set_printoptions(6)
# 计算Model_LeNet的结果
output = model(x)
print('Model_LeNet output: ', output)
# 计算Torch_LeNet的结果
torch_output = torch_model(x)
print('Torch_LeNet output: ', torch_output)

代码执行结果:

Model_LeNet output:  tensor([[-72007.750000, -73958.312500, -39047.375000, -70354.000000,
          55313.753906,  24012.710938, -18572.982422, -46341.015625,
         -52060.746094, -57787.097656]], grad_fn=<AddmmBackward0>)
Torch_LeNet output:  tensor([[-72007.781250, -73958.335938, -39047.386719, -70354.039062,
          55313.781250,  24012.724609, -18572.986328, -46341.035156,
         -52060.757812, -57787.109375]], grad_fn=<AddmmBackward0>)

可以看到,输出结果相差不大。

这里还可以统计一下LeNet-5模型的参数量和计算量。

参数量

按照公式
p a r a m e t e r s = P × D × U × V + P \begin{align} parameters = P \times D \times U \times V + P \end{align} parameters=P×D×U×V+P进行计算,可以得到:

  • 第一个卷积层的参数量为: 6 × 1 × 5 × 5 + 6 = 156 6 \times 1 \times 5 \times 5 + 6 = 156 6×1×5×5+6=156
  • 第二个卷积层的参数量为: 16 × 6 × 5 × 5 + 16 = 2416 16 \times 6 \times 5 \times 5 + 16 = 2416 16×6×5×5+16=2416
  • 第三个卷积层的参数量为: 120 × 16 × 5 × 5 + 120 = 48120 120 \times 16 \times 5 \times 5 + 120= 48120 120×16×5×5+120=48120
  • 第一个全连接层的参数量为: 120 × 84 + 84 = 10164 120 \times 84 + 84= 10164 120×84+84=10164
  • 第二个全连接层的参数量为: 84 × 10 + 10 = 850 84 \times 10 + 10= 850 84×10+10=850

所以,LeNet-5总的参数量为 61706 61706 61706

在PyTorch中,还可以使用torchsummary.summaryAPI自动计算参数量。

from torchsummary import summary
summary(torch_model, (1, 32, 32))

代码执行结果:

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1            [-1, 6, 28, 28]             156
         MaxPool2d-2            [-1, 6, 14, 14]               0
            Conv2d-3           [-1, 16, 10, 10]           2,416
         AvgPool2d-4             [-1, 16, 5, 5]               0
            Conv2d-5            [-1, 120, 1, 1]          48,120
            Linear-6                   [-1, 84]          10,164
            Linear-7                   [-1, 10]             850
================================================================
Total params: 61,706
Trainable params: 61,706
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.00
Forward/backward pass size (MB): 0.06
Params size (MB): 0.24
Estimated Total Size (MB): 0.30
----------------------------------------------------------------

可以看到,结果与公式推导一致。

计算量

按照公式
F L O P s = M ′ × N ′ × P × D × U × V + M ′ × N ′ × P \begin{align} FLOPs=M'\times N'\times P\times D\times U\times V + M'\times N'\times P \end{align} FLOPs=M×N×P×D×U×V+M×N×P进行计算,可以得到:

  • 第一个卷积层的计算量为: 28 × 28 × 5 × 5 × 6 × 1 + 28 × 28 × 6 = 122304 28\times 28\times 5\times 5\times 6\times 1 + 28\times 28\times 6=122304 28×28×5×5×6×1+28×28×6=122304
  • 第二个卷积层的计算量为: 10 × 10 × 5 × 5 × 16 × 6 + 10 × 10 × 16 = 241600 10\times 10\times 5\times 5\times 16\times 6 + 10\times 10\times 16=241600 10×10×5×5×16×6+10×10×16=241600
  • 第三个卷积层的计算量为: 1 × 1 × 5 × 5 × 120 × 16 + 1 × 1 × 120 = 48120 1\times 1\times 5\times 5\times 120\times 16 + 1\times 1\times 120=48120 1×1×5×5×120×16+1×1×120=48120
  • 平均汇聚层的计算量为: 16 × 5 × 5 = 400 16\times 5\times 5=400 16×5×5=400
  • 第一个全连接层的计算量为: 120 × 84 = 10080 120 \times 84 = 10080 120×84=10080
  • 第二个全连接层的计算量为: 84 × 10 = 840 84 \times 10 = 840 84×10=840

所以,LeNet-5总的计算量为 423344 423344 423344

在PyTorch中,还可以使用torchstat.statAPI自动统计计算量。

from torchstat import stat
stat(torch_model, (1, 32, 32))

代码执行结果:

      module name  input shape output shape   params memory(MB)       MAdd      Flops  MemRead(B)  MemWrite(B) duration[%]  MemR+W(B)
0           conv1    1  32  32    6  28  28    156.0       0.02  235,200.0  122,304.0      4720.0      18816.0      50.06%    23536.0
1           pool2    6  28  28    6  14  14      0.0       0.00    3,528.0    4,704.0     18816.0       4704.0      49.94%    23520.0
2           conv3    6  14  14   16  10  10   2416.0       0.01  480,000.0  241,600.0     14368.0       6400.0       0.00%    20768.0
3           pool4   16  10  10   16   5   5      0.0       0.00    1,600.0    1,600.0      6400.0       1600.0       0.00%     8000.0
4           conv5   16   5   5  120   1   1  48120.0       0.00   96,000.0   48,120.0    194080.0        480.0       0.00%   194560.0
5         linear6          120           84  10164.0       0.00   20,076.0   10,080.0     41136.0        336.0       0.00%    41472.0
6         linear7           84           10    850.0       0.00    1,670.0      840.0      3736.0         40.0       0.00%     3776.0
total                                        61706.0       0.03  838,074.0  429,248.0      3736.0         40.0     100.00%   315632.0
=====================================================================================================================================
Total params: 61,706
-------------------------------------------------------------------------------------------------------------------------------------
Total memory: 0.03MB
Total MAdd: 838.07KMAdd
Total Flops: 429.25KFlops
Total MemR+W: 308.23KB

3. 模型训练

使用交叉熵损失函数,并用随机梯度下降法作为优化器来训练LeNet-5网络。 用RunnerV3在训练集上训练5个epoch,并保存准确率最高的模型作为最佳模型。

import torch.optim as opt

torch.random.manual_seed(100)
# 学习率大小
lr = 0.1
# 批次大小
batch_size = 64
# 加载数据
train_loader = io.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
dev_loader = io.DataLoader(dev_dataset, batch_size=batch_size)
test_loader = io.DataLoader(test_dataset, batch_size=batch_size)
# 定义LeNet网络
# 自定义算子实现的LeNet-5
model = Model_LeNet(in_channels=1, num_classes=10)
# PyTorch实现的LeNet-5
# model = Torch_LeNet(in_channels=1, num_classes=10)
# 定义优化器
optimizer = opt.SGD(model.parameters(), lr=lr)
# 定义损失函数
loss_fn = F.cross_entropy
# 定义评价指标
metric = Accuracy(is_logist=True)
# 实例化 RunnerV3 类,并传入训练配置。
runner = RunnerV3(model, optimizer, loss_fn, metric)
# 启动训练
log_steps = 15
eval_steps = 15
runner.train(train_loader, dev_loader, num_epochs=5, log_steps=log_steps,
             eval_steps=eval_steps, save_path="best_model.pdparams")

代码执行结果:

[Train] epoch: 0/5, step: 0/80, loss: 2.29860
[Train] epoch: 0/5, step: 15/80, loss: 2.31052
[Evaluate]  dev score: 0.08500, dev loss: 2.30621
[Evaluate] best accuracy performence has been updated: 0.00000 --> 0.08500
[Train] epoch: 1/5, step: 30/80, loss: 2.30723
[Evaluate]  dev score: 0.10000, dev loss: 2.30257
[Evaluate] best accuracy performence has been updated: 0.08500 --> 0.10000
[Train] epoch: 2/5, step: 45/80, loss: 2.30510
[Evaluate]  dev score: 0.12500, dev loss: 2.29797
[Evaluate] best accuracy performence has been updated: 0.10000 --> 0.12500
[Train] epoch: 3/5, step: 60/80, loss: 2.29647
[Evaluate]  dev score: 0.12500, dev loss: 2.29648
[Train] epoch: 4/5, step: 75/80, loss: 2.30547
[Evaluate]  dev score: 0.12500, dev loss: 2.29393
[Evaluate]  dev score: 0.12500, dev loss: 2.29474
[Train] Training done!

可视化观察训练集与验证集的损失变化情况。

def plot_training_loss_acc(runner, fig_name,
                           fig_size=(16, 6),
                           sample_step=20,
                           loss_legend_loc="upper right",
                           acc_legend_loc="lower right",
                           train_color="#e4007f",
                           dev_color='#f19ec2',
                           fontsize='large',
                           train_linestyle="-",
                           dev_linestyle='--'):
    plt.figure(figsize=fig_size)

    plt.subplot(1, 2, 1)
    train_items = runner.train_step_losses[::sample_step]
    train_steps = [x[0] for x in train_items]
    train_losses = [x[1] for x in train_items]

    plt.plot(train_steps, train_losses, color=train_color, linestyle=train_linestyle, label="Train loss")
    if len(runner.dev_losses) > 0:
        dev_steps = [x[0] for x in runner.dev_losses]
        dev_losses = [x[1] for x in runner.dev_losses]
        plt.plot(dev_steps, dev_losses, color=dev_color, linestyle=dev_linestyle, label="Dev loss")
    # 绘制坐标轴和图例
    plt.ylabel("loss", fontsize=fontsize)
    plt.xlabel("step", fontsize=fontsize)
    plt.legend(loc=loss_legend_loc, fontsize='x-large')

    # 绘制评价准确率变化曲线
    if len(runner.dev_scores) > 0:
        plt.subplot(1, 2, 2)
        plt.plot(dev_steps, runner.dev_scores,
                 color=dev_color, linestyle=dev_linestyle, label="Dev accuracy")

        # 绘制坐标轴和图例
        plt.ylabel("score", fontsize=fontsize)
        plt.xlabel("step", fontsize=fontsize)
        plt.legend(loc=acc_legend_loc, fontsize='x-large')

    plt.savefig(fig_name)
    plt.show()

plot_training_loss_acc(runner, 'cnn-loss1.pdf')

代码执行结果如下图所示:
HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验_第4张图片


4. 模型评价

使用测试数据对在训练过程中保存的最佳模型进行评价,观察模型在测试集上的准确率以及损失变化情况。

# 加载最优模型
runner.load_model('best_model.pdparams')
# 模型评价
score, loss = runner.evaluate(test_loader)
print("[Test] accuracy/loss: {:.4f}/{:.4f}".format(score, loss))

代码执行结果:

[Test] accuracy/loss: 0.1250/2.2954

5. 模型预测

同样地,我们也可以使用保存好的模型,对测试集中的某一个数据进行模型预测,观察模型效果。

# 获取测试集中第一条数据
X, label = next(iter(test_loader))
logits = runner.predict(X)
# 多分类,使用softmax计算预测概率
pred = F.softmax(logits, dim=1)
# 获取概率最大的类别
pred_class = torch.argmax(pred[1]).numpy()
label = label[2].numpy()
# 输出真实类别与预测类别
print("The true category is {} and the predicted category is {}".format(label, pred_class))
# 可视化图片
plt.figure(figsize=(2, 2))
image, label = test_set[0][1], test_set[1][1]
image = np.array(image).astype('float32')
image = np.reshape(image, [28, 28])
image = Image.fromarray(image.astype('uint8'), mode='L')
plt.imshow(image)
plt.savefig('cnn-number2.pdf')
plt.show()

代码执行结果:

The true category is 6 and the predicted category is 7

执行代码后得到下图:
HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验_第5张图片


二、基于残差网络的手写体数字识别实验


三、实验Q&A

使用前馈神经网络实现MNIST识别,与LeNet效果对比。

代码实现如下:

import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision.datasets import mnist
from torchvision import transforms
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

train_batch_size = 64  # 超参数
test_batch_size = 128  # 超参数
learning_rate = 0.01  # 学习率
nums_epoches = 20  # 训练次数
lr = 0.1  # 优化器参数
momentum = 0.5  # 优化器参数
train_dataset = mnist.MNIST('./', train=True, transform=transforms.ToTensor(), target_transform=None, download=True)
test_dataset = mnist.MNIST('./', train=False, transform=transforms.ToTensor(), target_transform=None, download=False)
train_loader = DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=test_batch_size, shuffle=False)

class model(nn.Module):
    def __init__(self, in_dim, hidden_1, hidden_2, out_dim):
        super(model, self).__init__()
        self.layer1 = nn.Sequential(nn.Linear(in_dim, hidden_1, bias=True), nn.BatchNorm1d(hidden_1))
        self.layer2 = nn.Sequential(nn.Linear(hidden_1, hidden_2, bias=True), nn.BatchNorm1d(hidden_2))
        self.layer3 = nn.Sequential(nn.Linear(hidden_2, out_dim))

    def forward(self, x):
        # 注意 F 与 nn 下的激活函数使用起来不一样的
        x = F.relu(self.layer1(x))
        x = F.relu(self.layer2(x))
        x = self.layer3(x)
        return x

# 实例化网络
model = model(28 * 28, 300, 100, 10)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
# momentum:动量因子
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum)

# 开始训练 先定义存储损失函数和准确率的数组
losses = []
acces = []
# 测试用
eval_losses = []
eval_acces = []

for epoch in range(nums_epoches):
    # 每次训练先清零
    train_loss = 0
    train_acc = 0
    # 将模型设置为训练模式
    model.train()
    # 动态学习率
    if epoch % 5 == 0:
        optimizer.param_groups[0]['lr'] *= 0.1
    for img, label in train_loader:
        # 例如 img=[64,1,28,28] 做完view()后变为[64,1*28*28]=[64,784]
        # 把图片数据格式转换成与网络匹配的格式
        img = img.view(img.size(0), -1)
        # 前向传播,将图片数据传入模型中
        # out输出10维,分别是各数字的概率,即每个类别的得分
        out = model(img)
        # 这里注意参数out是64*10,label是一维的64
        loss = criterion(out, label)
        # 反向传播
        # optimizer.zero_grad()意思是把梯度置零,也就是把loss关于weight的导数变成0
        optimizer.zero_grad()
        loss.backward()
        # 这个方法会更新所有的参数,一旦梯度被如backward()之类的函数计算好后,我们就可以调用这个函数
        optimizer.step()
        # 记录误差
        train_loss += loss.item()
        # 计算分类的准确率,找到概率最大的下标
        _, pred = out.max(1)
        num_correct = (pred == label).sum().item()  # 记录标签正确的个数
        acc = num_correct / img.shape[0]
        train_acc += acc
    losses.append(train_loss / len(train_loader))
    acces.append(train_acc / len(train_loader))

    eval_loss = 0
    eval_acc = 0
    model.eval()
    for img, label in test_loader:
        img = img.view(img.size(0), -1)

        out = model(img)
        loss = criterion(out, label)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        eval_loss += loss.item()

        _, pred = out.max(1)
        num_correct = (pred == label).sum().item()
        acc = num_correct / img.shape[0]
        eval_acc += acc
    eval_losses.append(eval_loss / len(test_loader))
    eval_acces.append(eval_acc / len(test_loader))

    print('epoch:{},Train Loss:{:.4f},Train Acc:{:.4f},Test Loss:{:.4f},Test Acc:{:.4f}'
          .format(epoch, train_loss / len(train_loader), train_acc / len(train_loader),
                  eval_loss / len(test_loader), eval_acc / len(test_loader)))
plt.title('trainloss')
plt.plot(np.arange(len(losses)), losses)
plt.legend(['Train Loss'], loc='upper right')

# 测试
correct = 0
total = 0
y_predict = []
y_true = []
with torch.no_grad():
    for data in test_loader:
        input, target = data
        input = input.view(input.size(0), -1)
        output = model(input)  # 输出十个最大值
        _, predict = torch.max(output.data, dim=1)  # 元组取最大值的下表
        #
        # print('predict:',predict)
        total += target.size(0)
        correct += (predict == target).sum().item()
        y_predict.extend(predict.tolist())
        y_true.extend(target.tolist())
print('正确率:', correct / total)
print('correct:', correct)

代码执行结果:

epoch:0,Train Loss:0.3542,Train Acc:0.9165,Test Loss:0.1266,Test Acc:0.9627
epoch:1,Train Loss:0.1263,Train Acc:0.9657,Test Loss:0.0777,Test Acc:0.9776
epoch:2,Train Loss:0.0862,Train Acc:0.9767,Test Loss:0.0581,Test Acc:0.9827
epoch:3,Train Loss:0.0637,Train Acc:0.9831,Test Loss:0.0464,Test Acc:0.9870
epoch:4,Train Loss:0.0500,Train Acc:0.9870,Test Loss:0.0384,Test Acc:0.9882
epoch:5,Train Loss:0.0357,Train Acc:0.9917,Test Loss:0.0256,Test Acc:0.9949
epoch:6,Train Loss:0.0328,Train Acc:0.9925,Test Loss:0.0259,Test Acc:0.9949
epoch:7,Train Loss:0.0308,Train Acc:0.9937,Test Loss:0.0253,Test Acc:0.9953
epoch:8,Train Loss:0.0297,Train Acc:0.9936,Test Loss:0.0244,Test Acc:0.9954
epoch:9,Train Loss:0.0296,Train Acc:0.9934,Test Loss:0.0239,Test Acc:0.9958
epoch:10,Train Loss:0.0270,Train Acc:0.9949,Test Loss:0.0232,Test Acc:0.9960
epoch:11,Train Loss:0.0280,Train Acc:0.9943,Test Loss:0.0233,Test Acc:0.9959
epoch:12,Train Loss:0.0271,Train Acc:0.9944,Test Loss:0.0226,Test Acc:0.9958
epoch:13,Train Loss:0.0276,Train Acc:0.9940,Test Loss:0.0244,Test Acc:0.9952
epoch:14,Train Loss:0.0272,Train Acc:0.9944,Test Loss:0.0232,Test Acc:0.9958
epoch:15,Train Loss:0.0264,Train Acc:0.9949,Test Loss:0.0242,Test Acc:0.9951
epoch:16,Train Loss:0.0272,Train Acc:0.9947,Test Loss:0.0230,Test Acc:0.9956
epoch:17,Train Loss:0.0271,Train Acc:0.9948,Test Loss:0.0229,Test Acc:0.9960
epoch:18,Train Loss:0.0268,Train Acc:0.9948,Test Loss:0.0233,Test Acc:0.9957
epoch:19,Train Loss:0.0271,Train Acc:0.9946,Test Loss:0.0234,Test Acc:0.9959
正确率: 0.996
correct: 9960

执行代码后得到下图:
HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验_第6张图片
前馈神经网络运行结果比卷积神经网络要好,前馈神经网络的运行速度低于卷积神经网络。

上面的运行结果明显和paddlepaddle运行得到的结果差异很大

为什么?

改一下PyTorch代码:

# 数据预处理
transforms = Compose([Resize(32), ToTensor(), Normalize(mean=[0.5], std=[0.5])])

# 学习率
lr = 0.45

代码执行结果:

···
[Train] epoch: 0/5, step: 0/80, loss: 2.30833
[Train] epoch: 0/5, step: 15/80, loss: 2.30816
[Evaluate]  dev score: 0.39500, dev loss: 2.27583
[Evaluate] best accuracy performence has been updated: 0.00000 --> 0.39500
[Train] epoch: 1/5, step: 30/80, loss: 2.12486
[Evaluate]  dev score: 0.39000, dev loss: 1.95682
[Train] epoch: 2/5, step: 45/80, loss: 2.17857
[Evaluate]  dev score: 0.34000, dev loss: 2.01130
[Train] epoch: 3/5, step: 60/80, loss: 1.35790
[Evaluate]  dev score: 0.55000, dev loss: 1.36803
[Evaluate] best accuracy performence has been updated: 0.39500 --> 0.55000
[Train] epoch: 4/5, step: 75/80, loss: 0.61455
[Evaluate]  dev score: 0.75000, dev loss: 0.79454
[Evaluate] best accuracy performence has been updated: 0.55000 --> 0.75000
[Evaluate]  dev score: 0.76500, dev loss: 0.72680
[Evaluate] best accuracy performence has been updated: 0.75000 --> 0.76500
[Train] Training done!
[Test] accuracy/loss: 0.7350/0.7020
The true category is 6 and the predicted category is 6

执行代码后得到下图:
HBU_神经网络与深度学习 实验9 卷积神经网络:基于两种经典卷积神经网络的手写体数字识别实验_第7张图片
准确率终于靠谱一点儿了。

你可能感兴趣的:(python,深度学习,cnn)