1.输入为32*32的图片,放到一个5*5的卷积层中然后该卷积层的输出通道是6,高宽为28*28.该层输出可以被认为是feature map(特征图)
2.接下来是个2*2的pooling层,高宽被压缩到14*14,但输出通道依旧是6.
3.然后接下来的卷积层,卷积层的核依旧是5*5的,使得特征图变成了10*10的。这里输出通道数是16.
4.再接一个pooling层,输出通道数不变,特征图大小变为5*5.
5.再把数据拉成一个向量,输入到全连接层上,图上的Gauss现在已经不用了。可以认为后接二个全连接层得到10个输出,然后softmax得到一个概率。
总结:
LeNet是早期成功的神经网络,该模型通过卷积层来学习图片的空间信息,通过池化层来降低的图片的敏感度,然后通过全连接层来转换到类别空间,得到实类。可以被认为为两个卷积和池化,后接一个多层感知机得到一个从图片到类别的映射。
import torch
from torch import nn
from d2l import torch as d2l
class Reshape(torch.nn.Module):
def forward(self, x):
return x.view(-1, 1, 28, 28) # 把 x 变成 批量数不变,通道数为1,大小为28*28
net = torch.nn.Sequential(
Reshape(), nn,Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),
nn.AvgPool2d(2, stride=2),
nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2), nn.Flatten(), # 卷积后得到一个4D的数据,通过Flatten拉平
nn.Linear(16 * 5 * 5, 120), nn.Sigmoid(),
nn.Linear(120, 84), nn.Sigmoid(),
nn.Linear(84, 10)
)
# 检查模型------------------------------
X = torch.rand(Size=(1, 1, 28, 28), dtype=torch.float32)
for layer in net:
X = layer(X)
print(layer.__class__.__name__, 'output shape:\t', X.shape)
# --------------------------------------
核心思想:通过不断的卷积把空间信息不断压缩,压缩后的数据添加到通道里。通道是一直在增加的,feature map(特征图)的高宽是一直在减少的,最后的最后我们可以认为高宽变成1通道数大至上千,最后一般做全连接输出。
# LeNet 在 Fashion-MNIST 数据集上的表现
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
# ----------------------------------------
# 对 evaluate_accuracy函数进行轻微的修改,使得可在GPU上运行
def evaluate_accuracy_gpu(net, data_iter, device=None):
if isinstance(net, torch.nn.Module):
net.eval() # eval 关闭模型中的dropout功能,调整到验证状态,梯度清零,不调整权重
if not device:
device = next(iter(net.parameters())).device
metric = d2l.Accumulator(2)
for X, y in data_iter:
if isinstance(X, list):
X = [x.to(device) for x in X]
else:
X = X.to(device)
y = y.to(device)
metric.add(d2l.accuracy(net(X), y), y.numel()) # numel 为计算y的元素个数
return metric[0] / metric[1]
# 为了使用GPU,train部分也需要改动
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
"""Train a model with a GPU (defined in chapter 6)"""
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
# xavier这个函数根据输入输出的大小,使用随机数时保证输入和输出的方差是差不多的,保证模型一开始的稳定性
net.apply(init_weigths)
print('training on', device)
net.to(device) # 模型也得挪到GPU上
optimizer = torch.optim.SGD(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss()
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
legend=['train loss', 'train acc', 'test acc'])
timer, num_batches = d2l.Timer(), len(train_iter)
for epoch in range(num_epochs):
metric = d2l.Accumulator(3)
net.train()
for i, (X, y) in enumerate(train_iter):
timer.start()
optimizer.zero_grad() # 操作梯度设置为 0
X, y = X.to(device), y.to(device) # 输入输出挪到device上,可以是CPU,也可以是GPU
y_hat = net(X)
l = loss(y_hat, y) # 前向操作,计算损失
l.backward() # 计算梯度
optimizer.step() # 迭代参数
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y)) # 后面是过程动画化,打印过程
timer.stop()
train_l = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches,
(train_l, train_acc, None))
test_acc = evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
f'on {str(device)}')
# 训练和评估LeNet-5模型
lr, num_epochs = 0.9, 10
train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
ReNet为什么能训练出1000层的模型:
1.避免梯度消失,乘法变加法