d2l笔记: 6 卷积神经网络
从全连接层到卷积
多层感知机适合处理表格数据,在问题中,我们预先不知道有什么关联信息。但是在视觉领域,有一些特点可以辅助我们对信息进行判断,而且多层感知机在面对海量的信息时维度过大,会导致训练上非常难以进行。
视觉对象具有局部性和平移不变性,也就是说,神经网络的前面几层应该只探索图像的局部区域,而且不管这个对象出现在图像中的哪个位置,都会使这几层有相似的反应。
根据这两个原则,我们将多层感知机“优化”为卷积神经网络。
图像卷积
卷积运算类似于向量的内积运算,结果是一个数字,可以表示相关性。
在二维互相关运算(卷积运算的简化版)中,卷积窗口从输入张量左上角开始,从左到右、从上到下滑动。 当卷积窗口滑动到新一个位置时,包含在该窗口中的部分张量与卷积核张量进行按元素相乘,得到的张量再求和得到一个单一的标量值,由此我们得出了这一位置的输出张量值。
LeNet
网络结构与PyTorch实现
LeNet-5 由卷积编码器(两个卷积层)和全连接层密集块(三个全连接层)组成。
由于当时ReLU和最大汇聚层还没有出现,所以LeNet在卷积块中使用的还是sigmoid激活函数和平均汇聚层。
网络的结构如下(去掉了最后一层的高斯激活):
net = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5, padding=2),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(6, 16, kernel_size=5),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.Linear(16 * 5 * 5, 120),
nn.Sigmoid(),
nn.Linear(120, 84),
nn.Sigmoid(),
nn.Linear(84, 10))
各层的输出的形状:
下面的四个参数分别为:batch_size大小,图像的通道数,图像的高度,图像的宽度
Conv2d output shape: torch.Size([1, 6, 28, 28])
Sigmoid output shape: torch.Size([1, 6, 28, 28])
AvgPool2d output shape: torch.Size([1, 6, 14, 14])
Conv2d output shape: torch.Size([1, 16, 10, 10])
Sigmoid output shape: torch.Size([1, 16, 10, 10])
AvgPool2d output shape: torch.Size([1, 16, 5, 5])
Flatten output shape: torch.Size([1, 400])
Linear output shape: torch.Size([1, 120])
Sigmoid output shape: torch.Size([1, 120])
Linear output shape: torch.Size([1, 84])
Sigmoid output shape: torch.Size([1, 84])
Linear output shape: torch.Size([1, 10])
模型训练和评估
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
在使用GPU计算数据集之前,需要将其从内存中复制到显存中,因此需要加上 X = X.to(device)
和 y = y.to(device)
。
def evaluate_accuracy_gpu(net, data_iter, device=None):
if isinstance(net, nn.Module):
net.eval()
if not device:
device = next(iter(net.parameters())).device
metric = d2l.Accumulator(2)
with torch.no_grad():
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())
return metric[0] / metric[1]
训练函数也需要在正向和反向传播之前加上 X, y = X.to(device), y.to(device)
将一个 batch 的数据移动到 GPU 上。
同时,使用Xavier随机初始化模型参数。
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
# 用Xavier初始化模型参数
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
# 监控训练的设备
print('training on', device)
net.to(device)
# 随机梯度下降 交叉熵损失
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()
X, y = X.to(device), y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
optimizer.step()
with torch.no_grad():
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
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)}')
最后调用函数进行训练和评估。
lr, num_epochs = 0.9, 10
train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())