resnet系列模型

resnet50网络结构yuanma resnet50网络结构图简易_2d

                                                resnet系列结构图

resnet的网络构成都是1个卷积+4个残差+1个全连接网络。黄框为resnet50的结构,50 = 1+(3+4+6+3)*3+1,其中3、4、6、3的意思是有3个这样的残差块。。。

两种残差块

 

resnet50网络结构yuanma resnet50网络结构图简易_resnet50网络结构yuanma_02

        BasicBlock                                   BottleBlock

    残差块有2种,左侧的BasicBlock适用于较浅的resnet18及resnet34,右侧的Bottleneck适用于较深的resnet50及以上。

为什么要设计2种结构,我的理解:通过1*1减少通道数,从而减少参数量,节约显存,构建更深的网络。

    对图中的256、64不必太过在意,不是每层都是一样的,以系列图及代码为准。

    BasicBlock中的3*3都是下面这个

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

对BasicBlock,结构为:3*3卷积——块归一化——Relu激活——3*3卷积——块归一化——与输入相加(这一步可能涉及将输入下采样后相加)——Relu激活

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = 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:
            residual = self.downsample(x)

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

        return out

对BottleBlock,结构为:1*1卷积——块归一化——Relu激活——3*3卷积——块归一化——Relu激活——1*1卷积——块归一化——与输入相加(这一步可能涉及将输入下采样后相加)——Relu激活

在BottleBlock中两个1*1的卷积核都改变了输入输出通道数。

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        # 如:256->64
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)   # inplanes == 4*planes 见上图可知,输入通道数是输出通道数量的4倍
        self.bn1 = nn.BatchNorm2d(planes)
        # 如 64->64
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        # 如:64->256
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)   # 输出通道数是输入通道数量的4倍
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = 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:
            residual = self.downsample(x)

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

        return out

ResNet类

class ResNet(nn.Module):
  def __init__(self, block, layers, num_classes=1000):
    self.inplanes = 64   # 经过开始一个卷积块后,在4个块前,通道数由rgb3通道变为64
    super(ResNet, self).__init__()
    # 开始:1个卷积层
    self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                 bias=False) # resnet第一个卷积将输入3通道图像转化为64维 
    self.bn1 = nn.BatchNorm2d(64)
    self.relu = nn.ReLU(inplace=True)
    self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True)   # 减小特征图尺寸,112->56

    # 中间:4个块,每个块包含多层残差block
    # stride 只有第2、3、4块的第一个block才为2,通过卷积下采样,实现特征图更小,通道更多 
    self.layer1 = self._make_layer(block, 64, layers[0])
    self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
    self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
    self.layer4 = self._make_layer(block, 512, layers[3], stride=2)   

    # 最后:1个全连接层
    self.avgpool = nn.AvgPool2d(7)
    self.fc = nn.Linear(512 * block.expansion, num_classes)   # block.expansion为1、4,全连接层的输入为512、2048通道

    for m in self.modules():
      # 卷积层初始化
      if isinstance(m, nn.Conv2d):
        n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
        m.weight.data.normal_(0, math.sqrt(2. / n))
      # bn初始化 
      elif isinstance(m, nn.BatchNorm2d):
        m.weight.data.fill_(1)
        m.bias.data.zero_()

  def _make_layer(self, block, planes, blocks, stride=1):
    # block:指定basicblock或bottleblock
    # planes:block 第一个卷积的输出通道数
    # block:这个块有几个残差结构
    # stride:值为1或2,改变这个块第一个残差结构第一层的特征图尺寸

    downsample = None
    # stride != 1:第2、3、4个块
    # self.inplanes != planes * block.expansion:上层的输出不是第一个残差结构第一层的输出通道数的block.expansion倍,涵盖了所有使用了bottleblock的块,和resnet18、resnet34的2、3、4个块
    # 下采样是通过卷积实现的,目的是改变通道数量或通过stride改变尺寸,叫下采样不是特别恰当
    # resnet系列图中一共有4*5=20个块,只有resnet18和resnet34的第一个块(共2个)没做下采样,其他18个块都在第一个残差结构里做下采样了(即用了botttleblock的18、101、152系列,及18、34的2、3、4块)
    if stride != 1 or self.inplanes != planes * block.expansion:
      downsample = nn.Sequential(
        nn.Conv2d(self.inplanes, planes * block.expansion,
              kernel_size=1, stride=stride, bias=False),
        nn.BatchNorm2d(planes * block.expansion),
      )

    layers = []
    layers.append(block(self.inplanes, planes, stride, downsample))   # 所有块的第一层可能会涉及到下采样(除了2个不做下采样);2、3、4块的第一个残差结构stride为2,目的是改变特征图尺寸
    self.inplanes = planes * block.expansion   # 下个残差结构的输入通道数是上个结构第一层输出通道数的block.expansion倍,其实看系列图每个块中最后一个卷积结构就可以知道
    for i in range(1, blocks):
      layers.append(block(self.inplanes, planes))

    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)

    x = self.avgpool(x)
    x = x.view(x.size(0), -1)
    x = self.fc(x)

    return x

 

基于类及配置构建resnet网络

以两种Block为例说明

import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import torch


__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
           'resnet152']


model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3mb4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}


def resnet34(pretrained=False):
    """Constructs a ResNet-34 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3])
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
    return model


def resnet50(pretrained=False):
  """Constructs a ResNet-50 model.
  Args:
    pretrained (bool): If True, returns a model pre-trained on ImageNet
  """
  model = ResNet(Bottleneck, [3, 4, 6, 3])
  if pretrained:
    model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
  return model