动手学深度学习之经典卷积神经网络之LeNet

LeNet

  • LeNet的结构如下,它的输入是一个32 * 32的image,放到一个5 * 5的卷积层中,它的通道数是6,它的输出是一个28 * 28的一个矩阵,这里有个概念叫做feature map,也就第卷积层的输出的那一坨就是feature map。接下来使用一个2*2的pooling层,这样就从28 * 28转换为了14 * 14,通道数目不变。接下来又是一个5 * 5的卷积层,这输出从14 * 14转换为了10 * 10,通道数变为16。后面再接上一个pooling层,输出为一个5 * 5,通道数为16。然后将最后一个pooling层接到一个全连接层,全连接层的输入是最后一个pooling层得到的一坨拉成一个向量的长度为5 * 5 * 16, 他的输出的向量长度为120,再输入一个全连接层,这个全连接层的输出是64,最后接一个Gauss层(现在不用了,基本上可以认为是一个softmax层)。
    在这里插入图片描述

总结

在这里插入图片描述

LeNet的实现

LeNet(LeNet-5)由两个部分组成:卷积编码器和全连接层密集块

import torch
import torchvision
from d2l import torch as d2l
from torch import nn
from torch.utils import data
from torchvision import transforms

# 这个类的作用就是将我们的额输入X变为一个批量数不变,通道数变为1,大小变为28*28
class Reshape(nn.Module):
    def forward(self, x):
        return x.view(-1, 1, 28, 28)

LeNet = nn.Sequential(
    Reshape(), nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),  # 第一个卷积层,经过Reshape()后我们得到的输入数据是28*28的大小,这里我们对数据做一个填充使它变为32*32大小,这里我们的卷积核的大小为5*5
    nn.AvgPool2d(kernel_size=2, stride=2),  # 第一个池化层,经过上述的卷积层,我这一层的输入的形状是6*28*28,这里我们选择的池化窗口的大小是2*2,步幅是2,步幅和窗口大小相同,也就是不重复扫描,这一层的输出的形状为6*14*4
    nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),  # 第二个卷积层,经过上面的池化层,这里的输入的形状是6*14*14, 输出通道的大小为16,卷积核的大小是5*5,所以输出形状是16*10*10
    nn.AvgPool2d(kernel_size=2, stride=2), nn.Flatten(),  # 第二个池化层,上面的卷积层后,这里的输入是16*10*10,这里选择的池化窗口的大小是6,步幅为2,所以我们得到输出的形状是16*5*5,然后使用Flatten(),将它展平,也就是保持维度0不变,其他的维度拉直
    nn.Linear(16 * 5 * 5, 120), nn.Sigmoid(),  # 第一个全连接层,上面的操作我们得到了一个长度为16*5*5的向量,作为该层输入,这一层的输出是长度为120的向量,激活函数选用Sigmoid
    nn.Linear(120, 84), nn.Sigmoid(),  # 第二个全连接层,这一层的输入是上一层的输出,输出是一个长度为84的向量,激活函数选用Sigmoid
    nn.Linear(84, 10))  # 第三个全连接层,输入是上一层的输出,输出是长度为10的向量
# 检查模型
X = torch.rand(size=(1, 1, 28, 28), dtype=torch.float32)
for layer in LeNet:
    X = layer(X)
    print(layer.__class__.__name__, "output shape:\t", X.shape)
Reshape output shape:	 torch.Size([1, 1, 28, 28])
Conv2d output shape:	 torch.Size([1, 6, 28, 28])
ReLU 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])
ReLU 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])
ReLU output shape:	 torch.Size([1, 120])
Linear output shape:	 torch.Size([1, 84])
ReLU output shape:	 torch.Size([1, 84])
Linear output shape:	 torch.Size([1, 10])
# 测试LeNet在Fashion-MNIST数据集上的表现
batch_size = 256

trans = transforms.ToTensor()
train_mnist = torchvision.datasets.FashionMNIST(root="./fashion-mnist", train=True, transform=trans, download=True)
test_mnist = torchvision.datasets.FashionMNIST(root="./fashion-mnist", train=False, transform=trans, download=True)

train_iter = data.DataLoader(train_mnist, batch_size=batch_size)
test_iter = data.DataLoader(test_mnist, batch_size=batch_size)
/Users/tiger/opt/anaconda3/envs/d2l-zh/lib/python3.8/site-packages/torchvision/datasets/mnist.py:498: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to the underlying (supposedly non-writeable) NumPy array using the tensor. You may want to copy the array to protect its data or make it writeable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at  ../torch/csrc/utils/tensor_numpy.cpp:180.)
  return torch.from_numpy(parsed.astype(m[2], copy=False)).view(*s)
# evaluate_accuracy函数
def evaluate_accuracy(net, data_iter, device=None):
    """使用GPU计算模型在数据集上的精度"""
    if isinstance(net, torch.nn.Module):
        net.eval()  # eval的意识就是关闭模型中的dropout功能,调到评价模式;与之相对应的是train()
        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)
        y = y.to(device)
        metric.add(d2l.accuracy(net(X), y), y.numel())
    return metric[0] / metric[1 ]
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
    """用GPU训练模型(在第六章定义)。"""
    # 初始化weight
    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(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.1, 10
train_ch6(LeNet, train_iter, test_iter, num_epochs, lr, "cpu")
loss 0.348, train acc 0.872, test acc 0.859
6905.4 examples/sec on cpu
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值