NNDL 实验六 卷积神经网络(3)LeNet实现MNIST

目录

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

5.3.1 数据

5.3.1.1 数据预处理

5.3.2 模型构建

5.3.3 模型训练

5.3.4 模型评价

5.3.5 模型预测

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

可视化LeNet中的部分特征图和卷积核,谈谈自己的看法(选做)

总结:


常用的手写数字识别数据集:MNIST数据集。MNIST handwritten digit database, Yann LeCun, Corinna Cortes and Chris Burges

MNIST数据集是计算机视觉领域的经典入门数据集,包含了60,000个训练样本和10,000个测试样本。

这些数字已经过尺寸标准化并位于图像中心,图像是固定大小(28×28像素)。

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

LeNet-5虽然提出的时间比较早,但它是一个非常成功的神经网络模型。

基于LeNet-5的手写数字识别系统在20世纪90年代被美国很多银行使用,用来识别支票上面的手写数字。

5.3.1 数据

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

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

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

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

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

import json
import gzip

# 打印并观察数据集分布情况
train_set, dev_set, test_set = json.load(gzip.open('mnist.json.gz'))
train_images, train_labels = train_set[0][:1000], train_set[1][:1000]
dev_images, dev_labels = dev_set[0][:200], dev_set[1][:200]
test_images, test_labels = test_set[0][:200], test_set[1][:200]
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])))

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

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
 
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')

5.3.1.1 数据预处理

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

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

代码实现如下:

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

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

import random
from torch.utils.data import Dataset,DataLoader
 
class MNIST_dataset(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])
 
 
# 加载 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')

5.3.2 模型构建

这里的LeNet-5和原始版本有4点不同:

  • C3层没有使用连接表来减少卷积数量。
  • 汇聚层使用了简单的平均汇聚,没有引入权重和偏置参数以及非线性激活函数。
  • 卷积层的激活函数使用ReLU函数。
  • 最后的输出层为一个全连接线性层。

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

具体实现如下:

import torch.nn.functional as F
import torch.nn as nn
import  torch
 
class Model_LeNet(nn.Module):
    def __init__(self, in_channels, num_classes=10):
        super(Model_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, 2), stride=2)
        # 卷积层:输入通道数为6,输出通道数为16,卷积核大小为5×5,步长为1
        self.conv3 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5, stride=1)
        # 汇聚层:汇聚窗口为2×2,步长为2
        self.pool4 = nn.AvgPool2d(kernel_size=(2, 2), stride=2)
        # 卷积层:输入通道数为16,输出通道数为120,卷积核大小为5×5
        self.conv5 = nn.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

1.测试LeNet-5模型,构造一个形状为 [1,1,32,32]的输入数据送入网络,观察每一层特征图的形状变化。

代码实现如下:

import numpy as np
 
# 这里用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中所包含的子层
print(model.named_parameters())
x = torch.tensor(inputs)
for item in model.children():
    # item是LeNet类中的一个子层
    # 查看经过子层之后的输出数据形状
    item_shapex = 0
    names = []
    parameter = []
    for name in item.named_parameters():
        names.append(name[0])
        parameter.append(name[1])
        item_shapex += 1
    try:
        x = item(x)
    except:
        # 如果是最后一个卷积层输出,需要展平后才可以送入全连接层
        x = x.reshape([x.shape[0], -1])
        x = item(x)
 
    if item_shapex == 2:
        # 查看卷积和全连接层的数据和参数的形状,
        # 其中item.parameters()[0]是权重参数w,item.parameters()[1]是偏置参数b
        print(item, x.shape, parameter[0].shape, parameter[1].shape)
    else:
        # 汇聚层没有参数
        print(item, x.shape)

结果:

 从输出结果看,

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

2.

使用自定义算子,构建LeNet-5模型

自定义的Conv2D和Pool2D算子中包含多个for循环,所以运算速度比较慢。

飞桨框架中,针对卷积层算子和汇聚层算子进行了速度上的优化,这里基于paddle.nn.Conv2D、paddle.nn.MaxPool2D和paddle.nn.AvgPool2D构建LeNet-5模型,对比与上边实现的模型的运算速度。

使用pytorch中的相应算子,构建LeNet-5模型

torch.nn.Conv2d();torch.nn.MaxPool2d();torch.nn.avg_pool2d()

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

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

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')

结果: 

4.令两个网络加载同样的权重,测试一下两个网络的输出结果是否一致。

# 这里用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)

结果:

可以看到,输出结果是一致的。 

5.统计LeNet-5模型的参数量和计算量。

参数量

按照公式(5.18)进行计算,可以得到:

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

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

在pytorch中,还可以使用torchsummaryAPI自动计算参数量。

from torchsummary import summary
model = Torch_LeNet(in_channels=1, num_classes=10)
params_info = summary(model, (1, 32, 32))
print(params_info)

运行结果:

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

计算量

按照公式(5.19)进行计算,可以得到:

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

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

在飞桨中,还可以使用paddle.flopsAPI自动统计计算量。pytorch可以么?

答:可以,在torch中可以使用torchstat统计计算量。

from torchstat import stat
 
model =Torch_LeNet(in_channels=1, num_classes=10)
# 导入模型,输入一张输入图片的尺寸
stat(model, (1, 32,32))

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

5.3.3 模型训练

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

import torch.optim as opti
torch.manual_seed(100)
# 学习率大小
lr = 0.1
# 批次大小
batch_size = 64
# 加载数据
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
dev_loader = DataLoader(dev_dataset, batch_size=batch_size)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
model = Model_LeNet(in_channels=1, num_classes=10)
optimizer = opti.SGD(model.parameters(), 0.2)
# 定义损失函数
loss_fn = F.cross_entropy
# 定义评价指标
metric = Accuracy()
# 实例化 RunnerV3 类,并传入训练配置。
runner = RunnerV3(model, optimizer, loss_fn, metric)
# 启动训练
log_steps = 15
eval_steps = 15
runner.train(train_loader, dev_loader, num_epochs=6, log_steps=log_steps,eval_steps=eval_steps, save_path="best_model.pdparams")
 

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

# 可视化误差
def plot(runner, fig_name):
    plt.figure(figsize=(10, 5))
 
    plt.subplot(1, 2, 1)
    train_items = runner.train_step_losses[::30]
    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='#8E004D', label="Train loss")
    if runner.dev_losses[0][0] != -1:
        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='#E20079', linestyle='--', label="Dev loss")
    # 绘制坐标轴和图例
    plt.ylabel("loss", fontsize='x-large')
    plt.xlabel("step", fontsize='x-large')
    plt.legend(loc='upper right', fontsize='x-large')
 
    plt.subplot(1, 2, 2)
    # 绘制评价准确率变化曲线
    if runner.dev_losses[0][0] != -1:
        plt.plot(dev_steps, runner.dev_scores,
                 color='#E20079', linestyle="--", label="Dev accuracy")
    else:
        plt.plot(list(range(len(runner.dev_scores))), runner.dev_scores,
                 color='#E20079', linestyle="--", label="Dev accuracy")
    # 绘制坐标轴和图例
    plt.ylabel("score", fontsize='x-large')
    plt.xlabel("step", fontsize='x-large')
    plt.legend(loc='lower right', fontsize='x-large')
 
    plt.savefig(fig_name)
    plt.show()
 
 
runner.load_model('best_model.pdparams')
plot(runner, 'cnn-loss1.pdf')

5.3.4 模型评价

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

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

5.3.5 模型预测

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

# 获取测试集中第一条数
X, label = next(iter(test_loader))
logits = runner.predict(X)
# 多分类,使用softmax计算预测概率
pred = F.softmax(logits,dim=1)
print(pred.shape)
# 获取概率最大的类别
pred_class = torch.argmax(pred[2]).numpy()
print(pred_class)
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][2], test_set[1][2]
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')

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

import torch
from torchvision import transforms  # 对图像进行原始的数据处理的工具
from torchvision import datasets  # 获取数据
from torch.utils.data import DataLoader  # 加载数据
import torch.nn.functional as F  # 与全连接层中的relu激活函数 有关
import torch.optim as optim  # 与优化器有关
 
 
batch_size = 64
transform = transforms.Compose([  # 处理图像
    transforms.ToTensor(),  # Convert the PIL Image to Tensor
    transforms.Normalize((0.1307,), (0.3081,))  # 归一化;0.1307为均值,0.3081为标准差
])
 
train_dataset = datasets.MNIST(root='./dataset/mnist/', train=True, download=True, transform=transform)
# download=True表示自动下载MNIST数据集
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root='./dataset/mnist/', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)
 
 
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.l1 = torch.nn.Linear(784, 512)
        self.l2 = torch.nn.Linear(512, 256)
        self.l3 = torch.nn.Linear(256, 128)
        self.l4 = torch.nn.Linear(128, 64)
        self.l5 = torch.nn.Linear(64, 10)
 
    def forward(self, x):
        x = x.view(-1, 784)  # -1其实就是自动获取mini_batch
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = F.relu(self.l4(x))
        return self.l5(x)  # 最后一层不做激活,不进行非线性变换
 
 
model = Net()
 
criterion = torch.nn.CrossEntropyLoss()  # 构建损失函数
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
 
def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        # 获得一个批次的数据和标签
        inputs, target = data
        optimizer.zero_grad()
        # 获得模型预测结果(64, 10)
        outputs = model(inputs)
        # 交叉熵代价函数outputs(64,10),target(64)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()
 
        running_loss += loss.item()
        if batch_idx % 300 == 299:  # batch_idx最大值为937;937*64=59968 意味着丢弃了部分的样本
            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
            # 注:在python中,通过使用%,实现格式化字符串的目的;%d 有符号整数(十进制)
            running_loss = 0.0
 
 
def test():
    correct = 0  # 正确预测的数量
    total = 0  # 总数量
    with torch.no_grad():  # 测试的时候不需要计算梯度(避免产生计算图)
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)  # dim = 1 列是第0个维度,行是第1个维度
            total += labels.size(0)
            correct += (predicted == labels).sum().item()  # 张量之间的比较运算
    print('accuracy on test set: %d %% ' % (100 * correct / total))
 
 
if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

前馈神经网络在开始时就能获得很高的准确率,LeNet在刚开始的时候的准确率比较低,而运行速度比前馈神经网络快。

可视化LeNet中的部分特征图和卷积核,谈谈自己的看法(选做)

class Paddle_LeNet1(nn.Module):
    def __init__(self, in_channels, num_classes=10):
        super(Paddle_LeNet1, 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):
        image=[]
        # C1:卷积层+激活函数
        output = F.relu(self.conv1(x))
        image.append(output)
        # S2:汇聚层
        output = self.pool2(output)
 
        # C3:卷积层+激活函数
        output = F.relu(self.conv3(output))
        image.append(output)
        # S4:汇聚层
        output = self.pool4(output)
        # C5:卷积层+激活函数
        output = F.relu(self.conv5(output))
        image.append(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 image
 
 
# create model
model1 = Paddle_LeNet1(in_channels=1, num_classes=10)
 
 
# model_weight_path ="./AlexNet.pth"
model_weight_path = 'best_model.pdparams'
model1.load_state_dict(torch.load(model_weight_path))
 
 
# forward正向传播过程
out_put = model1(X)
print(out_put[0].shape)
for i in range(0,3):
 for feature_map in out_put[i]:
    # [N, C, H, W] -> [C, H, W]    维度变换
    im = np.squeeze(feature_map.detach().numpy())
    # [C, H, W] -> [H, W, C]
    im = np.transpose(im, [1, 2, 0])
    print(im.shape)
 
    # show 9 feature maps
    plt.figure()
    for i in range(6):
        ax = plt.subplot(2, 3, i + 1)  # 参数意义:3:图片绘制行数,5:绘制图片列数,i+1:图的索引
        # [H, W, C]
        # 特征矩阵每一个channel对应的是一个二维的特征矩阵,就像灰度图像一样,channel=1
        # plt.imshow(im[:, :, i])i,,
        plt.imshow(im[:, :, i], cmap='gray')
    plt.show()
    break

 

斋藤康毅:

图灵社区

​ 

​ 

​ 

​ 

​ 

总结:

通过本次实验对LeNet网络有了更多的认识和理解,学习到了参数量、计算量,测试了网络的运算速度。印象最深的还是选做题,比较使用前馈神经网络识别MNIST数据集和使用LeNet网络识别。还可视化了LeNet中的部分特征图和卷积核,通过老师分享的资料学习到了鱼书中关于这部分的知识。前馈神经网络需要学习的内容还有很多,还是需要自己课下花时间多研究的,多学习理解优秀的文章。

参考:
NNDL 实验六 卷积神经网络(3)LeNet实现MNIST_HBU_David的博客-CSDN博客_lenet实现mnist

NNDL 实验六 卷积神经网络(3)LeNet实现MNIST_别被打脸的博客-CSDN博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值