LeNet Pytorch实现【初学者】

1. 内容来源

23 经典卷积神经网络 LeNet【动手学深度学习v2】_哔哩哔哩_bilibili23 经典卷积神经网络 LeNet【动手学深度学习v2】共计3条视频,包括:LeNet、代码、QA等,UP主更多精彩视频,请关注UP账号。https://www.bilibili.com/video/BV1t44y1r7ct/?spm_id_from=333.999.0.0&vd_source=f94822d3eca79b8e245bb58bbced6b77

2. Pytorch实现

2.1 模型构建

由于此篇文章(LeCun Y, Bottou L, Bengio Y, et al. Gradient-based learning applied to document recognition[J]. Proceedings of the IEEE, 1998, 86(11): 2278-2324.)是历史上第一个深度学习网络,原文中某些操作与现在常用的层有少许出入,沐神简化成以下模型:

1. 将数据集reshape成(batch_size, 1, 28, 28)

2. 经过卷积层(输出6通道,使用5*5卷积核,2填充)-- 激活层(Sigmoid)-- 平均池化层(使用2*2核,2步长)

3. 经过卷积层(输出16通道,使用5*5卷积核,无填充)-- 激活层(Sigmoid)-- 平均池化层(使用2*2核,2步长)

4. 展开成一维向量特征,经过线性层(输入维度16*5*5,输出维度120)-- 激活层(Sigmoid)

5. 经过线性层(输入维度120,输出维度84)-- 激活层(Sigmoid)

6. 输出层(输入维度84,输出维度10)

代码实现:

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)
    
net = torch.nn.Sequential(
    Reshape(), 
    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)
)

其中第一个线性层的16*5*5可以手推,也可以使用以下方式打印每一层的输出维度

代码实现:

# Dimension Check
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)

输出:

Reshape output shape:    	 torch.Size([1, 1, 28, 28])
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])

2.2 模型训练

由于从LeNet开始网络训练计算量开始指数型暴涨,需要借助GPU进行加速,所以重写train函数

代码实现:

def train_gpu(net, train_iter, test_iter, num_epochs, lr, device):
    # Parameter Initialization
    def init_weight(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weight)
    # Device Choosing
    print('training on', device)
    net.to(device)
    # Trainging
    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)
            yhat = net(X)
            l = loss(yhat, y)
            l.backward()
            optimizer.step()
            metric.add(l * X.shape[0], d2l.accuracy(yhat, 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 + (1 + i) / 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}, test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec', 
          f'on {str(device)}')

其中,涉及matric、animator代码是沐神用来动态展示训练过程的可以省略,与在CPU上训练不同的在于所有涉及计算的数据均需要使用.to(device)搬运到GPU上,与模型所在位置保持一致。device可以用沐神封装的try_gpu()函数自动获取名称。

try_gpu()源码:

def try_gpu(i=0):
    """Return gpu(i) if exists, otherwise return cpu().

    Defined in :numref:`sec_use_gpu`"""
    if torch.cuda.device_count() >= i + 1:
        return torch.device(f'cuda:{i}')
    return torch.device('cpu')

 训练代码:

#Training
lr, num_epochs = 0.9, 10
train_gpu(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())

结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云龙弓手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值