目录
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中的部分特征图和卷积核,谈谈自己的看法。(选做)
参考资料
本节将实现经典卷积网络LeNet-5,并进行手写体数字识别任务。
LeNet-5虽然提出的时间比较早,但它是一个非常成功的神经网络模型。基于LeNet-5的手写数字识别系统在20世纪90年代被美国很多银行使用,用来识别支票上面的手写数字。
手写体数字识别是计算机视觉中最常用的图像分类任务,让计算机识别出给定图片中的手写体数字(0-9共10个数字)。由于手写体风格差异很大,因此手写体数字识别是具有一定难度的任务。
我们采用常用的手写数字识别数据集:MNIST数据集。
MNIST handwritten digit database, Yann LeCun, Corinna Cortes and Chris Burges
MNIST数据集是计算机视觉领域的经典入门数据集,包含了60,000个训练样本和10,000个测试样本。这些数字已经过尺寸标准化并位于图像中心,图像是固定大小(28×28像素)。下图给出了部分样本的示例。
为了节省训练时间,本节选取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 matplotlib.pyplot as plt
from PIL import Image
import numpy as np
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虽然提出的时间比较早,但它是一个非常成功的神经网络模型。基于LeNet-5的手写数字识别系统在20世纪90年代被美国很多银行使用,用来识别支票上面的手写数字。LeNet-5的网络结构如下图所示。
我们使用上面定义的卷积层算子和汇聚层算子构建一个LeNet-5模型。
这里的LeNet-5和原始版本有4点不同:
- C3层没有使用连接表来减少卷积数量。
- 汇聚层使用了简单的平均汇聚,没有引入权重和偏置参数以及非线性激活函数。
- 卷积层的激活函数使用ReLU函数。
- 最后的输出层为一个全连接线性层。
网络共有7层,包含3个卷积层、2个汇聚层以及2个全连接层的简单卷积神经网络接,受输入图像大小为32×32=1024,输出对应10个类别的得分。具体实现如下:
import torch.nn.functional as F
import torch.nn as nn
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]的输入数据送入网络,观察每一层特征图的形状变化。代码实现如下:
# 这里用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)
print(model)
# 通过调用LeNet从基类继承的sublayers()函数,查看LeNet中所包含的子层
print(model.named_parameters())
x = torch.tensor(inputs)
print(x)
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
循环,所以运算速度比较慢。pytorch中,针对卷积层算子和汇聚层算子进行了速度上的优化,这里基于torch.nn.Conv2d();torch.nn.MaxPool2d();torch.nn.avg_pool2d()构建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)进行计算,可以得到:
所以,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)进行计算,可以得到:
所以,LeNet-5总的计算量为423344。
在飞桨中,还可以使用paddle.flopsAPI自动统计计算量。pytorch可以么?
可以,在torch中可使用torchstatAPI统计计算量。
from torchstat import stat
使用交叉熵损失函数,并用随机梯度下降法作为优化器来训练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/282, loss: 2.29467
[Train] epoch: 0/6, step: 15/282, loss: 2.28796
[Evaluate] dev score: 0.11000, dev loss: 2.29656
[Evaluate] best accuracy performence has been updated: 0.00000 --> 0.11000
[Train] epoch: 0/6, step: 30/282, loss: 2.23975
[Evaluate] dev score: 0.28000, dev loss: 2.24914
[Evaluate] best accuracy performence has been updated: 0.11000 --> 0.28000
[Train] epoch: 0/6, step: 45/282, loss: 2.14549
[Evaluate] dev score: 0.14000, dev loss: 2.21046
[Train] epoch: 1/6, step: 60/282, loss: 1.53033
[Evaluate] dev score: 0.28000, dev loss: 2.03015
[Train] epoch: 1/6, step: 75/282, loss: 1.76938
[Evaluate] dev score: 0.43500, dev loss: 1.50521
[Evaluate] best accuracy performence has been updated: 0.28000 --> 0.43500
[Train] epoch: 1/6, step: 90/282, loss: 0.74312
[Evaluate] dev score: 0.72000, dev loss: 0.88398
[Evaluate] best accuracy performence has been updated: 0.43500 --> 0.72000
[Train] epoch: 2/6, step: 105/282, loss: 0.54866
[Evaluate] dev score: 0.82500, dev loss: 0.46658
[Evaluate] best accuracy performence has been updated: 0.72000 --> 0.82500
[Train] epoch: 2/6, step: 120/282, loss: 0.32134
[Evaluate] dev score: 0.79500, dev loss: 0.54553
[Train] epoch: 2/6, step: 135/282, loss: 0.38424
[Evaluate] dev score: 0.90000, dev loss: 0.28482
[Evaluate] best accuracy performence has been updated: 0.82500 --> 0.90000
[Train] epoch: 3/6, step: 150/282, loss: 0.08964
[Evaluate] dev score: 0.89000, dev loss: 0.29195
[Train] epoch: 3/6, step: 165/282, loss: 0.42120
[Evaluate] dev score: 0.84000, dev loss: 0.43841
[Train] epoch: 3/6, step: 180/282, loss: 0.46647
[Evaluate] dev score: 0.87500, dev loss: 0.32823
[Train] epoch: 4/6, step: 195/282, loss: 0.28612
[Evaluate] dev score: 0.88000, dev loss: 0.33385
[Train] epoch: 4/6, step: 210/282, loss: 0.15028
[Evaluate] dev score: 0.95000, dev loss: 0.17772
[Evaluate] best accuracy performence has been updated: 0.90000 --> 0.95000
[Train] epoch: 4/6, step: 225/282, loss: 0.11253
[Evaluate] dev score: 0.95000, dev loss: 0.13939
[Train] epoch: 5/6, step: 240/282, loss: 0.08045
[Evaluate] dev score: 0.93000, dev loss: 0.24721
[Train] epoch: 5/6, step: 255/282, loss: 0.13160
[Evaluate] dev score: 0.90000, dev loss: 0.28647
[Train] epoch: 5/6, step: 270/282, loss: 0.22351
[Evaluate] dev score: 0.95500, dev loss: 0.13278
[Evaluate] best accuracy performence has been updated: 0.95000 --> 0.95500
[Evaluate] dev score: 0.94500, dev loss: 0.13454
[Train] Training done!
可视化观察训练集与验证集的损失变化情况。
# 可视化误差
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(iter(test_loader))
logits = runner.predict(X)
# 多分类,使用softmax计算预测概率
pred = F.softmax(logits, dim=1)
print(pred.shape)
# 获取概率最大的类别
pred_class = torch.argmax(pred[1]).numpy()
print(pred_class)
label = label[1].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')
运行结果:
import torch
import torch.nn as nn
from matplotlib import pyplot as plt
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision import datasets
batch_size = 64
lr = 0.01
momentum = 0.5
epoch = 5
# 归一化
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
# train=True训练集,=False测试集
train_dataset = datasets.MNIST(root='./pythonProject/mnist', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./pythonProject/mnist', train=False, transform=transform, download=True)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
fig = plt.figure()
for i in range(12):
plt.subplot(3, 4, i + 1)
plt.tight_layout()
plt.imshow(train_dataset.train_data[i], cmap='gray', interpolation='none')
plt.title("Labels: {}".format(train_dataset.train_labels[i]))
plt.xticks([])
plt.yticks([])
plt.show()
# 定义前馈神经网络
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
model = Model_MLP_L2_V3()
# 设置损失函数和优化器
criterion = torch.nn.CrossEntropyLoss() # 交叉熵损失
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=momentum)
def train(epoch):
running_loss = 0.0 # 这整个epoch的loss清零
running_total = 0
running_correct = 0
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data
optimizer.zero_grad()
# forward + backward + update
outputs = model(inputs)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
# 把运行中的loss累加起来,为了下面300次一除
running_loss += loss.item()
# 把运行中的准确率acc算出来
_, predicted = torch.max(outputs.data, dim=1)
running_total += inputs.shape[0]
running_correct += (predicted == target).sum().item()
if batch_idx % 100 == 99:
print('[%d, %5d]: loss: %.3f , acc: %.2f %%' % (
epoch + 1, batch_idx + 1, running_loss / 300, 100 * running_correct / running_total))
running_loss = 0.0 # 该批次loss清零
running_total = 0
running_correct = 0 # 该批次acc清零
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个维度,沿着行(第1个维度)去找1.最大值和2.最大值的下标
total += labels.size(0) # 张量之间的比较运算
correct += (predicted == labels).sum().item()
accuracy = correct / total # 测试准确率=正确数/总数
print('[%d]: Accuracy on test set: %.1f %% ' % (epoch + 1, 100 * accuracy))
return accuracy
# 主函数
if __name__ == '__main__':
acc_list_test = []
for epoch in range(epoch):
train(epoch)
acc_test = test()
acc_list_test.append(acc_test)
plt.plot(acc_list_test)
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()
运行结果:
[1, 100]: loss: 0.574 , acc: 48.86 %
[1, 200]: loss: 0.163 , acc: 85.44 %
[1, 300]: loss: 0.118 , acc: 89.09 %
[1, 400]: loss: 0.094 , acc: 91.56 %
[1, 500]: loss: 0.085 , acc: 92.44 %
[1, 600]: loss: 0.067 , acc: 94.09 %
[1, 700]: loss: 0.061 , acc: 94.58 %
[1, 800]: loss: 0.056 , acc: 94.69 %
[1, 900]: loss: 0.048 , acc: 95.50 %
[1]: Accuracy on test set: 96.7 %
[2, 100]: loss: 0.047 , acc: 95.64 %
[2, 200]: loss: 0.039 , acc: 96.39 %
[2, 300]: loss: 0.039 , acc: 96.44 %
[2, 400]: loss: 0.041 , acc: 96.38 %
[2, 500]: loss: 0.037 , acc: 96.97 %
[2, 600]: loss: 0.035 , acc: 96.75 %
[2, 700]: loss: 0.034 , acc: 96.88 %
[2, 800]: loss: 0.032 , acc: 97.08 %
[2, 900]: loss: 0.029 , acc: 97.38 %
[2]: Accuracy on test set: 97.6 %
[3, 100]: loss: 0.028 , acc: 97.45 %
[3, 200]: loss: 0.028 , acc: 97.50 %
[3, 300]: loss: 0.026 , acc: 97.77 %
[3, 400]: loss: 0.025 , acc: 97.75 %
[3, 500]: loss: 0.028 , acc: 97.53 %
[3, 600]: loss: 0.029 , acc: 97.33 %
[3, 700]: loss: 0.028 , acc: 97.16 %
[3, 800]: loss: 0.026 , acc: 97.59 %
[3, 900]: loss: 0.022 , acc: 97.88 %
[3]: Accuracy on test set: 98.0 %
[4, 100]: loss: 0.021 , acc: 97.80 %
[4, 200]: loss: 0.024 , acc: 97.66 %
[4, 300]: loss: 0.026 , acc: 97.61 %
[4, 400]: loss: 0.021 , acc: 98.20 %
[4, 500]: loss: 0.022 , acc: 98.06 %
[4, 600]: loss: 0.022 , acc: 97.97 %
[4, 700]: loss: 0.023 , acc: 97.86 %
[4, 800]: loss: 0.021 , acc: 97.86 %
[4, 900]: loss: 0.020 , acc: 98.19 %
[4]: Accuracy on test set: 98.4 %
[5, 100]: loss: 0.019 , acc: 98.38 %
[5, 200]: loss: 0.021 , acc: 98.30 %
[5, 300]: loss: 0.020 , acc: 98.17 %
[5, 400]: loss: 0.018 , acc: 98.30 %
[5, 500]: loss: 0.018 , acc: 98.27 %
[5, 600]: loss: 0.018 , acc: 98.42 %
[5, 700]: loss: 0.019 , acc: 98.33 %
[5, 800]: loss: 0.018 , acc: 98.27 %
[5, 900]: loss: 0.018 , acc: 98.27 %
[5]: Accuracy on test set: 98.5 %
由输出结果可知,前馈神经网络所需求的参数量要比LeNet大得多,且前馈神经网络在训练之初就能获得很高的准确率,LeNet在刚开始的时候的准确率却比较低;但与LeNet相比前馈神经网络的不足之处在于:前馈神经网络虽然在训练之初就能获得较高的准确率,但在后续的训练过程中,准确率却很难再有显著提升,且训练时间要比LeNet长。
from keras.models import Sequential
from keras.layers import Dense,Flatten
from keras.layers.convolutional import Conv2D,MaxPooling2D
from keras.utils.np_utils import to_categorical
from keras.datasets import mnist
from keras import backend as K
from keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape((-1,28,28,1))
y_train = to_categorical(y_train,10)
x_test = x_test.reshape((-1,28,28,1))
y_test = to_categorical(y_test,10)
model = Sequential()
model.add(Conv2D(6,(5,5),strides=(1,1),input_shape=(28,28,1),padding='valid',activation='relu',kernel_initializer='uniform'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(16,(5,5),strides=(1,1),padding='valid',activation='relu',kernel_initializer='uniform'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(120,activation='relu'))
model.add(Dense(84,activation='relu'))
model.add(Dense(10,activation='softmax'))
model.compile(optimizer='sgd',loss='categorical_crossentropy',metrics=['accuracy'])
model.summary()
model.fit(x_train,y_train,batch_size=100,epochs=50,shuffle=True)
model.save('D:/LeNet/LeNet-5_model.h5')
loss, accuracy=model.evaluate(x_test, y_test,batch_size=100)
print(loss, accuracy)
#----------------------------------各个层特征可视化-------------------------------
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#加载前面保存的模型
model=load_model('D:/LeNet/LeNet-5_model.h5')
#查看输入图片
fig1,ax1 = plt.subplots(figsize=(4,4))
ax1.imshow(np.reshape(x_test[12], (28, 28)))
plt.show()
image_arr=np.reshape(x_test[12], (-1,28, 28,1))
#可视化第一个MaxPooling2D
layer_1 = K.function([model.layers[0].input], [model.layers[1].output])
# 只修改inpu_image
f1 = layer_1([image_arr])[0]
# 第一层卷积后的特征图展示,输出是(1,12,12,6),(样本个数,特征图尺寸长,特征图尺寸宽,特征图个数)
re = np.transpose(f1, (0,3,1,2))
for i in range(6):
plt.subplot(2,4,i+1)
plt.imshow(re[0][i]) #,cmap='gray'
plt.show()
#可视化第二个MaxPooling2D
layer_2 = K.function([model.layers[0].input], [model.layers[3].output])
f2 = layer_2([image_arr])[0]
# 第一层卷积后的特征图展示,输出是(1,4,4,16),(样本个数,特征图尺寸长,特征图尺寸宽,特征图个数)
re = np.transpose(f2, (0,3,1,2))
for i in range(16):
plt.subplot(4,4,i+1)
plt.imshow(re[0][i]) #, cmap='gray'
plt.show()
#----------------------------------可视化滤波器-------------------------------
model=load_model('D:/LeNet/LeNet-5_model.h5')
#将张量转换成有效图像
def deprocess_image(x):
# 对张量进行规范化
x -= x.mean()
x /= (x.std() + 1e-5)
x *= 0.1
x += 0.5
x = np.clip(x, 0, 1)
# 转化到RGB数组
x *= 255
x = np.clip(x, 0, 255).astype('uint8')
return x
for i_kernal in range(10):
input_img=model.input
## 构建一个损耗函数,使所考虑的层的第n个滤波器的激活最大化,-1层softmax层
loss = K.mean(model.layers[-1].output[:,i_kernal])
# loss = K.mean(model.output[:, :,:, i_kernal])
# 计算输入图像的梯度与这个损失
grads = K.gradients(loss, input_img)[0]
# 效用函数通过其L2范数标准化张量
grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)
# 此函数返回给定输入图像的损耗和梯度
iterate = K.function([input_img, K.learning_phase()], [loss, grads])
# 从带有一些随机噪声的灰色图像开始
np.random.seed(0)
#图像通道
num_channels=1
#输入图像尺寸
img_height=img_width=28
#归一化图像
input_img_data = (255- np.random.randint(0,255,(1, img_height, img_width, num_channels))) / 255.
failed = False
# run gradient ascent
print('####################################',i_kernal+1)
loss_value_pre=0
# 运行梯度上升500步
for i in range(500):
loss_value, grads_value = iterate([input_img_data,1])
if i%10 == 0:
# print(' predictions: ' , np.shape(predictions), np.argmax(predictions))
print('Iteration %d/%d, loss: %f' % (i, 500, loss_value))
print('Mean grad: %f' % np.mean(grads_value))
if all(np.abs(grads_val) < 0.000001 for grads_val in grads_value.flatten()):
failed = True
print('Failed')
break
# print('Image:\n%s' % str(input_img_data[0,0,:,:]))
if loss_value_pre != 0 and loss_value_pre > loss_value:
break
if loss_value_pre == 0:
loss_value_pre = loss_value
# if loss_value > 0.99:
# break
input_img_data += grads_value * 1 #e-3
plt.subplot(2,5, i_kernal+1)
# plt.imshow((process(input_img_data[0,:,:,0])*255).astype('uint8'), cmap='Greys') #cmap='Greys'
img_re = deprocess_image(input_img_data[0])
img_re = np.reshape(img_re, (28,28))
plt.imshow(img_re) #cmap='Greys'
plt.show()
运行结果:
基于pytorch平台实现对MNIST数据集的分类分析(前馈神经网络、softmax)基础版
基于keras的LeNet-5模型可视化、网络特征可视化及kernel可视化_lwy_520的博客-CSDN博客