目录
5.3 基于LeNet实现手写体数字识别实验
5.3.1 数据
5.3.1.1 数据预处理
5.3.2 模型构建
1.测试LeNet-5模型,构造一个形状为 [1,1,32,32]的输入数据送入网络,观察每一层特征图的形状变化。
2.使用自定义算子,构建LeNet-5模型
3.测试两个网络的运算速度。
4.令两个网络加载同样的权重,测试一下两个网络的输出结果是否一致。
5.这里还可以统计一下LeNet-5模型的参数量和计算量。
5.3.3 模型训练
5.3.4 模型评价
5.3.5 模型预测
使用前馈神经网络实现MNIST识别,与LeNet效果对比。(选做)
可视化LeNet中的部分特征图和卷积核,谈谈自己的看法。(选做)
手写体数字识别是计算机视觉中最常用的图像分类任务,让计算机识别出给定图片中的手写体数字(0-9共10个数字)。由于手写体风格差异很大,因此手写体数字识别是具有一定难度的任务。
我们采用常用的手写数字识别数据集:MNIST数据集。MNIST数据集是计算机视觉领域的经典入门数据集,包含了60,000个训练样本和10,000个测试样本。这些数字已经过尺寸标准化并位于图像中心,图像是固定大小(28×28像素)。
LeNet-5虽然提出的时间比较早,但它是一个非常成功的神经网络模型。基于LeNet-5的手写数字识别系统在20世纪90年代被美国很多银行使用,用来识别支票上面的手写数字。LeNet-5的网络结构如下图所示。
为了节省训练时间,本节选取MNIST数据集的一个子集进行后续实验,数据集的划分为:
MNIST数据集分为train_set、dev_set和test_set三个数据集,每个数据集含两个列表分别存放了图片数据以及标签数据。比如train_set包含:
观察数据集分布情况,代码实现如下:
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')
图像分类网络对输入图片的格式、大小有一定的要求,数据输入模型前,需要对数据进行预处理操作,使图片满足网络训练以及预测的需要。本实验主要应用了如下方法:
代码实现如下:
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')
这里的LeNet-5和原始版本有4点不同:
网络共有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
代码实现如下:
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)
从输出结果看,
自定义的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
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)
可以看到,输出结果是一致的。
参数量
按照公式(5.18)进行计算,可以得到:
所以,LeNet-5总的参数量为6170661706。
在pytorch中,还可以使用torchsummaryAPI自动计算参数量。
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)进行计算,可以得到:
所以,LeNet-5总的计算量为423344
在飞桨中,还可以使用paddle.flops
API自动统计计算量。pytorch可以么?
可以,在torch中可以使用torchstat统计计算量。
from torchstat import stat
model =Torch_LeNet(in_channels=1, num_classes=10)
# 导入模型,输入一张输入图片的尺寸
stat(model, (1, 32,32))
可以看到,结果与公式推导一致。
使用交叉熵损失函数,并用随机梯度下降法作为优化器来训练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")
可视化观察训练集与验证集的损失变化情况。
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')
使用测试数据对在训练过程中保存的最佳模型进行评价,观察模型在测试集上的准确率以及损失变化情况。
# 加载最优模型
runner.load_model('best_model.pdparams')
# 模型评价
score, loss = runner.evaluate(test_loader)
print("[Test] accuracy/loss: {:.4f}/{:.4f}".format(score, loss))
同样地,我们也可以使用保存好的模型,对测试集中的某一个数据进行模型预测,观察模型效果。
# 获取测试集中第一条数据
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')
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, Resize
from torch.utils.data import DataLoader
from sklearn.metrics import accuracy_score
# 超参数
BATCH_SIZE = 64 # 批次大小
EPOCHS = 5 # 迭代轮数
# 设备
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
# 数据转换
transformers = Compose(transforms=[ToTensor(), Normalize(mean=(0.1307,), std=(0.3081,))])
# 数据装载
dataset_train = MNIST(root=r'./data', train=True, download=False, transform=transformers)
dataset_test = MNIST(root=r'./data', 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)
# FNN
class FNN(nn.Module):
# 定义网络结构
def __init__(self):
super(FNN, self).__init__()
self.layer1 = nn.Linear(28 * 28, 28) # 隐藏层
self.out = nn.Linear(28, 10) # 输出层
# 计算
def forward(self, x):
# 初始形状[batch_size, 1, 28, 28]
x = x.view(-1, 28 * 28)
x = torch.relu(self.layer1(x)) # 使用relu函数激活
x = self.out(x) # 输出层
return x
# CNN
class CNN(nn.Module):
# 定义网络结构
def __init__(self):
super(CNN, 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.to('cpu').data.numpy()
y_true = labels.to('cpu').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):
# 设备转换
datas = datas.to(DEVICE)
labels = labels.to(DEVICE)
# 计算结果
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):
# 设备转换
datas = datas.to(DEVICE)
labels = labels.to(DEVICE)
# 打印信息
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):
t1 = time.time()
for epoch in range(EPOCHS):
train(model, optimizer, epoch)
test(model, epoch)
t2 = time.time()
print(f'共耗时{t2 - t1}秒')
# 绘制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'Start {model_name}')
# 查看分配显存
print('GPU_Allocated:%d' % torch.cuda.memory_allocated())
# 优化器
optimizer = optim.Adam(params=model.parameters(), lr=0.001)
run(model, optimizer, model_name)
if __name__ == '__main__':
models = [FNN().to(DEVICE),
CNN().to(DEVICE)]
model_names = ['FNN', 'CNN']
for model, model_name in zip(models, model_names):
initialize(model, model_name)
Start FNN
GPU_Allocated:6726144
Train Epoch:0 Loss:2.375047
Train Epoch:0 Loss:0.487770
Train Epoch:0 Loss:0.309409
Train Epoch:0 Loss:0.161553
Train Epoch:0 Loss:0.359490
Train Epoch:0 Loss:0.558052
Train Epoch:0 Loss:0.398713
Train Epoch:0 Loss:0.264075
Train Epoch:0 Loss:0.505945
Train Epoch:0 Loss:0.324596
Test Epoch:0 Accuracy:0.890625
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.906250
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.921875
Test Epoch:0 Accuracy:0.953125
Test Epoch:0 Accuracy:0.906250
Test Epoch:0 Accuracy:0.906250
Train Epoch:1 Loss:0.211096
Train Epoch:1 Loss:0.180755
Train Epoch:1 Loss:0.180979
Train Epoch:1 Loss:0.082437
Train Epoch:1 Loss:0.167887
Train Epoch:1 Loss:0.210127
Train Epoch:1 Loss:0.172560
Train Epoch:1 Loss:0.198250
Train Epoch:1 Loss:0.136321
Train Epoch:1 Loss:0.337761
Test Epoch:1 Accuracy:0.953125
Test Epoch:1 Accuracy:0.921875
Test Epoch:1 Accuracy:0.890625
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.937500
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.953125
Test Epoch:1 Accuracy:0.953125
Train Epoch:2 Loss:0.182056
Train Epoch:2 Loss:0.136325
Train Epoch:2 Loss:0.083841
Train Epoch:2 Loss:0.113584
Train Epoch:2 Loss:0.089297
Train Epoch:2 Loss:0.118878
Train Epoch:2 Loss:0.101036
Train Epoch:2 Loss:0.149545
Train Epoch:2 Loss:0.173542
Train Epoch:2 Loss:0.081950
Test Epoch:2 Accuracy:0.968750
Test Epoch:2 Accuracy:0.953125
Test Epoch:2 Accuracy:0.937500
Test Epoch:2 Accuracy:0.937500
Test Epoch:2 Accuracy:0.921875
Test Epoch:2 Accuracy:0.968750
Test Epoch:2 Accuracy:0.953125
Test Epoch:2 Accuracy:0.921875
Train Epoch:3 Loss:0.103856
Train Epoch:3 Loss:0.139319
Train Epoch:3 Loss:0.154465
Train Epoch:3 Loss:0.099467
Train Epoch:3 Loss:0.178826
Train Epoch:3 Loss:0.178021
Train Epoch:3 Loss:0.414776
Train Epoch:3 Loss:0.044757
Train Epoch:3 Loss:0.142585
Train Epoch:3 Loss:0.103355
Test Epoch:3 Accuracy:0.953125
Test Epoch:3 Accuracy:0.953125
Test Epoch:3 Accuracy:0.953125
Test Epoch:3 Accuracy:0.984375
Test Epoch:3 Accuracy:0.937500
Test Epoch:3 Accuracy:0.953125
Test Epoch:3 Accuracy:0.968750
Test Epoch:3 Accuracy:0.968750
Train Epoch:4 Loss:0.038627
Train Epoch:4 Loss:0.189685
Train Epoch:4 Loss:0.050275
Train Epoch:4 Loss:0.057730
Train Epoch:4 Loss:0.047852
Train Epoch:4 Loss:0.087336
Train Epoch:4 Loss:0.031808
Train Epoch:4 Loss:0.045069
Train Epoch:4 Loss:0.083553
Train Epoch:4 Loss:0.121792
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.953125
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.968750
Test Epoch:4 Accuracy:0.968750
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.953125
共耗时57.37505865097046秒
Start CNN
GPU_Allocated:6816768
Train Epoch:0 Loss:2.295992
Train Epoch:0 Loss:0.218390
Train Epoch:0 Loss:0.227322
Train Epoch:0 Loss:0.113204
Train Epoch:0 Loss:0.046523
Train Epoch:0 Loss:0.077850
Train Epoch:0 Loss:0.071634
Train Epoch:0 Loss:0.049825
Train Epoch:0 Loss:0.086670
Train Epoch:0 Loss:0.017135
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.953125
Test Epoch:0 Accuracy:1.000000
Test Epoch:0 Accuracy:1.000000
Test Epoch:0 Accuracy:0.984375
Test Epoch:0 Accuracy:0.984375
Test Epoch:0 Accuracy:0.968750
Test Epoch:0 Accuracy:0.984375
Train Epoch:1 Loss:0.024688
Train Epoch:1 Loss:0.111760
Train Epoch:1 Loss:0.027320
Train Epoch:1 Loss:0.005744
Train Epoch:1 Loss:0.049898
Train Epoch:1 Loss:0.093255
Train Epoch:1 Loss:0.050449
Train Epoch:1 Loss:0.008950
Train Epoch:1 Loss:0.003847
Train Epoch:1 Loss:0.034719
Test Epoch:1 Accuracy:1.000000
Test Epoch:1 Accuracy:1.000000
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:1.000000
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.984375
Test Epoch:1 Accuracy:0.968750
Test Epoch:1 Accuracy:1.000000
Train Epoch:2 Loss:0.025615
Train Epoch:2 Loss:0.014122
Train Epoch:2 Loss:0.024139
Train Epoch:2 Loss:0.020173
Train Epoch:2 Loss:0.005790
Train Epoch:2 Loss:0.009601
Train Epoch:2 Loss:0.024010
Train Epoch:2 Loss:0.037900
Train Epoch:2 Loss:0.001027
Train Epoch:2 Loss:0.015340
Test Epoch:2 Accuracy:1.000000
Test Epoch:2 Accuracy:1.000000
Test Epoch:2 Accuracy:1.000000
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
Train Epoch:3 Loss:0.005868
Train Epoch:3 Loss:0.032232
Train Epoch:3 Loss:0.010090
Train Epoch:3 Loss:0.004378
Train Epoch:3 Loss:0.019720
Train Epoch:3 Loss:0.008472
Train Epoch:3 Loss:0.001280
Train Epoch:3 Loss:0.102997
Train Epoch:3 Loss:0.049539
Train Epoch:3 Loss:0.118767
Test Epoch:3 Accuracy:0.968750
Test Epoch:3 Accuracy:1.000000
Test Epoch:3 Accuracy:1.000000
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.002708
Train Epoch:4 Loss:0.001630
Train Epoch:4 Loss:0.001386
Train Epoch:4 Loss:0.003931
Train Epoch:4 Loss:0.001605
Train Epoch:4 Loss:0.035478
Train Epoch:4 Loss:0.004013
Train Epoch:4 Loss:0.024497
Train Epoch:4 Loss:0.000618
Train Epoch:4 Loss:0.005133
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:1.000000
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.984375
Test Epoch:4 Accuracy:0.984375
共耗时67.44729924201965秒
Process finished with exit code 0
对比准确率和loss上,LeNet要明显好于FNN差别不大,但FNN训练时间比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
斋藤康毅:
深度学习入门:基于Python的理论与实现 (ituring.com.cn)
总结:
在此次实验刚开始时遇到了一个小问题 使用数据集显示的图出现异常(如下)后来通过询问同学重新更换一遍数据集就很神奇的恢复了,后面基于LeNet 实现手写数字识别就比较顺利的完成,选做题也很有意思,前馈神经网络和LeNet进行了对比,体会到了他们的区别
ref:
https://blog.csdn.net/qq_38975453/article/details/126799661
NNDL 实验5(上) - HBU_DAVID - 博客园 (cnblogs.com)
6. 卷积神经网络 — 动手学深度学习 2.0.0-beta1 documentation (d2l.ai)
7. 现代卷积神经网络 — 动手学深度学习 2.0.0-beta1 documentation (d2l.ai)