动手学深度学习V2每日笔记(经典卷积神经网络LeNet)

本文主要参考沐神的视频教程 https://www.bilibili.com/video/BV1t44y1r7ct/spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=c7bfc6ce0ea0cbe43aa288ba2713e56d
文档教程 https://zh-v2.d2l.ai/

本文的主要内容对沐神提供的代码中个人不太理解的内容进行笔记记录,内容不会特别严谨仅供参考。

1.函数目录

1.1 torch

torch.nn位置
MaxPool2d2.2

2. LeNet

  • LeNet是早期成功的神经网络
  • 先使用卷积层来学习图片空间信息
  • 然后使用全连接层来转换到类别空间
    在这里插入图片描述
    LeNet-5网络参数详解
操作输出形状
输入层\1x28x28
卷积层kernel=5、padding=2、stride=1、output_channel=66x28x28
平均池化层kernel=2、padding=0、stride=26x14x14
卷积层kernel=5、padding=0、stride=1、output_channel=1616x10x10
平均池化层kernel=2、padding=0、stride=216x5x5
全连接层480->120120
全连接层120->8484
全连接层84->1010

在这里插入图片描述

3. 代码实现

3.1 model

import torch
from torch import nn

class Reshape(torch.nn.Module):
    def forward(self, x):
        return x.view(-1, 1, 28, 28)

net = nn.Sequential(
    Reshape(),
    nn.Conv2d(in_channels=1, out_channels=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((1,1,28,28), dtype=torch.float32)
for layer in net:
    X = layer(X)
    print(layer.__class__.__name__, 'output shape:\t',X.shape)

3.2 train

import torch
from torch import nn

import model
import tools
from model import net
from d2l import torch as d2l
import pandas as pd
from tools import *

def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
    """用GPU训练模型(在第六章定义)"""
    #模型参数初始化
    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)
    # 定义优化器
    ptimizer = torch.optim.SGD(net.parameters(), lr=lr)
    # 定义损失函数
    loss = nn.CrossEntropyLoss()
    # 训练集损失函数
    # 训练集损失列表
    train_loss_all = []
    train_acc_all = []
    # 验证集损失列表
    val_loss_all = []
    val_acc_all = []
    timer = tools.Timer()
    timer.start()
    for epoch in range(num_epochs):
        train_loss, train_acc = train_epoch_gpu(net, train_iter, loss, ptimizer, device)
        val_loss, val_acc = evalution_loss_accuracy_gpu(net, test_iter, loss, device)
        train_loss_all.append(train_loss)
        train_acc_all.append(train_acc)
        val_loss_all.append(val_loss)
        val_acc_all.append(val_acc)
        print("{} train loss:{:.4f} train acc: {:.4f}".format(epoch, train_loss_all[-1], train_acc_all[-1]))
        print("{} val loss:{:.4f} val acc: {:.4f}".format(epoch, val_loss_all[-1], val_acc_all[-1]))
        print("训练和验证耗费的时间{:.0f}m{:.0f}s".format(timer.stop() // 60, timer.stop() % 60))

    train_process = pd.DataFrame(data={"epoch": range(num_epochs),
                                       "train_loss_all": train_loss_all,
                                       "val_loss_all": val_loss_all,
                                       "train_acc_all": train_acc_all,
                                       "val_acc_all": val_acc_all, })
    return train_process

if __name__ == "__main__":
    batch_size = 256
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
    LeNet5 = model.net
    train_process = train_ch6(LeNet5,train_iter,test_iter,10,0.8,tools.try_gpu())
    tools.matplot_acc_loss(train_process)

自定义的tools文件

import pandas as pd
import torch
import matplotlib.pyplot as plt
from torch import nn
import time
import numpy as np

class Timer:  #@save
    """记录多次运行时间"""
    def __init__(self):
        self.times = []
        self.start()

    def start(self):
        """启动计时器"""
        self.tik = time.time()

    def stop(self):
        """停止计时器并将时间记录在列表中"""
        self.times.append(time.time() - self.tik)
        return self.times[-1]

    def avg(self):
        """返回平均时间"""
        return sum(self.times) / len(self.times)

    def sum(self):
        """返回时间总和"""
        return sum(self.times)

    def cumsum(self):
        """返回累计时间"""
        return np.array(self.times).cumsum().tolist()


argmax = lambda x, *args, **kwargs: x.argmax(*args, **kwargs) #返回最大值的索引下标
astype = lambda x, *args, **kwargs: x.type(*args, **kwargs)  # 转换数据类型
reduce_sum = lambda x, *args, **kwargs: x.sum(*args, **kwargs)  # 求和

# 对多个变量累加
class Accumulator:
    """For accumulating sums over `n` variables."""

    def __init__(self, n):
        """Defined in :numref:`sec_utils`"""
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]

# 计算正确预测的数量
def accuracy(y_hat, y):
    """Compute the number of correct predictions.
    Defined in :numref:`sec_utils`"""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        y_hat = argmax(y_hat, axis=1)
    cmp = astype(y_hat, y.dtype) == y
    return float(reduce_sum(astype(cmp, y.dtype)))

# 单轮训练
def train_epoch(net, train_iter, loss, trainer):
    if isinstance(net, nn.Module):
        net.train()
    metric_train = Accumulator(3)
    for X, y in train_iter:
        y_hat = net(X)
        l = loss(y_hat, y)
        if isinstance(trainer, torch.optim.Optimizer):
            trainer.zero_grad()
            l.mean().backward()
            trainer.step()
        else:
            l.sum().backward()
            trainer(X.shape[0])
        metric_train.add(float(l.sum()), accuracy(y_hat, y), y.numel())
    #返回训练损失和训练精度
    return metric_train[0]/metric_train[2], metric_train[1]/metric_train[2]

# 单轮训练
def train_epoch_gpu(net, train_iter, loss, trainer,device):
    if isinstance(net, nn.Module):
        net.train()
    metric_train = Accumulator(3)
    for i, (X, y) in enumerate(train_iter):
        X, y = X.to(device), y.to(device)
        y_hat = net(X)
        l = loss(y_hat, y)
        if isinstance(trainer, torch.optim.Optimizer):
            trainer.zero_grad()
            l.backward()
            trainer.step()
        else:
            l.sum().backward()
            trainer(X.shape[0])
        metric_train.add(l * X.shape[0], accuracy(y_hat, y), X.shape[0])
    #返回训练损失和训练精度
    return metric_train[0]/metric_train[2], metric_train[1]/metric_train[2]

# 用于计算验证集上的准确率
def evalution_loss_accuracy(net, data_iter, loss):
    if isinstance(net, torch.nn.Module):
        net.eval()
    meteric = Accumulator(3)
    with torch.no_grad():
        for X, y in data_iter:
            l = loss(net(X), y)
            meteric.add(float(l.sum())*X.shape[0], accuracy(net(X), y), X.shape[0])
    return meteric[0]/meteric[2], meteric[1]/meteric[2]

# 用于计算验证集上的准确率
def evalution_loss_accuracy_gpu(net, data_iter, loss, device='None'):
    if isinstance(net, torch.nn.Module):
        net.eval()
        if not device:
            #将net层的第一个元素拿出来看其在那个设备上
            device = next(iter(net.parameters())).device
    meteric = Accumulator(3)
    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)  # 赋值给 X,将数据移动到GPU中
            y = y.to(device)  # 赋值给 y,将数据移动到GPU中
            l = loss(net(X), y)
            meteric.add(l * X.shape[0], accuracy(net(X), y), X.shape[0])
            # meteric.add(float(l.sum()), accuracy(net(X), y), y.numel())  # 转为浮点数
    return meteric[0]/meteric[2], meteric[1]/meteric[2]

def matplot_acc_loss(train_process):
    # 显示每一次迭代后的训练集和验证集的损失函数和准确率
    plt.figure(figsize=(12, 4))
    plt.subplot(1, 2, 1)
    plt.plot(train_process['epoch'], train_process.train_loss_all, "ro-", label="Train loss")
    plt.plot(train_process['epoch'], train_process.val_loss_all, "bs-", label="Val loss")
    plt.legend()
    plt.xlabel("epoch")
    plt.ylabel("Loss")
    plt.subplot(1, 2, 2)
    plt.plot(train_process['epoch'], train_process.train_acc_all, "ro-", label="Train acc")
    plt.plot(train_process['epoch'], train_process.val_acc_all, "bs-", label="Val acc")
    plt.xlabel("epoch")
    plt.ylabel("acc")
    plt.legend()
    plt.show()

def gpu(i=0):
    """Get a GPU device.

    Defined in :numref:`sec_use_gpu`"""
    return torch.device(f'cuda:{i}')

def cpu():
    """Get the CPU device.

    Defined in :numref:`sec_use_gpu`"""
    return torch.device('cpu')
def num_gpus():
    """Get the number of available GPUs.

    Defined in :numref:`sec_use_gpu`"""
    return torch.cuda.device_count()

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

    Defined in :numref:`sec_use_gpu`"""
    if num_gpus() >= i + 1:
        return gpu(i)
    return cpu()
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 动手深度学习v2是一本非常好的深度学习教材,是从谷歌机器习研究员李沐所主持的Gluon团队创作的。它提供了丰富的案例和实际应用,深入浅出地介绍了深度学习的基础理论和实践技能。 下载动手深度学习v2非常简单,可以通过访问官方网站来获取。首先,打开谷歌或百度搜索引擎,搜索"动手深度学习v2下载",就可以找到相关的下载链接。建议选择官网下载,因为官网下载最为安全可靠。 进入官网后,点击首页上的"下载"按钮,然后在目录下找到本书的下载链接,下载适合你的版本即可。此外,动手深度学习v2还有在线阅读的版本,方便习者随时随地习。 总的来说,动手深度学习v2是一本非常优秀的深度学习教材,相关下载链接也十分便捷,能够帮助广大习者更好地掌握深度学习相关的知识和技能。 ### 回答2: 动手深度学习v2是一本非常优秀的深度学习入门书籍,笔者十分推荐。如果您想要下载该书籍,可以使用以下方法: 1.进入动手深度学习v2的官网(https://zh.d2l.ai/),点击右上角的“Github”按钮,进入书籍的Github仓库。 2.在仓库中找到“releases”目录,选择最新的版本号,点击进入。 3.在该版本的页面中,找到“Source code (zip)”或“Source code (tar.gz)”选项,点击下载压缩包。 4.下载完成后,解压缩文件即可得到电子书的文件夹,其中包括PDF和HTML格式的书籍。 除此之外,您也可以在该官网中找到由中文社区翻译的在线电子书版本。在该电子书中,您可以直接在线阅读和习。值得注意的是,该书籍的在线翻译版本可能会比英文原版稍有滞后。如果您想要阅读最新的内容,请下载英文原版或者在该官网上查看最新的更新。 ### 回答3: 深度学习是现在的热门话题之一。而动手深度学习v2是一本非常好的深度学习教材,旨在为做实际项目的习者提供知识技能和实战经验。为了下载此书,您需要按照以下步骤进行。 首先,您需要访问动手深度学习官方网站,网址为d2l.ai。然后,您需要找到下载页面,这个页面可以通过页面上的“全书下载”按钮或主页面上的一个标签来访问。 在下载页面,您需要选择您所需要的版本,v2版本是最新版本。接着,您需要选择您所需的格式。您可以选择PDF格式或HTML格式,下方还提供了在线阅读链接。 若您选择了PDF格式,则需要点击下载链接,页面会跳到GitHub仓库中。在GitHub页面,您需要选择ZIP文件并下载。下载完成后,您就可以在本地解压并阅读这本书了。 若您选择了HTML格式,则不需下载,只需点击在线阅读链接即可。页面会跳转到包含书籍所有章节、实例代码、作者笔记等信息的HTML页面,您可以任意阅读或者下载章节(在左侧点击对应章节)。 总之,动手深度学习v2是一本亲身实践的深度学习教材,其深入浅出的讲解以及丰富的实战案例,能够帮助初者快速掌握深度学习这一技术,同时也是深度学习领域专业人士的必备读物。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值