首页 > 其他分享 >ResNet代码精读

ResNet代码精读

时间:2024-05-02 12:11:22浏览次数:13  
标签:精读 nn 代码 ResNet stride block self channel out

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_channel, out_channel, stride=1, downsample=None, **kwargs):  # 虚线对应的 downsample
        super(BasicBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
                               kernel_size=3, stride=stride, padding=1, bias=False) # 有BN层不需要偏置 ,这里的stride需要根据传进来的值对矩阵改变宽高
        self.bn1 = nn.BatchNorm2d(out_channel)
        self.relu = nn.ReLU()
        self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel, # 第一个卷积已经改变宽高
                               kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_channel)
        self.downsample = downsample

    def forward(self, x):
        identity = x  # 分支线上的
        if self.downsample is not None:
            identity = self.downsample(x)

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

        out = self.conv2(out)
        out = self.bn2(out) # 先加上捷径分支,再relu激活

        out += identity  # 加上捷径的再输出
        out = self.relu(out)

        return out

上面定义了一个两层的卷积层,论文中有用到过。

class Bottleneck(nn.Module):
    """
    注意:原论文中,在虚线残差结构的主分支上,第一个1x1卷积层的步距是2,第二个3x3卷积层步距是1。
    但在pytorch官方实现过程中是第一个1x1卷积层的步距是1,第二个3x3卷积层步距是2,
    这么做的好处是能够在top1上提升大概0.5%的准确率。
    可参考Resnet v1.5 https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch
    """
    expansion = 4

    def __init__(self, in_channel, out_channel, stride=1, downsample=None,
                 groups=1, width_per_group=64):
        super(Bottleneck, self).__init__()

        width = int(out_channel * (width_per_group / 64.)) * groups

        self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=width,           # 这里的out_channel是第一层和第二层的输出矩阵深度
                               kernel_size=1, stride=1, bias=False)  # squeeze channels # 第二层的stride根据传入的来判断
        self.bn1 = nn.BatchNorm2d(width)
        # -----------------------------------------
        self.conv2 = nn.Conv2d(in_channels=width, out_channels=width, groups=groups,
                               kernel_size=3, stride=stride, bias=False, padding=1) # stride是为了调整矩阵的宽高
        self.bn2 = nn.BatchNorm2d(width)
        # -----------------------------------------
        self.conv3 = nn.Conv2d(in_channels=width, out_channels=out_channel*self.expansion,
                               kernel_size=1, stride=1, bias=False)  # unsqueeze channels
        self.bn3 = nn.BatchNorm2d(out_channel*self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample

    def forward(self, x):
        identity = x
        if self.downsample is not None:
            identity = self.downsample(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)

        out += identity  #先加上再激活
        out = self.relu(out)

        return out


这个残差块和第一个残差块我觉得唯一的区别就是这个残差块多了一层。
这里提一下一直以来都比较困惑的一个点:虚线残差块有两个作用,一个是改变矩阵深度,如resnet50,101,152的conv_2x的第一层,都是改变输入矩阵的深度,而不改变输入矩阵的宽高。因为输入输出矩阵的宽高是一致的。而且虚线残差块仅出现在每个conv_··x的第一层,因为经过第一层之后,矩阵的深度和宽高都被调整为对应的输出矩阵的宽高,所以后面的都是实线残差结构。这也就是为什么下面的for循环可以直接将剩下的残差块压入。

class ResNet(nn.Module):

    def __init__(self,
                 block,   # 根据模型选择bottleneck还是basicmodule
                 blocks_num,
                 num_classes=1000,
                 include_top=True,
                 groups=1,
                 width_per_group=64):
        super(ResNet, self).__init__()
        self.include_top = include_top
        self.in_channel = 64

        self.groups = groups
        self.width_per_group = width_per_group

        self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7, stride=2,
                               padding=3, bias=False)  # 设置padding是为了高和宽缩减为原来的一半
        self.bn1 = nn.BatchNorm2d(self.in_channel)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)  # 设置padding理由同上
        self.layer1 = self._make_layer(block, 64, blocks_num[0])
        self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
        self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
        self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
        if self.include_top:
            self.avgpool = nn.AdaptiveAvgPool2d((1, 1))  # output size = (1, 1) 自适应展平为长宽(1*1)的矩阵
            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')

    def _make_layer(self, block, channel, block_num, stride=1): # channel都是第一层的深度,但是50层和以上都有4倍的最后一层
        downsample = None
        if stride != 1 or self.in_channel != channel * block.expansion: # 第二个条件是因为resnet50,101,152的conv_2x虽然stride是1(输入输出矩阵同宽高),但是深度不同,所以第一层也得 
                                                                        #  加上虚线残差结构
            downsample = nn.Sequential(
                nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=1, stride=stride, bias=False), # 对于layer1来说,因为池化过后的长宽和输出的长宽一致,所以也就虚线stride就是1,而对于下面的三层,stride都是2才能改变矩阵的长宽
                nn.BatchNorm2d(channel * block.expansion))

        layers = []
        layers.append(block(self.in_channel,
                            channel,
                            downsample=downsample,
                            stride=stride,
                            groups=self.groups,
                            width_per_group=self.width_per_group))
        self.in_channel = channel * block.expansion    #这里的in_channel是个成员数据,对于每个残差块,输出矩阵深度不一致。对于下面的循环,输入输出矩阵深度应该一致(实线残差结构)。

        for _ in range(1, block_num):  # 这里剩下的都是实线残差结构了,因此直接加上即可
            layers.append(block(self.in_channel,
                                channel,
                                groups=self.groups,
                                width_per_group=self.width_per_group))

        return nn.Sequential(*layers)

    def forward(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)

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

        return x

给个简单的模型构建传参的例子

def resnet50(num_classes=1000, include_top=True):
    # https://download.pytorch.org/models/resnet50-19c8e357.pth
    return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)


根据block判断选择几层的残差结构

标签:精读,nn,代码,ResNet,stride,block,self,channel,out
From: https://www.cnblogs.com/wl511/p/18170075

相关文章

  • Sensor代码框架
    #include<stdio.h>//定义一个枚举类型来表示光电开关的状态typedefenum{SWITCH_OPEN,SWITCH_CLOSED}SwitchState;//定义一个结构体来记录光电开关传感器的状态typedefstruct{SwitchStatecurrentState;//当前状态SwitchStatelastState;......
  • SAP 事务代码CU71报错 - 特性LOBM_LWEDT不存在 -
    SAP事务代码CU71报错-特性LOBM_LWEDT不存在 -  1,在事务代码CU71或者如下配置里。    定义排序规则,   试图使用SAP标准特性LOBM_LWEDT, SAP报错说:’特性LOBM_LWEDT不存在’。这是SAP系统上的一个标准的特性,怎么能不存在SAP系统上呢?  2,解决方法:......
  • 五个重要的编程原则让你写出高质量代码
    Therearefiveprinciplesthatyoushouldconform.1:Singleresponsibilityprinciple.各司其职,一个对象不要封装的太复杂,设计的时候要考虑好哪些功能属于这个对象,不要将一个对象弄得太复杂,当你意识到一个对象承担了太多责任的时候,尝试分开它,减小耦合度,以便维护。2:Open-Clo......
  • 代码
     #-*-coding:utf-8-*-"""@author:14931@file:deletlie.py@time:2024/05/01@desc:"""importnumpyasnpimportpandasaspdfile_path='D:/NM004-20230627224400-20230627224859-0.txt'#读整个txt文件读取到单个字符串wit......
  • html,js代码编译,加密,代码一键打包软件,HTML转exe程序
    个人软件注意杀毒软件会报毒,,放行便可小尘web打包程序可以将整个web工程项目打包成一个exe程序运行不是打包浏览器内核应用,是代码打包软件,打包后和原来一样放在nginx类软件里运行下载地址https://download.csdn.net/download/rllmqe/88789653链接:https://pan.baidu.com/s/1HTql......
  • SpringBoot camunda常用代码
    图例: 1:默认排他网关,表达式Type:expression:${number%200==0}2:servicetask(系统自动执行用的最多):常用Delegateexpression${testGateWay}举例:@Component("testGateWay")publicclassTestGateWayimplementsJavaDelegate{@Overridepublicvoidexecute......
  • 猿代码 Linux基础操作
    Linux基础操作常用操作命令--help#获取/home/user/soft/bin/myexe#执行第三方程序./myexe#当前目录下执行第三方程序whoami#用户名称hostname#服务器名称当前所使用的节点lscpu#查看cpu信息free-h#查看内存信息top#查看哪些进程在运行lsls-l#详细列表显示......
  • android 反编译APK取源代码。
    坑,自己写的AndroidAPK程序,发现线上版本是1.9.4,本地的代码版本却是1.9.1。不知道到底怎么回事,svn里面也没有日志记录。。。。。只能从线上apk反编译来看看了,幸好这个升级日志里面,更新内容很少。。。。。真的是诡异 反编译过程如下,其他地方转来的,仅做记录用,方便自己以后按这......
  • 7. 中间代码 | 2.抽象语句 --> 树中间语言
    1.   表达式 A_exp->T_exp,T_stm structTr_exp_{//Tr_ex表达式,Tr_nx无结果语句,Tr_cx每件语句enum{Tr_ex,Tr_nx,Tr_cx}kind;union{T_expexp,T_stmnx,structCxcx;}u;};structCx{patchListtrues;patchListfalses;T_stm......
  • 通义灵码实战系列:一个新项目如何快速启动,如何维护遗留系统代码库?
    作者:别象进入2024年,AI热度持续上升,翻阅科技区的文章,AI可谓是军书十二卷,卷卷有爷名。而麦肯锡最近的研究报告显示,软件工程是AI影响最大的领域之一,AI已经成为了软件工程的必选项,也有研究称开发者每天的事务性工作可能占到了七成左右,比如单侧编写等,而这部分恰好是AI所擅长......