如何用Sequential搭建深度学习实战中的小神经网络?
摘要:# 一、torch.nn.Sequential代码栗子 > 官方文档:[Sequential — PyTorch 2.0 documentation](https:pytorch.orgdocsstableg
一、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。
