神经网络与深度学习笔记二

深度学习平台

常见的深度学习平台如表1所示。

表1 常见深度学习平台对比

库名 发布者 支持语言 支持系统 T e n s o r F l o w G o o g l e P y t h o n / C + + / J a v a / G o L i n u x / M a c O S / A n d r o i d / i O S C a f f e U C B e r k e l e y P y t h o n / C + + / M a t l a b L i n u x / M a c O S / W i n d o w s J A X G o o g l e P y t h o n L i n u x / W i n d o w s M X N e t A m a z o n / D M L C ( 分布式机器学习社区 ) P y t h o n / C + + / M a t l a b / J u l i a / G o / R / S c a l a L i n u x / M a c O S / W i n d o w s / A n d r o i d / i O S T o r c h / P y T o r c h F a c e b o o k C / P y t h o n / . . L i n u x / M a c O S / W i n d o w s / A n d r o i d / i O S P a d d l e P a d d l e 百度 P y t h o n L i n u x / W i n d o w s M M d e t e c t i o n 商汤 / 港中文 P y t h o n L i n u x / W i n d o w s \begin{array}{cccc} \hline 库名&发布者&支持语言&支持系统\\ \hline TensorFlow&Google&Python/C++/Java/Go&Linux/Mac OS/Android/iOS\\ Caffe&UC Berkeley&Python/C++/Matlab&Linux/Mac OS/Windows\\ JAX&Google&Python&Linux/Windows\\ MXNet&Amazon/DMLC(分布式机器学习社区)&Python/C++/Matlab/Julia/Go/R/Scala&Linux/Mac OS/Windows/Android/iOS\\ Torch/PyTorch&Facebook&C/Python/..&Linux/Mac OS/Windows/Android/iOS\\ PaddlePaddle&百度&Python&Linux/Windows\\ MMdetection&商汤/港中文&Python&Linux/Windows\\ \hline \end{array} 库名TensorFlowCaffeJAXMXNetTorch/PyTorchPaddlePaddleMMdetection发布者GoogleUCBerkeleyGoogleAmazon/DMLC(分布式机器学习社区)Facebook百度商汤/港中文支持语言Python/C++/Java/GoPython/C++/MatlabPythonPython/C++/Matlab/Julia/Go/R/ScalaC/Python/..PythonPython支持系统Linux/MacOS/Android/iOSLinux/MacOS/WindowsLinux/WindowsLinux/MacOS/Windows/Android/iOSLinux/MacOS/Windows/Android/iOSLinux/WindowsLinux/Windows
其中最常用的为Pytorch与TensorFlow2,相较于TensorFlow2,Pytorch上手简单学习速度快、函数简介、运用灵活。

∙ \bullet 张量(Tensor)
是一个物理量,对高维(维数 ≥ \geq 2) 的物理量进行“量纲分析”的一种工具。简单的可以理解为:一维数组称为矢量,二维数组为二阶张量,三维数组为三阶张量 ⋯ \cdots
∙ \bullet 计算图
用“结点”(nodes)和“线 ”(edges)的有向图来描述数学计算的图像。“节点” 一般用来表示施加的数学操作,但也可以表示数据输入的起点输出的终点,或者是读取 写入持久变量的终点。“线”表示“节点”之间的输入 输出关系。这些数据“线”可以输运“ size 可动态调整”的多维数据数组,即“张量”(tensor)

Pytorch的基本使用包括:
1 ◯ \textcircled{1} 1使用tensor表示数据
2 ◯ \textcircled{2} 2使用Dataset 、DataLoader读取样本数据和标签
3 ◯ \textcircled{3} 3使用变量(Variable)存储神经网络权值等参数
4 ◯ \textcircled{4} 4使用计算图(computational graph)来表示计算任务
5 ◯ \textcircled{5} 5在代码运行过程中同时执行计算图

卷积神经网络

基本概念

∙ \bullet 全连接网络:链接权过多,难算难收敛,同时可能进入局部极小值,也容易产生过拟合问题.
∙ \bullet 局部连接网络:顾名思义,只有一部分权值连接。部分输入和权值卷积。
∙ \bullet 填充( Padding):也就是在矩阵的边界上填充一些值,以增加矩阵的大小,通常用 0 或者复制边界像素来进行填充。
∙ \bullet 步长(Stride):卷积核每次滑动的行数和列数。
∙ \bullet 池化(pooling):使用局部统计特征,如均值或最大值。解决特征过多问题。
∙ \bullet 卷积神经网络结构
\quad 构成:由多个卷积层和下采样层构成,后面可连接全连接网络
\quad 卷积层:k 个滤波器
\quad 下采样层:采用 mean 或 max
\quad 后面:连着全连接网络
前向传播定义为:
z [ l ] ( x , y ) = ∑ u = 0 p ∑ v = 0 q a [ l − 1 ] ( x + u , y + v ) w r o t [ l ] , k ( u , v ) (1) z^{[l]}(x,y)=\sum_{u=0}^{p}\sum_{v=0}^{q}a^{[l-1]}(x+u,y+v)w_{rot}^{[l],k}(u,v)\tag{1} z[l](x,y)=u=0pv=0qa[l1](x+u,y+v)wrot[l],k(u,v)(1) a [ l ] ( x , y ) = f ( z [ l ] ( x ) ) (2) a^{[l]}(x,y)=f(z^{[l]}(x))\tag{2} a[l](x,y)=f(z[l](x))(2)
若第 l l l层为卷积+池化层,则:
a [ l ] ( x , y ) = d o w n s a m p l e ( ∑ u = 0 p ∑ v = 0 q a [ l − 1 ] ( x + u , y + v ) w r o t [ l ] , k ( u , v ) ) (3) a^{[l]}(x,y)=downsample(\sum_{u=0}^{p}\sum_{v=0}^{q}a^{[l-1]}(x+u,y+v)w_{rot}^{[l],k}(u,v))\tag{3} a[l](x,y)=downsample(u=0pv=0qa[l1](x+u,y+v)wrot[l],k(u,v))(3)

LeNet-5

网络结构

LeNet(LeNet-5)由卷积编码器以及全连接密集块组成,如图1所示
在这里插入图片描述

图1 LeNet-5结构

∙ \bullet C1层
1 ◯ \textcircled{1} 1 6个Feature map构成
2 ◯ \textcircled{2} 2 每个神经元对输入进行55卷积
3 ◯ \textcircled{3} 3 每个神经元对应 5
5+1个参数,共6个feature map,28乘28个神经元,因此共有122,304连接
∙ \bullet S2层
下采样层,使用最大池化进行下采样,池化的size,选择(2,2)。
∙ \bullet C3层
卷积层,其卷积核大小为(5,5)。
∙ \bullet S4层
下采样层,与S2层工作相同。
∙ \bullet C5层
1 ◯ \textcircled{1} 1 120 个神经元
2 ◯ \textcircled{2} 2 每个神经元同样对输入进行 55 卷积,与 S4 全连接
3 ◯ \textcircled{3} 3 总连接数 (5
5*16+1)*120=48120
∙ \bullet F6层
1 ◯ \textcircled{1} 1 84 个神经元
2 ◯ \textcircled{2} 2 与 C5 全连接
3 ◯ \textcircled{3} 3 总连接数 (120+1)*84=10164
∙ \bullet 输出层
1 ◯ \textcircled{1} 1 由欧式径向基函数单元构成
2 ◯ \textcircled{2} 2 每类一个单元
3 ◯ \textcircled{3} 3 输出 RBF 单元计算输入向量和参数向量之间的欧式距离

网络说明

与现在网络的区别
1 ◯ \textcircled{1} 1卷积时不进行填充(padding)
2 ◯ \textcircled{2} 2池化层选用平均池化而非最大池化
3 ◯ \textcircled{3} 3选用Sigmoid或tanh而非ReLU作为非线性环节激活函数
4 ◯ \textcircled{4} 4层数较浅,参数数量小(约为6万)

普遍规律:随网络深入,宽、高衰减,通道数增加

代码实现

import torch
from torch import nn
from d2l import torch as d2l

#《动手学深度学习》6.6
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)
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
def evaluate_accuracy_gpu(net, data_iter, device=None): #@save
    """使用GPU计算模型在数据集上的精度"""
    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):
                # BERT微调所需的(之后将介绍)
                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]
#@save
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)
    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())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值