目录
使用前馈神经网络实现MNIST识别,与LeNet效果对比。(选做)
5.3 基于LeNet实现手写体数字识别实验
在本节中,我们实现经典卷积网络LeNet-5,并进行手写体数字识别任务。
5.3.1数据
手写体数字识别是计算机视觉中最常用的图像分类任务,让计算机识别出给定图片中的手写体数字(0-9共10个数字)。由于手写体风格差异很大,因此手写体数字识别是具有一定难度的任务。
我们采用常用的手写数字识别数据集:MNIST数据集。MNIST数据集是计算机视觉领域的经典入门数据集,包含了60,000个训练样本和10,000个测试样本。这些数字已经过尺寸标准化并位于图像中心,图像是固定大小(28×28像素)。如下图给出了部分样本的实例。
为了节省训练时间,本节选取MNIST数据集的一个子集进行后续实验,数据集的划分为:
- 训练集:1,000条样本
- 验证集:200条样本
- 测试集:200条样本
MNIST数据集分为train_set、dev_set和test_set三个数据集,每个数据集含两个列表分别存放了图片数据以及标签数据。比如train_set包含:
- 图片数据:[1 000, 784]的二维列表,包含1 000张图片。每张图片用一个长度为784的向量表示,内容是 28×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
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')
5.3.1.1 数据预处理
图像分类网络对输入图片的格式、大小有一定的要求,数据输入模型前,需要对数据进行预处理操作,使图片满足网络训练以及预测的需要。本实验主要应用了如下方法:
- 调整图片大小:LeNet网络对输入图片大小的要求为 32×32 ,而MNIST数据集中的原始图片大小却是 28×28,这里为了符合网络的结构设计,将其调整为32×32;
- 规范化: 通过规范化手段,把输入图像的分布改变成均值为0,标准差为1的标准正态分布,使得最优解的寻优过程明显会变得平缓,训练过程更容易收敛。
在飞桨中,提供了部分视觉领域的高层API,可以直接调用API实现简单的图像处理操作。通过调用torchvision.transforms.Resize调整大小;调用torchvision.transforms.Normalize进行标准化处理;使用torchvision.transforms.Compose将两个预处理操作进行拼接。
代码实现如下:
from torchvision.transforms import Compose, Resize, Normalize
# 数据预处理
transforms = Compose([Resize(32), Normalize(mean=[127.5], std=[127.5], data_format='CHW')])
将原始的数据集封装为Dataset类,以便DataLoader调用。
import torch
import numpy as np
import random
from PIL import Image
class MNIST_dataset(torch.utils.data.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])
# 固定随机种子
random.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')
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
下面测试一下上面的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。
- 再经过一个全连接层的计算,最终得到了长度为类别数的输出结果。
考虑到自定义的Conv2D
和Pool2D
算子中包含多个for
循环,所以运算速度比较慢。飞桨框架中,针对卷积层算子和汇聚层算子进行了速度上的优化,这里基于torch.nn.Conv2D,
torch.nn.MaxPool2D
和torch.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')
结果:
这里还可以令两个网络加载同样的权重,测试一下两个网络的输出结果是否一致。
# 这里用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)
结果:
可以看到,输出结果是一致的。
这里还可以统计一下LeNet-5模型的参数量和计算量。
参数量
按照公式(5.18)进行计算,可以得到:
- 第一个卷积层的参数量为:6×1×5×5+6=156;
- 第二个卷积层的参数量为:16×6×5×5+16=2416;
- 第三个卷积层的参数量为:120×16×5×5+120=48120;
- 第一个全连接层的参数量为:120×84+84=10164;
- 第二个全连接层的参数量为:84×10+10=850;
所以,LeNet-5总的参数量为61706。
在飞桨中,还可以使用torch.summaryAPI自动计算参数量。
from torchsummary import summary
model = Torch_LeNet(in_channels=1, num_classes=10)
model=model.cuda()
params_info = summary(model, (1, 32, 32))
print(params_info)
结果:
可以看到,结果与公式推导一致。
计算量
按照公式(5.19)进行计算,可以得到:
- 第一个卷积层的计算量为:28×28×5×5×6×1+28×28×6=122304;
- 第二个卷积层的计算量为:10×10×5×5×16×6+10×10×16=241600;
- 第三个卷积层的计算量为:1×1×5×5×120×16+1×1×120=48120;
- 平均汇聚层的计算量为:16×5×5=400
- 第一个全连接层的计算量为:120×84=10080;
- 第二个全连接层的计算量为:84×10=840;
所以,LeNet-5总的计算量为423344。
在飞桨中,还可以使用torch.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")
结果:
[Train] epoch: 0/6, step: 0/96, loss: 2.31111
[Train] epoch: 0/6, step: 15/96, loss: 2.27632
[Evaluate] dev score: 0.23500, dev loss: 2.29150
[Evaluate] best accuracy performence has been updated: 0.00000 --> 0.23500
[Train] epoch: 1/6, step: 30/96, loss: 2.22310
[Evaluate] dev score: 0.48500, dev loss: 2.21202
[Evaluate] best accuracy performence has been updated: 0.23500 --> 0.48500
[Train] epoch: 2/6, step: 45/96, loss: 1.91117
[Evaluate] dev score: 0.34500, dev loss: 1.85476
[Train] epoch: 3/6, step: 60/96, loss: 1.63403
[Evaluate] dev score: 0.58000, dev loss: 1.38171
[Evaluate] best accuracy performence has been updated: 0.48500 --> 0.58000
[Train] epoch: 4/6, step: 75/96, loss: 0.86185
[Evaluate] dev score: 0.60000, dev loss: 1.09760
[Evaluate] best accuracy performence has been updated: 0.58000 --> 0.60000
[Train] epoch: 5/6, step: 90/96, loss: 0.52558
[Evaluate] dev score: 0.72000, dev loss: 1.00647
[Evaluate] best accuracy performence has been updated: 0.60000 --> 0.72000
[Evaluate] dev score: 0.76500, dev loss: 0.55406
[Evaluate] best accuracy performence has been updated: 0.72000 --> 0.76500
[Train] Training done!
可视化观察训练集与验证集的损失变化情况。
import matplotlib.pyplot as plt
# 可视化误差
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(test_loader())
logits = runner.predict(X)
# 多分类,使用softmax计算预测概率
pred = F.softmax(logits)
# 获取概率最大的类别
pred_class = torch.argmax(pred[1]).numpy()
label = label[1][0].numpy()
# 输出真实类别与预测类别
print("The true category is {} and the predicted category is {}".format(label[0], pred_class[0]))
# 可视化图片
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')
结果:
使用前馈神经网络实现MNIST识别,与LeNet效果对比。(选做)
import matplotlib.pyplot as plt
import torch
import time
import torch.nn.functional as F
from torch import nn, optim
from torchvision.datasets import MNIST
from torchvision.transforms import Compose, ToTensor, Normalize
from torch.utils.data import DataLoader
from sklearn.metrics import accuracy_score
# 超参数
BATCH_SIZE = 64 # 批次大小
EPOCHS = 5 # 迭代轮数
# 数据转换
transformers = Compose(transforms=[ToTensor(), Normalize(mean=(0.1307,), std=(0.3081,))])
#数据装载
dataset_train = MNIST(root=r'./pythonProject/mnist', train=True, download=False, transform=transformers)
dataset_test = MNIST(root=r'./pythonProject/mnist', train=False, download=False, transform=transformers)
dataloader_train = DataLoader(dataset=dataset_train, batch_size=BATCH_SIZE, shuffle=True)
dataloader_test = DataLoader(dataset=dataset_test, batch_size=BATCH_SIZE, shuffle=True)
# 定义前馈神经网络
class Model_MLP_L2_V3(nn.Module):
def __init__(self):
super(Model_MLP_L2_V3, self).__init__()
self.conv1 = torch.nn.Sequential(torch.nn.Conv2d(1, 10, kernel_size=(5, 5)), torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2))
self.conv2 = torch.nn.Sequential(torch.nn.Conv2d(10, 20, kernel_size=(5, 5)), torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2))
self.fc = torch.nn.Sequential(torch.nn.Linear(320, 50), torch.nn.Linear(50, 10))
def forward(self, x):
batch_size = x.size(0)
x = self.conv1(x) # 一层卷积层,一层池化层,一层激活层
x = self.conv2(x)
x = x.view(batch_size, -1) # flatten变成全连接网络需要的输入(batch, 20,4,4)==>(batch,320),-1此处自动算出的是320
x = self.fc(x)
return x
#LeNet
class LeNet(nn.Module):
# 定义网络结构
def __init__(self):
super(LeNet, self).__init__()
# 卷积层+池化层+卷积层
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=(3, 3), stride=(1, 1), padding=1)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3), stride=(1, 1), padding=1)
self.pool = nn.MaxPool2d(2, 2)
# dropout
self.dropout = nn.Dropout(p=0.25)
# 全连接层
self.fc1 = nn.Linear(64 * 7 * 7, 512)
self.fc2 = nn.Linear(512, 64)
self.fc3 = nn.Linear(64, 10)
# 计算
def forward(self, x):
# 初始形状[batch_size, 1, 28, 28]
x = self.pool(F.relu(self.conv1(x)))
x = self.dropout(x)
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 64 * 7 * 7)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
loss_func = nn.CrossEntropyLoss() # 交叉熵损失函数
# 记录损失值、准确率
loss_list, accuracy_list = [], []
# 计算准确率
def get_accuracy(model, datas, labels):
out = torch.softmax(model(datas), dim=1, dtype=torch.float32)
predictions = torch.max(input=out, dim=1)[1] # 最大值的索引
y_predict = predictions.data.numpy()
y_true = labels.data.numpy()
# accuracy = float(np.sum(y_predict == y_true)) / float(y_true.size) # 准确率
accuracy = accuracy_score(y_true, y_predict) # 准确率
return accuracy
# 训练
def train(model, optimizer, epoch):
model.train() # 模型训练
for i, (datas, labels) in enumerate(dataloader_train):
# 计算结果
out = model(datas)
# 计算损失值
loss = loss_func(out, labels)
# 梯度清零
optimizer.zero_grad()
# 反向传播
loss.backward()
# 梯度更新
optimizer.step()
# 打印损失值
if i % 100 == 0:
print('Train Epoch:%d Loss:%0.6f' % (epoch, loss.item()))
loss_list.append(loss.item())
# 测试
def test(model, epoch):
model.eval()
with torch.no_grad():
for i, (datas, labels) in enumerate(dataloader_test):
# 打印信息
if i % 20 == 0:
accuracy = get_accuracy(model, datas, labels)
print('Test Epoch:%d Accuracy:%0.6f' % (epoch, accuracy))
accuracy_list.append(accuracy)
# 运行
def run(model, optimizer, model_name):
for epoch in range(EPOCHS):
train(model, optimizer, epoch)
test(model, epoch)
# 绘制Loss曲线
plt.rcParams['figure.figsize'] = (16, 8)
plt.subplots(1, 2)
plt.subplot(1, 2, 1)
plt.plot(range(len(loss_list)), loss_list)
plt.title('Loss Curve')
plt.subplot(1, 2, 2)
plt.plot(range(len(accuracy_list)), accuracy_list)
plt.title('Accuracy Cure')
plt.show()
def initialize(model, model_name):
print(f'{model_name}')
# 优化器
optimizer = optim.Adam(params=model.parameters(), lr=0.001)
run(model, optimizer, model_name)
if __name__ == '__main__':
models = [Model_MLP_L2_V3(),
LeNet()]
model_names = ['Model_MLP_L2_V3', 'LeNet']
for model, model_name in zip(models, model_names):
initialize(model, model_name)
结果:
Model_MLP_L2_V3
Train Epoch:0 Loss:2.304879
Train Epoch:0 Loss:0.162369
Train Epoch:0 Loss:0.283583
Train Epoch:0 Loss:0.074659
Train Epoch:0 Loss:0.264941
Train Epoch:0 Loss:0.110492
Train Epoch:0 Loss:0.068290
Train Epoch:0 Loss:0.103438
Train Epoch:0 Loss:0.109880
Train Epoch:0 Loss:0.074634
Test Epoch:0 Accuracy:1.000000
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.953125
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:1.000000
Test Epoch:0 Accuracy:0.984375
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.953125
Train Epoch:1 Loss:0.046762
Train Epoch:1 Loss:0.055487
Train Epoch:1 Loss:0.139215
Train Epoch:1 Loss:0.068915
Train Epoch:1 Loss:0.014989
Train Epoch:1 Loss:0.121642
Train Epoch:1 Loss:0.098162
Train Epoch:1 Loss:0.021184
Train Epoch:1 Loss:0.086161
Train Epoch:1 Loss:0.010311
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.968750
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.953125
Train Epoch:2 Loss:0.039069
Train Epoch:2 Loss:0.062444
Train Epoch:2 Loss:0.016014
Train Epoch:2 Loss:0.028385
Train Epoch:2 Loss:0.015349
Train Epoch:2 Loss:0.052743
Train Epoch:2 Loss:0.098162
Train Epoch:2 Loss:0.028939
Train Epoch:2 Loss:0.026430
Train Epoch:2 Loss:0.019552
Test Epoch:2 Accuracy:0.984375
Test Epoch:2 Accuracy:0.984375
Test Epoch:2 Accuracy:1.000000
Test Epoch:2 Accuracy:0.984375
Test Epoch:2 Accuracy:0.968750
Test Epoch:2 Accuracy:0.984375
Test Epoch:2 Accuracy:1.000000
Test Epoch:2 Accuracy:1.000000
Train Epoch:3 Loss:0.020695
Train Epoch:3 Loss:0.014993
Train Epoch:3 Loss:0.046973
Train Epoch:3 Loss:0.005308
Train Epoch:3 Loss:0.004479
Train Epoch:3 Loss:0.003790
Train Epoch:3 Loss:0.008464
Train Epoch:3 Loss:0.021006
Train Epoch:3 Loss:0.090460
Train Epoch:3 Loss:0.048635
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:0.984375
Test Epoch:3 Accuracy:0.984375
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:1.000000
Train Epoch:4 Loss:0.001347
Train Epoch:4 Loss:0.006823
Train Epoch:4 Loss:0.039667
Train Epoch:4 Loss:0.027812
Train Epoch:4 Loss:0.066850
Train Epoch:4 Loss:0.028142
Train Epoch:4 Loss:0.076361
Train Epoch:4 Loss:0.008753
Train Epoch:4 Loss:0.001639
Train Epoch:4 Loss:0.023208
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.968750
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:1.000000
LeNet
Train Epoch:0 Loss:2.304794
Train Epoch:0 Loss:0.215691
Train Epoch:0 Loss:0.050204
Train Epoch:0 Loss:0.085204
Train Epoch:0 Loss:0.126212
Train Epoch:0 Loss:0.054313
Train Epoch:0 Loss:0.089874
Train Epoch:0 Loss:0.075718
Train Epoch:0 Loss:0.017894
Train Epoch:0 Loss:0.180424
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.984375
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.984375
Test Epoch:0 Accuracy:0.984375
Test Epoch:0 Accuracy:1.000000
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.984375
Train Epoch:1 Loss:0.069641
Train Epoch:1 Loss:0.037744
Train Epoch:1 Loss:0.063520
Train Epoch:1 Loss:0.006902
Train Epoch:1 Loss:0.041781
Train Epoch:1 Loss:0.023375
Train Epoch:1 Loss:0.008915
Train Epoch:1 Loss:0.095643
Train Epoch:1 Loss:0.032320
Train Epoch:1 Loss:0.042086
Test Epoch:1 Accuracy:0.968750
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:1.000000
Test Epoch:1 Accuracy:1.000000
Test Epoch:1 Accuracy:1.000000
Test Epoch:1 Accuracy:1.000000
Train Epoch:2 Loss:0.038557
Train Epoch:2 Loss:0.034732
Train Epoch:2 Loss:0.037645
Train Epoch:2 Loss:0.038753
Train Epoch:2 Loss:0.042802
Train Epoch:2 Loss:0.020938
Train Epoch:2 Loss:0.010180
Train Epoch:2 Loss:0.028913
Train Epoch:2 Loss:0.025766
Train Epoch:2 Loss:0.059251
Test Epoch:2 Accuracy:0.968750
Test Epoch:2 Accuracy:0.984375
Test Epoch:2 Accuracy:1.000000
Test Epoch:2 Accuracy:1.000000
Test Epoch:2 Accuracy:0.984375
Test Epoch:2 Accuracy:1.000000
Test Epoch:2 Accuracy:0.984375
Test Epoch:2 Accuracy:1.000000
Train Epoch:3 Loss:0.028239
Train Epoch:3 Loss:0.002824
Train Epoch:3 Loss:0.097086
Train Epoch:3 Loss:0.025638
Train Epoch:3 Loss:0.011735
Train Epoch:3 Loss:0.125769
Train Epoch:3 Loss:0.006783
Train Epoch:3 Loss:0.091295
Train Epoch:3 Loss:0.052073
Train Epoch:3 Loss:0.003978
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:0.984375
Test Epoch:3 Accuracy:0.984375
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:0.984375
Test Epoch:3 Accuracy:0.984375
Test Epoch:3 Accuracy:1.000000
Train Epoch:4 Loss:0.040038
Train Epoch:4 Loss:0.023836
Train Epoch:4 Loss:0.002591
Train Epoch:4 Loss:0.022975
Train Epoch:4 Loss:0.014851
Train Epoch:4 Loss:0.024593
Train Epoch:4 Loss:0.013239
Train Epoch:4 Loss:0.003050
Train Epoch:4 Loss:0.014961
Train Epoch:4 Loss:0.024362
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:0.953125
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.968750
Test Epoch:4 Accuracy:1.000000
结果:
通过对比可得LeNet网络loss下降更快且普遍比FNN更低,准确率也普遍比FNN高。
心得体会
通过本次实验对LeNet网络的构建和参数量、计算量有了更深的了解,通过使用前馈神经网络识别MNIST数据集与LeNet网络进行对比对训练效果有了更直观的掌握。
ref
基于pytorch平台实现对MNIST数据集的分类分析(前馈神经网络、softmax)基础版