深度学习(十二)——神经网络:搭建小实战和Sequential的使用

深度,学习,十二,神经网络,搭建,实战,sequential,使用 · 浏览次数 : 165

小编点评

**代码优化** * **`Sequential`**函数的优越,可以使多个操作合并在一起,减少代码复杂度。 * **``summary`**`库用于可视化神经网络参数,可以帮助我们理解模型的相关参数。 * **``torch.utils.tensorboard`**库用于生成神经网络相关的图表,可以帮助我们了解模型的相关参数。 **代码** ```python class Demo(nn.Module): def __init__(self): super(Demo,self).__init__() # 使用Sequential函数将多个操作合并在一起 self.model1=Sequential( Conv2d(3,32,5,padding=2), MaxPool2d(2), Conv2d(32, 32, 5, padding=2), MaxPool2d(2), Conv2d(32, 64, 5, padding=2), MaxPool2d(2), Flatten(), Linear(1024, 64), Linear(64, 10) ) def forward(self,x): x=self.model1(x) return x # 可视化神经网络参数 writer = SummaryWriterwriter("logs_seq") writer.add_graph(Demo,input) writer.close() ```

正文

一、torch.nn.Sequential代码栗子

官方文档:Sequential — PyTorch 2.0 documentation

# Using Sequential to create a small model. When `model` is run,
# input will first be passed to `Conv2d(1,20,5)`. The output of
# `Conv2d(1,20,5)` will be used as the input to the first
# `ReLU`; the output of the first `ReLU` will become the input
# for `Conv2d(20,64,5)`. Finally, the output of
# `Conv2d(20,64,5)` will be used as input to the second `ReLU`
model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )
  • 在第一个变量名model中,依次执行nn.Convd2d(1,20,5)nn.ReLU()nn.Conv2d(20,64,5)nn.ReLU()四个函数。这样写起来的好处是使代码更简洁

  • 由此可见,函数\(Sequential\)的主要作用为依次执行括号内的函数

二、神经网络搭建实战

采用\(CIFAR10\)中的数据,并对其进行简单的分类。以下图为例:

  • 输入:3通道,32×32 → 经过一个5×5的卷积 → 变成32通道,32×32的图像 → 经过2×2的最大池化 → 变成32通道,16×16的图像.... → ... → 变成64通道,4×4的图像 → 把图像展平(Flatten)→ 变成64通道,1×1024 (64×4×4) 的图像 → 通过两个线性层,最后\(out\_feature=10\) → 得到最终图像

以上,就是CIFAR10模型的结构。本节的代码也基于CIFAR10 model的结构构建。

1. 神经网络中的参数设计及计算

(1)卷积层的参数设计(以第一个卷积层conv1为例)

  • 输入图像为3通道,输出图像为32通道,故:\(in\_channels=3\)\(out\_channels=32\)

  • 卷积核尺寸为\(5×5\)

  • 图像经过卷积层conv1前后的尺寸均为32×32,根据公式:

    \[H_{out}​=⌊\frac{H_{in}​+2×padding[0]−dilation[0]×(kernel\_size[0]−1)−1​}{stride[0]}+1⌋ \]

    \[W_{out}​=⌊\frac{W_{in}​+2×padding[1]−dilation[1]×(kernel\_size[1]−1)−1​}{stride[1]}+1⌋ \]

    可得:

    \[H_{out}​=⌊\frac{32​+2×padding[0]−1×(5−1)−1​}{stride[0]}+1⌋=32 \]

    \[W_{out}​=⌊\frac{32​+2×padding[1]−1×(5−1)−1​}{stride[1]}+1⌋=32 \]

    即:

    \[\frac{27+2×padding[0]​}{stride[0]}=31 \]

    \[\frac{27+2×padding[1]​}{stride[1]}=31 \]

    \(stride[0]\)\(stride[1]\)设置为2,那么上面的\(padding\)也会随之扩展为一个很大的数,这很不合理。所以这里设置:\(stride[0]=stride[1]=1\),由此可得:\(padding[0]=padding[1]=2\)

其余卷积层的参数设计及计算方法均同上

(2)最大池化操作的参数设计(以第一个池化操作maxpool1为例)

  • 由图可得,\(kennel\_size=2\)

其余最大池化参数设计方法均同上

(3)线性层的参数设计

  • 通过三次卷积和最大池化操作后,图像尺寸变为64通道4×4。之后使用\(Flatten()\)函数将图像展成一列,此时图像尺寸变为:1×(64×4×4),即\(1×1024\)

  • 因此,之后通过第一个线性层,\(in\_features=1024\)\(out\_features=64\)

  • 通过第二个线性层,\(in\_features=64\)\(out\_features=10\)

2. 构建神经网络实战

import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear

class Demo(nn.Module):
    def __init__(self):
        super(Demo,self).__init__()

        # 搭建第一个卷积层:in_channels=3,out_channels=32,卷积核尺寸为5×5,通过计算得出:padding=2;stride默认情况下为1,不用设置
        self.conv1=Conv2d(3,32,5,padding=2)

        # 第一个最大池化操作,kennel_size=2
        self.maxpool1=MaxPool2d(2)

        # 第二个卷积层及最大池化操作
        self.conv2=Conv2d(32,32,5,padding=2)
        self.maxpool2=MaxPool2d(2)

        # 第三个卷积层及最大池化操作
        self.conv3=Conv2d(32,64,5,padding=2)
        self.maxpool3=MaxPool2d(2)

        # 展开图像
        self.flatten=Flatten()

        # 线性层参数设计
        self.linear1=Linear(1024,64)
        self.linear2=Linear(64,10)

        # 如果是预测概率,那么取输出结果的最大值(它代表了最大概率)

    def forward(self,x):
        x = self.conv1(x)
        x = self.maxpool1(x)
        x = self.conv2(x)
        x = self.maxpool2(x)
        x = self.conv3(x)
        x = self.maxpool3(x)
        x = self.flatten(x)
        x = self.linear1(x)   #如果线性层的1024和64不会计算,可以在self.flatten之后print(x.shape)查看尺寸,以此设定linear的参数
        x = self.linear2(x)
        return x

demo=Demo()
print(demo)
"""
[Run]
Demo(
  (conv1): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
  (maxpool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
  (maxpool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv3): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
  (maxpool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (flatten): Flatten(start_dim=1, end_dim=-1)
  (linear1): Linear(in_features=1024, out_features=64, bias=True)
  (linear2): Linear(in_features=64, out_features=10, bias=True)
)

可以看出,网络还是有模有样的
"""

#构建输入,测试神经网络
input=torch.ones((64,3,32,32))  #构建图像,batch_size=64,3通道,32×32
output=demo(input)
print(output.shape)  #[Run] torch.Size([64, 10])

这里的\(forward\)函数写的有点烦,这时候\(Sequential\)函数的优越就体现出来了(墨镜黄豆)。下面是\(class\) \(Demo\)优化后的代码:

class Demo(nn.Module):
    def __init__(self):
        super(Demo,self).__init__()

        self.model1=Sequential(
            Conv2d(3,32,5,padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self,x):
        x=self.model1(x)
        return x

极简主义者看过后表示很满意ε٩(๑> ₃ <)۶з

3. 可视化神经网络

from torch.utils.tensorboard import SummaryWriter
writer=SummaryWriter("logs_seq")
writer.add_graph(demo,input)
writer.close()

这样就可以清晰地看到神经网络的相关参数啦

与深度学习(十二)——神经网络:搭建小实战和Sequential的使用相似的内容:

深度学习(十二)——神经网络:搭建小实战和Sequential的使用

“搭个网络真不难,像呼吸一样简单。”周华健学长如是地说(狗头)

深度学习(十一)——神经网络:线形层及其他层介绍

主要介绍神经网络线性层的计算,即torch.nn.Linear的原理及应用。并插入一些神经网络的其他层介绍,及调用pytorch中网络模型的方法。

深度学习(十)——神经网络:非线性激活

主要介绍了ReLU和Sigmiod两种非线性激活函数,以及在神经网络中进行非线性转换的目的。

深度学习(十四)——优化器

反向传播可以求出神经网路中每个需要调节参数的梯度,优化器可以根据梯度进行调整,达到降低整体误差的作用。本节我们对优化器进行介绍。

深度学习(十三)——损失函数与反向传播

介绍MAE、MSE、交叉熵三种损失函数计算及使用方法,以及反向传播的作用。

Python学习之十八_django的学习(二)

# Python学习之十八_django的学习(二) ## 前言 ``` 前面学习了基本的django的使用. 这里想着稍微深入一点学习templates 以及进行级联的路由展示. ``` ## 修改配置文件 ``` 要想使用 templates下面的文件. 需要修改一下项目级别的 settings

salesforce零基础学习(一百二十八)Durable Id获取以及相关概念浅入浅出

本篇参考: salesforce 零基础开发入门学习(十一)sObject及Schema深入 https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_enti

深度学习论文翻译解析(二十二):Uniformed Students Student-Teacher Anomaly Detection With Discriminative Latent Embbeddings

论文标题:Uniformed Students Student-Teacher Anomaly Detection With Discriminative Latent Embbeddings 论文作者: Paul Bergmann Michael Fauser David Sattlegger C

深度学习项目-MobileNetV2水果识别模型

本项目旨在研究利用深度学习模型进行水果图像分类的方法,具体包括两个主要任务:一是使用卷积神经网络(CNN)模型进行水果图片的分类,二是探索轻量级神经网络模型MobileNetV2在水果图像分类中的应用。

深度学习框架火焰图pprof和CUDA Nsys配置指南

注:如下是在做深度学习框架开发时,用到的火焰图pprof和 CUDA Nsys 配置指南,可能对大家有一些帮助,就此分享。一些是基于飞桨的Docker镜像配置的。 一、环境 & 工具配置 0. 开发机配置 # 1.构建镜像, 记得映射端口,可以多映射几个;记得挂载ssd目录,因为数据都在ssd盘上