5.3 基于LeNet实现手写体数字识别实验
在本节中,我们实现经典卷积网络LeNet-5,并进行手写体数字识别任务。
5.3.1 数据
手写体数字识别是计算机视觉中最常用的图像分类任务,让计算机识别出给定图片中的手写体数字(0-9共10个数字)。由于手写体风格差异很大,因此手写体数字识别是具有一定难度的任务。
我们采用常用的手写数字识别数据集:MNIST数据集。MNIST数据集是计算机视觉领域的经典入门数据集,包含了60,000个训练样本和10,000个测试样本。这些数字已经过尺寸标准化并位于图像中心,图像是固定大小(
28
×
28
28\times28
28×28像素)。图5.12给出了部分样本的示例。
图5.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 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])))
可视化观察其中的一张样本以及对应的标签,代码如下所示:
image, label = train_set[0][0], train_set[1][0]
image, label = np.array(image).astype('float32'), int(label)
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
32\times 32
32×32 ,而MNIST数据集中的原始图片大小却是
28
×
28
28\times 28
28×28 ,这里为了符合网络的结构设计,将其调整为
32
×
32
32 \times 32
32×32;
- 规范化: 通过规范化手段,把输入图像的分布改变成均值为0,标准差为1的标准正态分布,使得最优解的寻优过程明显会变得平缓,训练过程更容易收敛。
在飞桨中,提供了部分视觉领域的高层API,可以直接调用API实现简单的图像处理操作。通过调用torchvision.transforms.Resize 调整大小;调用torchvision.transforms.Normalize 进行标准化处理;使用torchvision.transforms.Compose 将两个预处理操作进行拼接。
代码实现如下:
transforms = Compose([Resize(32), Normalize(mean=[127.5], std=[127.5])])
将原始的数据集封装为Dataset类,以便DataLoader调用。
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)
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虽然提出的时间比较早,但它是一个非常成功的神经网络模型。基于LeNet-5的手写数字识别系统在20世纪90年代被美国很多银行使用,用来识别支票上面的手写数字。LeNet-5的网络结构如图5.13所示。
图5.13:LeNet-5网络结构
我们使用上面定义的卷积层算子和汇聚层算子构建一个LeNet-5模型。
这里的LeNet-5和原始版本有4点不同:
- C3层没有使用连接表来减少卷积数量。
- 汇聚层使用了简单的平均汇聚,没有引入权重和偏置参数以及非线性激活函数。
- 卷积层的激活函数使用ReLU函数。
- 最后的输出层为一个全连接线性层。
网络共有7层,包含3个卷积层、2个汇聚层以及2个全连接层的简单卷积神经网络接,受输入图像大小为
32
×
32
=
1
?
024
32\times 32=1\, 024
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__()
self.conv1 = torch.conv2d(in_channels=in_channels, out_channels=6, kernel_size=5, weight_attr=paddle.ParamAttr())
self.pool2 = torch.max_pool2d(size=(2,2), mode='max', stride=2)
self.conv3 = torch.conv2d(in_channels=6, out_channels=16, kernel_size=5, stride=1, weight_attr=paddle.ParamAttr())
self.pool4 = torch.max_pool2d(size=(2,2), mode='avg', stride=2)
self.conv5 = torch.conv2d(in_channels=16, out_channels=120, kernel_size=5, stride=1, weight_attr=paddle.ParamAttr())
self.linear6 = nn.Linear(120, 84)
self.linear7 = nn.Linear(84, num_classes)
def forward(self, x):
output = F.relu(self.conv1(x))
output = self.pool2(output)
output = F.relu(self.conv3(output))
output = self.pool4(output)
output = F.relu(self.conv5(output))
output = torch.squeeze(output, axis=[2,3])
output = F.relu(self.linear6(output))
output = self.linear7(output)
return output
下面测试一下上面的LeNet-5模型,构造一个形状为 [1,1,32,32]的输入数据送入网络,观察每一层特征图的形状变化。代码实现如下:
inputs = np.random.randn(*[1,3,32,32])
inputs = inputs.astype('float32')
model = Model_LeNet(in_channels=3, num_classes=10)
print(model.sublayers())
x = paddle.to_tensor(inputs)
for item in model.sublayers():
try:
x = item(x)
except:
x = paddle.reshape(x, [x.shape[0], -1])
x = item(x)
if len(item.parameters())==2:
print(item.full_name(), x.shape, item.parameters()[0].shape,
item.parameters()[1].shape)
else:
print(item.full_name(), x.shape)
从输出结果看,
- 对于大小为
32
×
32
32 \times32
32×32的单通道图像,先用6个大小为
5
×
5
5 \times5
5×5的卷积核对其进行卷积运算,输出为6个
28
×
28
28 \times28
28×28大小的特征图;
- 6个
28
×
28
28 \times28
28×28大小的特征图经过大小为
2
×
2
2 \times2
2×2,步长为2的汇聚层后,输出特征图的大小变为
14
×
14
14 \times14
14×14;
- 6个
14
×
14
14 \times14
14×14大小的特征图再经过16个大小为
5
×
5
5 \times5
5×5的卷积核对其进行卷积运算,得到16个
10
×
10
10 \times10
10×10大小的输出特征图;
- 16个
10
×
10
10 \times10
10×10大小的特征图经过大小为
2
×
2
2 \times2
2×2,步长为2的汇聚层后,输出特征图的大小变为
5
×
5
5 \times5
5×5;
- 16个
5
×
5
5 \times5
5×5大小的特征图再经过120个大小为
5
×
5
5 \times5
5×5的卷积核对其进行卷积运算,得到120个
1
×
1
1 \times1
1×1大小的输出特征图;
- 此时,将特征图展平成1维,则有120个像素点,经过输入神经元个数为120,输出神经元个数为84的全连接层后,输出的长度变为84。
- 再经过一个全连接层的计算,最终得到了长度为类别数的输出结果。
考虑到自定义的Conv2D 和Pool2D 算子中包含多个for 循环,所以运算速度比较慢。飞桨框架中,针对卷积层算子和汇聚层算子进行了速度上的优化,这里基于paddle.nn.Conv2D 、paddle.nn.MaxPool2D 和paddle.nn.AvgPool2D 构建LeNet-5模型,对比与上边实现的模型的运算速度。代码实现如下:
class Paddle_LeNet(nn.Module):
def __init__(self, in_channels, num_classes=10):
super(Paddle_LeNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=6, kernel_size=5)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)
self.pool4 = nn.AvgPool2d(kernel_size=2, stride=2)
self.conv5 = nn.Conv2d(in_channels=16, out_channels=120, kernel_size=5)
self.linear6 = nn.Linear(in_features=120, out_features=84)
self.linear7 = nn.Linear(in_features=84, out_features=num_classes)
def forward(self, x):
output = F.relu(self.conv1(x))
output = self.pool2(output)
output = F.relu(self.conv3(output))
output = self.pool4(output)
output = F.relu(self.conv5(output))
output = torch.squeeze(output)
output = F.relu(self.linear6(output))
output = self.linear7(output)
return output
测试两个网络的运算速度。
import time
inputs = np.random.randn(*[1,1,32,32])
inputs = inputs.astype('float32')
x = torch.as_tensor(inputs)
model = Model_LeNet(in_channels=1, num_classes=10)
paddle_model = Paddle_LeNet(in_channels=1, num_classes=10)
model_time = 0
for i in range(60):
strat_time = time.time()
out = model(x)
end_time = time.time()
if i < 10:
continue
model_time += (end_time - strat_time)
avg_model_time = model_time / 50
print('Model_LeNet speed:', avg_model_time, 's')
paddle_model_time = 0
for i in range(60):
strat_time = time.time()
paddle_out = paddle_model(x)
end_time = time.time()
if i < 10:
continue
paddle_model_time += (end_time - strat_time)
avg_paddle_model_time = paddle_model_time / 50
print('Paddle_LeNet speed:', avg_paddle_model_time, 's')
这里还可以令两个网络加载同样的权重,测试一下两个网络的输出结果是否一致。
inputs = np.random.randn(*[1,1,32,32])
inputs = inputs.astype('float32')
x = torch.as_tensor(inputs)
model = Model_LeNet(in_channels=1, num_classes=10)
params = model.state_dict()
for key in params:
if 'bias' in key:
params[key] = params[key].squeeze()
paddle_model = Paddle_LeNet(in_channels=1, num_classes=10)
paddle_model.set_state_dict(params)
paddle.set_printoptions(6)
output = model(x)
print('Model_LeNet output: ', output)
paddle_output = paddle_model(x)
print('Paddle_LeNet output: ', paddle_output)
小疑问:为什么权重和AIStudio差异这么大?(我也不知道)
可以看到,输出结果是一致的。 这里还可以统计一下LeNet-5模型的参数量和计算量。
参数量
按照公式(5.18)进行计算,可以得到:
- 第一个卷积层的参数量为:
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 API自动计算参数量。
print(x.shape)
print(summary(model,input_size=x.shape[1:]))
print(model.state_dict().keys())
可以看到,结果与公式推导不一致。如果有大佬知道,麻烦解答一下
5.3.3 模型训练
使用交叉熵损失函数,并用随机梯度下降法作为优化器来训练LeNet-5网络。 用RunnerV3在训练集上训练5个epoch,并保存准确率最高的模型作为最佳模型。
import torch
from torch import nn as nn
import torch.nn.functional as F
import numpy as np
from PIL import Image
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
class RunnerV3(object):
def __init__(self, model, optimizer, loss_fn, metric, **kwargs):
self.model = model
self.optimizer = optimizer
self.loss_fn = loss_fn
self.metric = metric
self.dev_scores = []
self.train_epoch_losses = []
self.train_step_losses = []
self.dev_losses = []
self.best_score = 0
def train(self, train_loader, dev_loader=None, **kwargs):
self.model.train()
num_epochs = kwargs.get("num_epochs", 0)
log_steps = kwargs.get("log_steps", 100)
eval_steps = kwargs.get("eval_steps", 0)
save_path = kwargs.get("save_path", "best_model.pdparams")
custom_print_log = kwargs.get("custom_print_log", None)
num_training_steps = num_epochs * len(train_loader)
if eval_steps:
if self.metric is None:
raise RuntimeError('Error: Metric can not be None!')
if dev_loader is None:
raise RuntimeError('Error: dev_loader can not be None!')
global_step = 0
for epoch in range(num_epochs):
total_loss = 0
for step, data in enumerate(train_loader):
X, y = data
logits = self.model(X)
y = torch.tensor(y, dtype=torch.int64)
loss = self.loss_fn(logits, y)
total_loss += loss
self.train_step_losses.append((global_step, loss.item()))
if log_steps and global_step % log_steps == 0:
print(
f"[Train] epoch: {epoch}/{num_epochs}, step: {global_step}/{num_training_steps}, loss: {loss.item():.5f}")
loss.backward()
if custom_print_log:
custom_print_log(self)
self.optimizer.step()
self.optimizer.zero_grad()
if eval_steps > 0 and global_step > 0 and \
(global_step % eval_steps == 0 or global_step == (num_training_steps - 1)):
dev_score, dev_loss = self.evaluate(dev_loader, global_step=global_step)
print(f"[Evaluate] dev score: {dev_score:.5f}, dev loss: {dev_loss:.5f}")
self.model.train()
if dev_score > self.best_score:
self.save_model(save_path)
print(
f"[Evaluate] best accuracy performence has been updated: {self.best_score:.5f} --> {dev_score:.5f}")
self.best_score = dev_score
global_step += 1
trn_loss = (total_loss / len(train_loader)).item()
self.train_epoch_losses.append(trn_loss)
print("[Train] Training done!")
@torch.no_grad()
def evaluate(self, dev_loader, **kwargs):
assert self.metric is not None
self.model.eval()
global_step = kwargs.get("global_step", -1)
total_loss = 0
self.metric.reset()
for batch_id, data in enumerate(dev_loader):
X, y = data
logits = self.model(X)
y = torch.tensor(y, dtype=torch.int64)
loss = self.loss_fn(logits, y).item()
total_loss += loss
self.metric.update(logits, y)
dev_loss = (total_loss / len(dev_loader))
dev_score = self.metric.accumulate()
if global_step != -1:
self.dev_losses.append((global_step, dev_loss))
self.dev_scores.append(dev_score)
return dev_score, dev_loss
@torch.no_grad()
def predict(self, x, **kwargs):
self.model.eval()
logits = self.model(x)
return logits
def save_model(self, save_path):
torch.save(self.model.state_dict(), save_path)
def load_model(self, model_path):
model_state_dict = torch.load(model_path)
self.model.set_state_dict(model_state_dict)
class torch_LeNet(nn.Module):
def __init__(self, in_channels, num_classes=10):
super(torch_LeNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=6, kernel_size=5)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)
self.pool4 = nn.AvgPool2d(kernel_size=2, stride=2)
self.conv5 = nn.Conv2d(in_channels=16, out_channels=120, kernel_size=5)
self.linear6 = nn.Linear(in_features=120, out_features=84)
self.linear7 = nn.Linear(in_features=84, out_features=num_classes)
def forward(self, x):
output = F.relu(self.conv1(x))
output = self.pool2(output)
output = F.relu(self.conv3(output))
output = self.pool4(output)
output = F.relu(self.conv5(output))
output = torch.squeeze(output)
output = F.relu(self.linear6(output))
output = self.linear7(output)
return output
lr = 0.1
batch_size = 64
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])
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]
from torchvision.transforms import Compose, Resize, Normalize,ToTensor
def accuracy(preds, labels):
if preds.shape[1] == 1:
preds = torch.as_tensor((preds >= 0.5),dtype=torch.float32)
else:
preds = torch.argmax(preds, dim=1).int()
return torch.mean(torch.as_tensor((preds == labels),dtype=torch.float32))
import torch
class Accuracy():
def __init__(self, is_logist=True):
"""
输入:
- is_logist: outputs是logist还是激活后的值
"""
self.num_correct = 0
self.num_count = 0
self.is_logist = is_logist
def update(self, outputs, labels):
"""
输入:
- outputs: 预测值, shape=[N,class_num]
- labels: 标签值, shape=[N,1]
"""
if outputs.shape[1] == 1:
outputs = torch.squeeze(outputs, dim=-1)
if self.is_logist:
preds = torch.tensor((outputs >= 0), dtype=torch.float32)
else:
preds = torch.tensor((outputs >= 0.5), dtype=torch.float32)
else:
preds = torch.argmax(outputs, dim=1)
preds = torch.tensor(preds, dtype=torch.int64)
labels = torch.squeeze(labels, dim=-1)
batch_correct = torch.sum(torch.tensor(preds == labels, dtype=torch.float32)).numpy()
batch_count = len(labels)
self.num_correct += batch_correct
self.num_count += batch_count
def accumulate(self):
if self.num_count == 0:
return 0
return self.num_correct / self.num_count
def reset(self):
self.num_correct = 0
self.num_count = 0
def name(self):
return "Accuracy"
transforms = Compose([Resize(32),ToTensor(), Normalize(mean=[127.5], std=[127.5])])
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')
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
dev_loader = torch.utils.data.DataLoader(dev_dataset, batch_size=batch_size)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size)
model = torch_LeNet(in_channels=1, num_classes=10)
optimizer = torch.optim.SGD(lr=lr, params=model.parameters())
loss_fn = F.cross_entropy
metric = Accuracy(is_logist=True)
runner = RunnerV3(model=model, optimizer=optimizer,loss_fn = loss_fn, metric=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.31964
[Train] epoch: 0/5, step: 15/80, loss: 1.96424
[Evaluate] dev score: 0.31000, dev loss: 1.94272
[Evaluate] best accuracy performence has been updated: 0.00000 --> 0.31000
[Train] epoch: 1/5, step: 30/80, loss: 1.90126
[Evaluate] dev score: 0.58500, dev loss: 1.58386
[Evaluate] best accuracy performence has been updated: 0.31000 --> 0.58500
[Train] epoch: 2/5, step: 45/80, loss: 0.92311
[Evaluate] dev score: 0.63000, dev loss: 1.17126
[Evaluate] best accuracy performence has been updated: 0.58500 --> 0.63000
[Train] epoch: 3/5, step: 60/80, loss: 0.31175
[Evaluate] dev score: 0.80000, dev loss: 0.40704
[Evaluate] best accuracy performence has been updated: 0.63000 --> 0.80000
[Train] epoch: 4/5, step: 75/80, loss: 0.36434
[Evaluate] dev score: 0.83000, dev loss: 0.44397
[Evaluate] best accuracy performence has been updated: 0.80000 --> 0.83000
[Evaluate] dev score: 0.85000, dev loss: 0.50347
[Evaluate] best accuracy performence has been updated: 0.83000 --> 0.85000
[Train] Training done!
'''
可视化观察训练集与验证集的损失变化情况。
from nndl import plot_training_loss_acc
plot_training_loss_acc(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))
'''
[Test] accuracy/loss: 0.8250/0.5201
'''
5.3.5 模型预测
同样地,我们也可以使用保存好的模型,对测试集中的某一个数据进行模型预测,观察模型效果。
X, label = next(test_loader())
logits = runner.predict(X)
pred = F.softmax(logits)
pred_class = paddle.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')
'''
The true category is 2 and the predicted category is 2
'''
使用前馈神经网络实现MNIST识别,与LeNet效果对比。(选做)
网络模型
如下图所示:一层输入一层线性层,一层含有十个神经元的输出层。使用relu激活函数
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torchvision.datasets as dsets
import torchvision.transforms as transforms
batch_size = 100
train_dataset = dsets.MNIST(root='/kaggle/working/data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = dsets.MNIST(root='/kaggle/working/data', train=False, transform=transforms.ToTensor(), download=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)
input_size = 784
hidden_size = 500
num_classes = 10
class Neural_net(nn.Module):
def __init__(self, input_num, hidden_size, output_num):
super(Neural_net, self).__init__()
self.layers1 = nn.Linear(input_num, hidden_size)
self.layers2 = nn.Linear(hidden_size, output_num)
def forward(self, x):
out = self.layers1(x)
out = torch.relu(out)
out = self.layers2(out)
return out
net = Neural_net(input_size, hidden_size, num_classes)
print(net)
learning_rate = 1e-1
num_epoches = 5
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate)
for epoch in range(num_epoches):
print("current epoch = {}".format(epoch))
for i, (images,labels) in enumerate(train_loader):
images = Variable(images.view(-1, 28*28))
labels = Variable(labels)
outputs = net(images)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if i%100 == 0:
print("current loss = %.5f" %loss.item())
total = 0
correct = 0
for images, labels in test_loader:
images = Variable(images.view(-1, 28*28))
labels = Variable(labels)
outputs = net(images)
_,predicts = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicts == labels).sum()
from sklearn.metrics import confusion_matrix
C2 = confusion_matrix(predicts, labels, labels=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
import sklearn
acc = sklearn.metrics.accuracy_score(labels, predicts)
print("Accuracy = %.2f" %(100*correct/total))
优化网络模型,需按照最优参数
一层线性层,500个神经元
增加一层含有200个神经元的线性层
运行时间:
将第二层隐层200个神经元变成500个神经元
通过实验结果,我们发现前馈神经网络模型使用一层隐藏层,500个神经元就已经达到了一个很好的准确率,后期我们无论怎么增加神经元或者层数,准确率都不会大幅度提升了。而且训练时间大幅度提升,占用了大量的时间。与LeNet相比,我觉得各有千秋,因为在训练的时候,LeNet网络比较复杂,还有六万多个参数,而前馈神经网络只有小一万个参数,所以LeNet网络训练起来比前馈神经网络训练起来更复杂一些,时间更长,但是在准确率方面,LeNet-5网络仅仅用了1400张图片达到了一个高达80的准确率,而前馈神经网络用了六万张图才达到了96的准确率。
所以最优网络模型为:784输入,一层隐藏层含有500个神经元,一层输出神经层,含有10个神经元。
可视化LeNet中的部分特征图和卷积核,谈谈自己的看法。(选做)
卷积核
特征图
第一层卷积后的部分图像 经历了一层最大池化层后:
感悟:
首先: 假设: 输入图片大小
W
×
W
W×W
W×W Filter大小
F
×
F
F×F
F×F 步长
S
S
S padding的像素数
P
P
P 输出图片大小为
N
×
N
N×N
N×N 那么:
N
=
f
l
o
o
r
[
(
W
?
F
+
2
P
)
/
S
+
1
]
N = floor[(W ? F + 2P )/S+1]
N=floor[(W?F+2P)/S+1] 通过数据我们可以发现,前后图像的大小符合图像大小前后变换计算公式。
28
?
28
=
[
(
32
?
5
)
+
1
]
[
(
32
?
5
)
+
1
]
28*28 = [(32-5)+1][(32-5)+1]
28?28=[(32?5)+1][(32?5)+1],通过图像,发现特征图,卷积核变得越来越扑朔迷离,越来越不符合人的主观感觉,而这正是计算机所要抓取的特征。毕竟人和计算机的思维是不同的,机器经历了复杂的变化训练出这么多参数来使其预测的准确率达到一个峰值。
总结:
使用之前写好的的训练模型,测试函数,但是这次将paddlepaddle框架变为torch框架的时候,有一个疑问就是使用pytorch框架计算出来的参数和使用paddlepaddle计算出来的参数不一样,如果是网络模型由于疏忽导致差异比较大,但是通过对比训练时间,我发现二者差异时间并不是很大,得出网络模型无差异的结论,不过Yang LeKun LeNet网络已经很好了,这次实验使用的LeNet-5在LeNet基础上进行改变,仅仅用1400条数据就使得准确率高达了百分之80,可见开发一个有用的网络牛逼。
遇到的错误:
TypeError: img should be PIL Image. Got <class 'torch.Tensor'>
修改方法: 使用transforms.ToTensor()将其转换为tensor类型。
参考
NNDL 实验六 卷积神经网络(3)LeNet实现MNIST LeNet-5结构详解 前馈神经网络实现手写数据集 神经网络卷积核和特征图大小的计算 浅尝CNN之LeNet的原理简述及Python实现 所以我给自己放了两天假
|