美文网首页机器学习&神经网络
resnet18 50网络结构以及pytorch实现代码

resnet18 50网络结构以及pytorch实现代码

作者: zyyupup | 来源:发表于2019-05-31 17:34 被阅读0次

    1 resnet简介

      关于resnet,网上有大量的文章讲解其原理和思路,简单来说,resnet巧妙地利用了shortcut连接,解决了深度网络中模型退化的问题。

    2 论文中的结构如下

    网络结构.png

    2.1 参考pytorch中的实现,自己画了一个网络图,包含了每一层的参数和输出

    resnet18&resnet50.jpg

    PS:经评论区@字里行间_yan提醒,原始图片中部分描述有歧义,已更正。一般来说,特征图的尺寸变化应表述为上采样和下采样,通道数的变化才是升维和降维。


    2020/4/17更新
    本来自己随便写写,感觉看到这篇文章的人挺多,回来填坑

    • 增加了pytorch中的代码解读。
    • 修复了图中参数k的标识错误(1x1卷积 k=1)
    • 新增SVG文件下载地址链接(虽然文件简单,下载后还请在本文点个赞鼓励下): 链接: 链接: https://pan.baidu.com/s/183ReRQMJXt2yUkhExnezBA 提取码: kmf2

    3 pytorch中的resnet

    3.1 代码文件

    完整代码文件可在pytorch官方文档查到,地址https://pytorch.org/docs/stable/_modules/torchvision/models/resnet.html#resnet18
    顺便说一句,torchvision里面实现了大部分经典的网络,分类分割检测都有,还包含了常用的一些数据库加载等,对于刚入门的同学来说会省很多事。

    3.2 代码阅读

    个人习惯从模型调用开始看,首先看调用

    def _resnet(arch, block, layers, pretrained, progress, **kwargs):
        model = ResNet(block, layers, **kwargs)
        if pretrained:
            state_dict = load_state_dict_from_url(model_urls[arch],
                                                  progress=progress)
            model.load_state_dict(state_dict)
        return model
    def resnet50(pretrained=False, progress=True, **kwargs):
        return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
                       **kwargs)
    

      可以看到resnet至少需要两个显示的参数,分别是block和layers。这里的block就是论文里提到的resnet18和resnet50中应用的两种不同结构。layers就是网络层数,也就是每个block的个数,在前文图中也有体现。
      然后看网络结构,代码略长,为了阅读体验就直接截取了重要部分以及在代码中注释,建议配合完整代码阅读。

    class ResNet(nn.Module):
        def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
                     groups=1, width_per_group=64, replace_stride_with_dilation=None,
                     norm_layer=None):
            super(ResNet, self).__init__()
            #参数比调用多几个,模型相较于最初发文章的时候有过更新
            #block: basicblock或者bottleneck,后续会提到
            #layers:每个block的个数,如resnet50, layers=[3,4,6,3]
            #num_classes: 数据库类别数量
            #zero_init_residual:其他论文中提到的一点小trick,残差参数为0
            #groups:卷积层分组,应该是为了resnext扩展
            #width_per_group:同上,此外还可以是wideresnet扩展
            #replace_stride_with_dilation:空洞卷积,非原论文内容
            #norm_layer:原论文用BN,此处设为可自定义
           
             # 中间部分代码省略,只看模型搭建部分
            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.avgpool = nn.AdaptiveAvgPool2d((1, 1))
            self.fc = nn.Linear(512 * block.expansion, num_classes)
    
        #中间部分代码省略
        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 = []
            #每一个self.layer的第一层需要调用downsample,所以单独写,跟下面range中的1 相对应
            #block的定义看下文
            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):
            #前向传播
            # See note [TorchScript super()]
            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
    

    然后是论文中的block

    def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
        """3x3 convolution with padding"""
        return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                         padding=dilation, groups=groups, bias=False, dilation=dilation)
    
    
    def conv1x1(in_planes, out_planes, stride=1):
        """1x1 convolution"""
        return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
    
    #用在resnet18中的结构,也就是两个3x3卷积
    class BasicBlock(nn.Module):
        expansion = 1
        __constants__ = ['downsample']
        #inplanes:输入通道数
        #planes:输出通道数
        #base_width,dilation,norm_layer不在本文讨论范围
        def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                     base_width=64, dilation=1, norm_layer=None):
            super(BasicBlock, self).__init__()
            #中间部分省略
            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#论文中最核心的部分,resnet的简洁和优美的体现
            out = self.relu(out)
    
            return out
    
    #bottleneck是应用在resnet50及其以上的结构,主要是1x1,3x3,1x1
    class Bottleneck(nn.Module):
        expansion = 4
        __constants__ = ['downsample']
    
        def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                     base_width=64, dilation=1, norm_layer=None):
            super(Bottleneck, self).__init__()
            #中间省略
            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
        #同basicblock
        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
    

       我已经很熟悉resnet,不知道在哪些地方存在阅读问题,所以只在代码中把一些关键的地方注释了,代码可以跟我画的那个图结合起来看,更容易理解。
      如有问题欢迎留言,我看到就会回复。

    相关文章

      网友评论

        本文标题:resnet18 50网络结构以及pytorch实现代码

        本文链接:https://www.haomeiwen.com/subject/misgtctx.html