# ResNet代码实现及原理——学习记录

Pytorch版源代码下载地址：
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py

ResNet

ResNet原理及具体细节不过多介绍，网上很多大佬总结的很好，我主要就是记录自己学习ResNet的过程，感觉是重点和难点的部分，话不多说进入正题。

1、深度残差网络（Deep Residual Network）

2、残差结构
ResNet中使用了一种连接方式叫做” shortcut connection“,顾名思义，就是抄近道的意思。

y= F(x) + x

y=F(x)+Wx

out += identity


if self.downsample is not None:
identity = self.downsample(x)
out += identity


3、两种残差块设计：

basic block中包含两个卷积层，卷积核数量相同，卷积核均为3×3，输入输出均为64通道，可直接相加。该block主要使用在相对浅层网络，比如ResNet-34。
bottle neck的结构是前两组滤波核数量相同，第三层滤波核数量是前两组的4倍，第二层尺寸3×3，其余两层尺寸是1×1，主要目的就是为了降低参数的数目，第一个64通道数的1×1卷积把256维通道数（channel)降到64维通道，然后在最后通过一个256通道的1×1卷积恢复。


class BasicBlock(nn.Module):
expansion = 1

def __init__(
self,
inplanes,
planes,
stride=1,
downsample=None,
groups=1,
base_width=64,
dilation=1,
norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
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")

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):
identity = x

out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)

out = self.conv2(out)
out = self.bn2(out)

if self.downsample is not None:
identity = self.downsample(x)

out += identity
out = self.relu(out)

return out


class Bottleneck(nn.Module):
expansion = 4

def __init__(
self,
inplanes,
planes,
stride=1,
downsample=None,
groups=1,
base_width=64,
dilation=1,
norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups

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

def forward(self, x):
identity = x

out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)

out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)

out = self.conv3(out)
out = self.bn3(out)

if self.downsample is not None:
identity = self.downsample(x)

out += identity
out = self.relu(out)

return out


4、ResNet整体网络结构

import torch
import torch.nn as nn

__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']

model_urls = {
}

def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,

def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)

class BasicBlock(nn.Module):
expansion = 1

def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
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")

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):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)

out = self.conv2(out)
out = self.bn2(out)

if self.downsample is not None:
identity = self.downsample(x)

out += identity
out = self.relu(out)

return out

class Bottleneck(nn.Module):

expansion = 4

def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups

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

def forward(self, x):
identity = x

out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)

out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)

out = self.conv3(out)
out = self.bn3(out)

if self.downsample is not None:
identity = self.downsample(x)

out += identity
out = self.relu(out)

return out

class ResNet(nn.Module):

def __init__(self, block, layers, num_classes=6, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer

self.inplanes = 64
self.dilation = 1
if replace_stride_with_dilation is None:

replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(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.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
dilate=replace_stride_with_dilation[0])
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
dilate=replace_stride_with_dilation[1])
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
dilate=replace_stride_with_dilation[2])
self.fc = nn.Linear(512 * block.expansion, num_classes)

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)

if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)

def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)

layers = []
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion

for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))

return nn.Sequential(*layers)

def _forward_impl(self, x):

x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)

x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)

x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)

return x

def forward(self, x):
return self._forward_impl(x)

def _resnet(arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(block, layers, **kwargs)

return model

def resnet18(pretrained=False, progress=True, **kwargs):
r"""ResNet-18 model from
"Deep Residual Learning for Image Recognition" _
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
**kwargs)

def resnet34(pretrained=False, progress=True, **kwargs):
r"""ResNet-34 model from
"Deep Residual Learning for Image Recognition" _
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
**kwargs)

def resnet50(pretrained=False, progress=True, **kwargs):
r"""ResNet-50 model from
"Deep Residual Learning for Image Recognition" _
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
**kwargs)

def resnet101(pretrained=False, progress=True, **kwargs):
r"""ResNet-101 model from
"Deep Residual Learning for Image Recognition" _
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
**kwargs)

def resnet152(pretrained=False, progress=True, **kwargs):
r"""ResNet-152 model from
"Deep Residual Learning for Image Recognition" _
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
**kwargs)

def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-50 32x4d model from
"Aggregated Residual Transformation for Deep Neural Networks" _
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['groups'] = 32
kwargs['width_per_group'] = 4
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
pretrained, progress, **kwargs)

def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-101 32x8d model from
"Aggregated Residual Transformation for Deep Neural Networks" _
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['groups'] = 32
kwargs['width_per_group'] = 8
return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
pretrained, progress, **kwargs)

def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-50-2 model from
"Wide Residual Networks" _
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
channels, and in Wide ResNet-50-2 has 2048-1024-2048.

Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['width_per_group'] = 64 * 2
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
pretrained, progress, **kwargs)

def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-101-2 model from
"Wide Residual Networks" _
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
channels, and in Wide ResNet-50-2 has 2048-1024-2048.

Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['width_per_group'] = 64 * 2
return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
pretrained, progress, **kwargs)

def test():
net = resnet34()
img = torch.randn(1, 3, 224, 224)
y = net(img)
print(y.size())

if __name__ == '__main__':
test()



Original: https://blog.csdn.net/retainenergy/article/details/123554292
Author: 下雨天不下雨
Title: ResNet代码实现及原理——学习记录

(0)

### 大家都在看

• #### 基于 Anaconda 的 Tensorflow 环境配置

一、什么是 Anaconda? Anaconda (官方网站) 是可以便携获取包且对包能够进行管理, 同时对环境可以统一进行管理的发行版本. Anaconda包含了 conda、P…

人工智能 2023年5月23日
0164
• #### 目标检测的Tricks | 【Trick7】数据增强——Mosaic（马赛克）

如有错误，恳请指出。 在之前的博客中也有提及到mosaic这种数据增强，然后用这篇博客来进行详细介绍。 文章目录 1. Mosaic概要介绍 2. Mosaic算法步骤 3. Mo…

人工智能 2023年6月17日
0108
• #### WSL2，NCCL报错RuntimeError: NCCL Error 2: unhandled system error

在WSL2上使用pytorch1.7.1，无法进行多显卡分布式训练，提示”RuntimeError: NCCL Error 2: unhandled system er…

人工智能 2023年7月23日
096
• #### 音乐音频 | 语音识别与音乐流派分类

文章目录 语音识别步骤 一、用SVM做音乐分类应用实例 * 1、数据集：EchoNest。 2、代码： – ①数据归一化。沿着最大方差轴旋转数据，确定数据的每个特征 对…

人工智能 2023年5月25日
0151
• #### 使用C语言实现矩阵转置（稀疏矩阵）

目录 1.转置矩阵（普通矩阵） 2.转置矩阵（稀疏矩阵） （1）稀疏矩阵 （2）稀疏矩阵的压缩存储方式 （3）理论运算方法 1.转置矩阵（普通矩阵） 矩阵的转置：根据主对角元素作为…

人工智能 2023年7月4日
0123
• #### OpenCV 编译安装教程

原创：PinkFeet 本文全程科学上网。 传统视觉算法时代，GPU 的作用没有现在明显。近些年来，随着深度学习方法崛起，卷积神经网络模块被嵌入到了 OpenCV，加上特定任务场景…

人工智能 2023年7月19日
0119
• #### python利用图像处理方法 实现多目标检测与裁剪（opencv）

图像处理方法实现多目标检测与裁剪 简述 * 1.批量resize – 1）效果 2）原理 3）代码分析 2.找出所有目标轮廓（定位） – 1）效果 2）原理…

人工智能 2023年6月19日
0157
• #### matlab coder为用于深度学习神经网络的代码生成安装MKL-DNN并配置环境

但是因为烟盒外包装缺陷检测运用到了神经网络，需要额外配置mkldnn，不然无法生成代码，因此花了一些时间和精力安装和配置mkldnn的环境，下面记录一下： Windows MKL-…

人工智能 2023年7月13日
0142
• #### 【简述】【图】P类问题、NP类问题、NP完全问题和NP难问题

P类问题（Polynomial Problem） P类问题是指 一类能够用确定性算法在多项式时间内求解的判定问题。其实，在非正式的定义中，我们可以把那些在多项式时间内求解的问题当作…

人工智能 2023年6月24日
0168
• #### anaconda安装tensorflow

萌新入门之tensorflow安装 anaconda环境下安装tensorflow * 管理员运行Anaconda Prompt 安装keras 安装pandas 安装tensor…

人工智能 2023年5月23日
0145
• #### 将conda 虚拟环境添加到 Jupyter lab内核

在conda中有多个虚拟环境，将其添加到jupyter lab中，便于在jupyter lab中切换环境。 首先在conda中创建一个tensorflow的虚拟环境(一定需要指定p…

人工智能 2023年5月25日
0129
• #### 使用OpenCV如何确定一个对象的方向

在本教程中，我们将构建一个程序，该程序可以使用流行的计算机视觉库 OpenCV 确定对象的方向（即以度为单位的旋转角度）。 最常见的现实世界用例之一是当您想要开发机械臂的取放系统时…

人工智能 2023年6月18日
0134
• #### DataFrame多表合并拼接函数concat、merge参数详解+代码操作展示

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

人工智能 2023年7月7日
0112
• #### neo4j 知识图谱_GitHub：如何构建一个股票市场知识图谱？（附代码&链接）

来源：专知 本文约 2600 字，建议阅读 5 分钟。 如何利用网络上的公开数据构建一个自己的股票证券知识图谱呢？ [ 导读 ]你不理财财不理你，理财是大家早就达成共识的事情。作为…

人工智能 2023年6月1日
0116
• #### 语音处理/语音识别基础（二）- 声音的存储

本文总结了声音的存储，并回答了以下几个问题。 [En] This paper summarizes the storage of sound and answers the fol…

人工智能 2023年5月25日
089
• #### 海康VisionMaster配合机械手九点标定

文章目录 一、图像源 二、标定板标定 三、N点标定 四、标定转换 总结 一、图像源 添加图像源，在图像源里添加标定板图片 ; 二、标定板标定 拖入标定板标定右键点击标定板标定，在运…

人工智能 2023年6月24日
0540