修订历史:
- 2025/02/16 介绍了 ResNet 的关键概念,包括 ResNet 网络结构的构建以及基本模块(asicBlock 和 Bottleneck)的设计,以及expansion 的作用等。
残差网络(ResNet)由微软研究院的何恺明、张祥雨、任少卿、孙剑等人提出,解决了随着网络深度增加而出现的训练精度下降问题,即 “退化现象(Degradation)”。ResNet 通过引入 “快捷连接(Shortcut connection)”,极大地消除了深度神经网络训练困难,使得网络深度可以突破 100 层,甚至达到 1000 层。
ResNet概述
- 由何恺明等提出
- 解决了深层网络的退化问题
- 引入了快捷连接(Shortcut connection)
- 使得网络深度突破100层,最大超过1000层
梯度消失/爆炸
深度神经网络中的梯度消失 / 爆炸问题主要是由于深度结构和反向传播算法的特性。梯度消失是指网络层之间的梯度(值小于 1.0)重复相乘导致的指数级变小,而梯度爆炸则是指梯度(值大于 1.0)重复相乘导致的指数级增长,这两种情况都会导致网络训练困难。
- 梯度消失/爆炸的根源
- 深度网络结构和反向传播算法
- 梯度消失和梯度爆炸的产生原因
源码解读
卷积核封装
- 封装3x3和1x1卷积核
- 提高代码可读性
def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
"""该函数返回一个3x3的卷积层,具有指定的输入通道、输出通道、步长、填充、分组数和扩张率。
参数: - in_planes: int,输入通道数 - out_planes: int,输出通道数 - stride: int,可选,卷积操作的步长,默认值为1 - groups: int,可选,分组卷积的分组数,默认值为1 - dilation: int,可选,卷积核的扩张率,默认值为1
返回: - 返回一个配置好的nn.Conv2d卷积层
"""
return nn.Conv2d(
in_planes, #输入通道数
out_planes, #输出通道数
kernel_size=3, # 卷积核大小为3x3
stride=stride, #卷积操作的步长,默认值为1
padding=dilation, #卷积核的扩张率,默认值为1.同时用于计算padding大小以保持特征图尺寸
groups=groups, #分组卷积的分组数,默认值为1
bias=False, # 不使用偏置项
dilation=dilation, # 卷积核的扩张率
)
def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
"""
该函数用于创建并返回一个1x1的卷积层。这种卷积通常用于调整通道数或进行线性变换。
参数:
- in_planes: int,输入通道数
- out_planes: int,输出通道数
- stride: int,可选,卷积操作的步长,默认值为1
返回:
- 返回一个配置好的nn.Conv2d卷积层
"""
return nn.Conv2d(
in_planes, # 输入通道数
out_planes, # 输出通道数
kernel_size=1, # 卷积核大小为1x1
stride=stride, # 卷积操作的步长
bias=False, # 不使用偏置项
)
基本模块设计
- ResNet由BasicBlock和Bottleneck组成
- ResNet-18/34与ResNet-50/101/152结构差异
- BasicBlock和Bottleneck的设计和作用
Shortcut Connection
- 同等维度映射和不同维度映射
- 通过1x1卷积实现维度匹配
BasicBlock
BasicBlock 类是 PyTorch 中用于构建卷积神经网络的一个基本模块,通常用于 ResNet(残差网络)中。
- 通常,拥有构建构建ResNet-18和ResNet-34
- 输入输出通道数相同
class BasicBlock(nn.Module):
expansion: int = 1
#`BasicBlock` 继承自 `nn.Module`,是 PyTorch 中自定义层的标准方式。
#`expansion` 属性表示输出通道数相对于输入通道数的扩展倍数,对于 `BasicBlock` 来说,这个值是 1。
def __init__(
self,
inplanes: int, #输入通道数
planes: int, #输出通道数
stride: int = 1, #卷积层的步长,默认为 1
downsample: Optional[nn.Module] = None, #一个可选的模块,用于在需要时对输入进行下采样,以匹配主路径的输出维度
groups: int = 1, #卷积层的分组数,`BasicBlock` 只支持 groups=1
base_width: int = 64, #基础宽度,`BasicBlock` 只支持 base_width=64
dilation: int = 1, #`dilation`: 卷积核的扩张率,`BasicBlock` 不支持 dilation>1
norm_layer: Optional[Callable[..., nn.Module]] = None,
) -> None: #正则化层,默认为 `nn.BatchNorm2d`
super().__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
#检查 `groups` 和 `base_width` 是否为默认值
if groups != 1 or base_width != 64:
raise ValueError("BasicBlock only supports groups=1 and base_width=64")
if dilation > 1:
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = norm_layer(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = norm_layer(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x: Tensor) -> Tensor:
identity = x # 备份输入张量,用于后续的残差连接
out = self.conv1(x) # 对x做卷积
out = self.bn1(out) # 对x归一化
out = self.relu(out) # 对x用激活函数
out = self.conv2(out) # 对x做卷积
out = self.bn2(out) # 归一化
#如果 `self.downsample` 不为 `None`,则对 `identity` 进行下采样,以匹配主路径的输出维度
if self.downsample is not None:
identity = self.downsample(x)
out += identity # 将主路径的输出与 `identity` 相加,实现残差连接
out = self.relu(out)
Bottleneck
Bottleneck 类是 PyTorch 中用于构建 ResNet 网络的一个关键模块,它是一个瓶颈残差单元,通常用于构建更深的 ResNet 网络,如 ResNet-50、ResNet-101 和 ResNet-152。
- 构建ResNet-50/101/152
- 减少中间特征图通道数
class Bottleneck(nn.Module):
# Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
# while original implementation places the stride at the first 1x1 convolution(self.conv1)
# according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
# This variant is also known as ResNet V1.5 and improves accuracy according to
# https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
expansion: int = 4 # 对输出通道进行倍增
def __init__(
self,
inplanes: int,
planes: int, #中间层通道数,输出通道数将是 `planes * self.expansion`
stride: int = 1,
downsample: Optional[nn.Module] = None, #一个可选的模块,用于在输入和输出维度不匹配时对输入进行下采样
groups: int = 1,
base_width: int = 64,
dilation: int = 1,
norm_layer: Optional[Callable[..., nn.Module]] = None,
) -> None:
"""
在初始化方法中,`Bottleneck` 模块创建了三个卷积层(`self.conv1`, `self.conv2`, `self.conv3`)和对应的批量归一化层(`self.bn1`, `self.bn2`, `self.bn3`)。第一个和第三个卷积层是 1x1 卷积,用于调整通道数,第二个卷积层是 3x3 卷积,用于提取特征。如果 `stride` 不为 1,则 `self.conv2` 和 `self.downsample` 会进行下采样。
"""
super().__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
#`base_width`: 基础宽度,用于计算卷积层的实际宽度,默认为 64
width = int(planes * (base_width / 64.0)) * groups
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv1x1(inplanes, width)
self.bn1 = norm_layer(width)
self.conv2 = conv3x3(width, width, stride, groups, dilation)
self.bn2 = norm_layer(width)
self.conv3 = conv1x1(width, planes * self.expansion)
self.bn3 = norm_layer(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
# Bottleneckd forward函数和BasicBlock类似,不再额外注释
def forward(self, x: Tensor) -> Tensor:
"""
`ottleneck` 类实现了 ResNet 中的瓶颈残差单元,通过使用 1x1 卷积层减少和增加通道数,可以在保持网络深度的情况下减少计算量。
"""
identity = x # x 为输入张量;identity 备份输入张量,用于后续的残差连接
#对输入进行 1x1 卷积、归一化和激活
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
#对结果进行 3x3 卷积、归一化和激活
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
#对结果进行 1x1 卷积和归一化
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity #将主路径的输出与 `identity` 相加,实现残差连接
out = self.relu(out) #通过 `self.relu` 应用激活函数
return out
Expansion作用
- 对输出通道进行倍增
- BasicBlock和Bottleneck的通道数控制
在 ResNet 的实现中,expansion 用于对输出通道进行倍增,以匹配不同层次的通道数目变化。对于 ResNet-18 和 ResNet-34,expansion 设置为 1;而对于 ResNet-50、ResNet-101 和 ResNet-152,expansion 设置为 4,以适应这些网络中的通道数目扩展。
网络整体结构
- ResNet网络由多个layer组成
- 每个layer由多个BasicBlock或Bottleneck堆叠
- 网络初始化和参数设置
这段代码定义了一个 ResNet 类,它是一个深度卷积神经网络模型,用于图像分类任务。以下是代码的详细注释和解释:
类定义
class ResNet(nn.Module):
- ResNet 类继承自
nn.Module,是 PyTorch 中自定义模型的标准方式。
初始化方法
def __init__(
self,
block: Type[Union[BasicBlock, Bottleneck]], # 选择基本模块
layers: List[int], # 每一层block的数目构成 -> [3,4,6,3]
num_classes: int = 1000, # 分类数目
zero_init_residual: bool = False, # 初始化
# 其他卷积构成,与本文ResNet无关
groups: int = 1,
width_per_group: int = 64,
replace_stride_with_dilation: Optional[List[bool]] = None,
# norm层
norm_layer: Optional[Callable[..., nn.Module]] = None,
) -> None:
block: 指定使用的基本模块,可以是BasicBlock或Bottleneck。layers: 一个列表,表示每个残差层中基本模块的数目。num_classes: 分类任务的类别数,默认为 1000。zero_init_residual: 是否对残差分支的最后一个批量归一化层进行零初始化。groups,width_per_group,replace_stride_with_dilation: 这些参数用于调整网络结构,通常用于更复杂的变体,如 ResNeXt。norm_layer: 指定使用的归一化层,默认为nn.BatchNorm2d。
网络结构
#接着上面代码
self.inplanes = 64 # 输入通道
#######其他卷积构成,与本文ResNet无关######
self.dilation = 1 # 空洞卷积
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError(
"replace_stride_with_dilation should be None "
f"or a 3-element tuple, got {replace_stride_with_dilation}"
)
self.groups = groups
self.base_width = width_per_group
#########################################
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# 通过_make_layer带到层次化设计的效果
self.layer1 = self._make_layer(block, 64, layers[0]) # 对应着conv2_x
self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) # 对应着conv3_x
self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]) # 对应着conv4_x
self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]) # 对应着conv5_x
# 分类头
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.inplanes: 初始输入通道数,设置为 64。self.conv1: 第一个卷积层,使用 7x7 卷积核,步长为 2,填充为 3,无偏置。self.bn1: 第一个批量归一化层。self.relu: ReLU 激活函数。self.maxpool: 3x3 最大池化层,步长为 2,填充为 1。self.layer1到self.layer4: 四个残差层,每个层由多个基本模块组成,通道数逐渐增加。self.avgpool: 自适应平均池化层,将特征图大小调整为 1x1。self.fc: 全连接层,用于分类。
模型初始化
# 接着上面代码
# 模型初始化
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck) and m.bn3.weight is not None:
nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]
elif isinstance(m, BasicBlock) and m.bn2.weight is not None:
nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type]
- 对卷积层使用 Kaiming 正态初始化。
- 对批量归一化层使用常数初始化,权重初始化为 1,偏置初始化为 0。
- 如果
zero_init_residual为 True,则对残差分支的最后一个批量归一化层进行零初始化。
层次化设计
def _make_layer(
self,
block: Type[Union[BasicBlock, Bottleneck]], # 基本构成模块选择
planes: int, # 输入的通道
blocks: int, # 模块数目
stride: int = 1, # 步长
dilate: bool = False, # 空洞卷积,与本文无关
) -> nn.Sequential:
_make_layer方法用于创建每个残差层,包含多个基本模块。block: 基本模块类型。planes: 该层的通道数。blocks: 该层中基本模块的数目。stride: 第一个基本模块的步长。dilate: 是否使用空洞卷积。
前向传播方法
def _forward_impl(self, x: Tensor) -> Tensor:
# 省略中间层的前向传播代码
x = self.avgpool(x) # 自适应池化
x = torch.flatten(x, 1)
x = self.fc(x) # 分类
return x
def forward(self, x: Tensor) -> Tensor:
return self._forward_impl(x)
_forward_impl: 实现模型的前向传播逻辑。forward: 调用_forward_impl方法,实现模型的前向传播。 这个 ResNet 类实现了 ResNet 网络的完整结构,包括卷积层、批量归一化层、激活函数、池化层、残差层和全连接层。通过组合不同的基本模块和层,可以构建不同深度的 ResNet 网络,如 ResNet-18、ResNet-34、ResNet-50 等。
总结
- ResNet通过Shortcut解决了深度网络的信息传递问题
- 简化学习目标,提高网络性能
- ResNet的改进和衍生模型
- ResNet在深度学习中的重要性