d2l基础LeNet实现与ch6各类基础函数讲解

文章详细介绍了如何使用PyTorch实现LeNet神经网络,包括网络结构搭建、数据集调整、GPU上的训练过程以及训练命令行。在数据集改正部分,针对内存限制调整了数据加载的线程数。训练过程中,讨论了loss函数的不同reduction选项对训练的影响,并提供了简化后的训练过程显示方式。

众所周知第七章在复现各大神经网络的时候也会用到ch6定义的各种函数,为了方便理解其中的细节,在这里具体讲解一下!

目录

1.LeNet实现

1.1net搭建

1.2数据集改正

1.3存储到gpu上的验证集

2.ch6训练

2.2loss探索

2.3改编版显数函数

2.4训练命令行


1.LeNet实现

1.1net搭建

  这里使用Seq简单复现即可,没啥好说的。

  注意:在Sequential里面也是可以写进自己的类的,详细见5_1。

            nn.Flatten()是将张量拉成(bs,-1)维度的张量

            注意最后送到全连接的input是需要自己算的!另外激活函数为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))
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)

'''
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])
'''

  简单用一个28的向量(与FM单张图片hw相同)看一下结构,注意卷积尺寸计算公式:

o=[(i+2p-k)/s]+1这个公式对应正方形尺寸图片卷积尺寸

1.2数据集改正

  原始的num_works=4,这里笔者的电脑太拉,用4的话内存不够用,所以改成2(如果2还不行直接上0)

def load_data_fashion_mnist_nw2(batch_size, resize=None):
    """下载Fashion-MNIST数据集,然后将其加载到内存中"""
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0, transforms.Resize(resize))
    trans = transforms.Compose(trans)
    mnist_train = torchvision.datasets.FashionMNIS
`d2l` 库是为了方便《动手学深度学习》(Dive into Deep Learning)这本书的学习而开发的辅助库。随着版本的升级,库中的函数结构和名称可能会发生变化,导致 `train_ch3` 函数缺失。以下是一些可能的解决方法: ### 1. 查看文档和更新日志 首先要查看 `d2l` 库的官方文档和更新日志,了解 `train_ch3` 函数在新版本中是否有替代函数或者被移除的原因。一般可以在 `d2l` 的 GitHub 仓库(https://github.com/d2l-ai/d2l-en )中找到相关信息。 ### 2. 手动定义函数 如果在新版本中该函数确实被移除,且没有合适的替代函数,可以手动将旧版本中的 `train_ch3` 函数代码复制到自己的项目中。以下是 `train_ch3` 函数的示例代码: ```python import time import torch from torch import nn from d2l import torch as d2l def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], legend=['train loss', 'train acc', 'test acc']) for epoch in range(num_epochs): train_metrics = d2l.train_epoch_ch3(net, train_iter, loss, updater) test_acc = d2l.evaluate_accuracy(net, test_iter) animator.add(epoch + 1, train_metrics + (test_acc,)) train_loss, train_acc = train_metrics assert train_loss < 0.5, train_loss assert train_acc <= 1 and train_acc > 0.7, train_acc assert test_acc <= 1 and test_acc > 0.7, test_acc ``` ### 3. 回退到旧版本 如果手动定义函数比较麻烦,也可以考虑将 `d2l` 库回退到包含 `train_ch3` 函数的旧版本。可以使用以下命令安装指定版本的 `d2l` 库: ```bash pip install d2l==<version_number> ``` 将 `<version_number>` 替换为包含 `train_ch3` 函数的版本号。
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值