Pytorch实现ResNet网络之Residual Block残差块
作者:实力 时间:2022-11-17 15:00:02
Residual Block
ResNet中最重要的组件是残差块(residual block),也称为残差单元(residual unit)。一个标准的残差块包含两层卷积层和一条跳过连接(skip connection),如下
假设输入x的大小为F×H×W,其中FFF表示通道数,H和W分别表示高度和宽度。那么通过残差块后输出的特征图的大小仍然是F×H×W。
跳过连接能够使得该层网络可以直接通过进行恒等映射(identity mapping)来优化模型,并避免反激化迫使网络退化。即残差块应该学习到输入数据和输出数据的差异,而不是完全复制输入数据。
实现一个残差块
代码如下所示:
import torch.nn as nn
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.shortcut = nn.Sequential()
if in_channels != out_channels or stride != 1:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels))
def forward(self, x):
residual = x
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
shortcut = self.shortcut(residual)
x += shortcut
x = self.relu(x)
return x
这段代码定义了一个继承自nn.Module
的残差块。在初始化过程中,我们定义了两个卷积层、两个批标准化(batch normalization)层以及一个恒等映射短连接(shortcut)。其中第二个卷积层的输入通道数必须与输出通道数相同。
在forward
函数中,我们首先将输入数据xxx保存到一个变量residual
中。然后将xxx通过第一个卷积层、批标准化以及ReLU激活函数,再通过第二个卷积层和批标准化。
默认情况下,跳过连接是一个恒等映射,即仅将输入数据复制并直接加到输出数据上。如果输入的通道数与输出的通道数不同,或者在卷积操作中改变了特征图的大小(stride > 1),则需要对输入进行适当的处理以与输出相匹配。我们使用1×1卷积层(又称为“投影级”)来改变大小和通道数,并将其添加到shortcut`, 确保整个残差块拓扑中都能够正确地实现残差学习。
来源:https://juejin.cn/post/7222854201201852476
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python 调用API接口 获取和解析 Json数据
pandas DataFrame索引行列的实现
对有自增长字段的表导入数据注意事项
微信小程序python用户认证的实现
![](https://img.aspxhome.com/file/2023/6/105816_0s.jpg)
深入浅出SQL嵌套SELECT语句
python聚类算法解决方案(rest接口/mpp数据库/json数据/下载图片及数据)
![](https://img.aspxhome.com/file/2023/6/117966_0s.png)
Python并行分布式框架Celery详解
![](https://img.aspxhome.com/file/2023/5/107535_0s.png)
Win10下配置VScode远程开发ssh-remote(免密登录)
![](https://img.aspxhome.com/file/2023/9/109519_0s.png)
Python中的基本数据类型介绍
![](https://img.aspxhome.com/file/2023/4/120314_0s.png)
pandas统计重复值次数的方法实现
ASP.NET MVC把数据库中枚举项的数字转换成文字
python+numpy+matplotalib实现梯度下降法
![](https://img.aspxhome.com/file/2023/8/95918_0s.gif)
使用mypy对python程序进行静态检查
![](https://img.aspxhome.com/file/2023/5/130815_0s.jpg)
python机器学习包mlxtend的安装和配置详解
![](https://img.aspxhome.com/file/2023/3/135373_0s.png)
vue.js中ref和$refs的使用及示例讲解
![](https://img.aspxhome.com/file/2023/2/133032_0s.png)
python的环境conda简介
python开发入门——set的使用
利用Anaconda完美解决Python 2与python 3的共存问题
Python3利用Dlib19.7实现摄像头人脸识别的方法
![](https://img.aspxhome.com/file/2023/1/76031_0s.gif)