深度学习网络——resnet

6 篇文章 1 订阅
4 篇文章 0 订阅

论文链接:https://arxiv.org/pdf/1512.03385.pdf
代码链接:https://pytorch.org/docs/stable/_modules/torchvision/models/resnet.html

导入包

导入需要使用的包,并声明可用的网络和预训练好的模型

# -*- coding:UTF-8 -*-

# import torch
# import torchvision
#
# net = torchvision.models.resnet18()
# print(net)

import torch.nn as nn
import torch.utils.model_zoo as model_zoo

# __all__ 用法:
# 1、模块中不使用__all__属性,则导入模块内的所有公有属性,方法和类。
# 2、模块中使用__all__属性,则表示只导入__all__中指定的属性,因此,使用__all__可以隐藏不想被import的默认值。
# 3、__all__变量是一个由string元素组成的list变量。
# 4、它定义了当我们使用 from <module> import * 导入某个模块的时候能导出的符号(这里代表变量,函数,类等)。
# 5、from <module> import * 默认的行为是从给定的命名空间导出所有的符号(当然下划线开头的变量,方法和类除外)。
# 6、需要注意的是 __all__ 只影响到了 from <module> import * 这种导入方式,
# 7、对于 from <module> import <member> 导入方式并没有影响,仍然可以从外部导入。
# 六种不同的网络架构
__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-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}

定义常用卷积

定义要使用到的1x1和3x3的卷积层

# 常见的 3x3 卷积
def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    # class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
    #     in_channels (int): 输入图片的通道数
    #     out_channels (int): 卷积产生的通道数
    #     kernel_size (int or tuple): 卷积内核的大小
    #     stride (int or tuple, optional): 卷积步长. Default: 1
    #     padding (int or tuple, optional): 添加到输入两侧的零填充. Default: 0
    #     dilation (int or tuple, optional): 卷积核元素之间的间距. Default: 1
    #     groups (int, optional): 从输入通道到输出通道的阻塞连接数. Default: 1
    #     bias (bool, optional): 如果 bias=True,添加偏置. Default: ``True``
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

# 常见的 1x1 卷积
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/34,比如:
在这里插入图片描述

# BasicBlock,基本的 residual block
class BasicBlock(nn.Module):
    # 每个 Residual Block 中的输出通道数相对于输入通道数的放大倍数,具体可查看论文中的图和表
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        # 二维卷积层
        self.conv1 = conv3x3(inplanes, planes, stride)
        # 批正则化,数据归一化处理,使得数据在进行 relu 之前不会因为数据过大而导致网络性能的不稳定
        # y = (x - mean[x]) * gamma / (sqrt([x]) + eps) + beta
        # class torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True)
        #     num_features: 来自期望输入的特征数,该期望输入的大小为'batch_size x num_features x height x width'
        #     eps: 为保证数值稳定性(分母不能趋近或取0),给分母加上的值。默认为1e-5。
        #     momentum: 动态均值和动态方差所使用的动量。默认为0.1。
        #     affine: 一个布尔值,当设为true,给该层添加可学习的仿射变换参数。
        #     Shape: - 输入:(N, C,H, W) - 输出:(N, C, H, W)(输入输出相同)
        self.bn1 = nn.BatchNorm2d(planes)
        # inplace 为 True,即为原地操作,将会改变输入的数据,否则不会改变原输入,只会产生新的输出
        # 计算结果不会有影响。利用in-place计算可以节省内(显)存,同时还可以省去反复申请和释放内存的时间。但是会对原变量覆盖,只要不带来错误就用。
        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):
        # 右侧曲线部分,identity mapping 指的就是本身的映射,也就是 x 自身
        identity = x

        # residual mapping,即残差映射部分
        # 第一层卷积
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        # 第二层卷积
        out = self.conv2(out)
        out = self.bn2(out)

        # 下采样
        # 若为空,即实线部分,跳跃连接为“实线”,指的是 identity mapping 和 residual mapping 通道数相同。
        # 若不为空,即虚线部分,跳跃连接为“虚线”,指的是两者通道数不同,需要使用1x1卷积调整通道维度,使其可以相加。
        # 即通道数相同直接相加,不同则需经过下采样后再相加
        if self.downsample is not None:
            identity = self.downsample(x)

        # identity mapping 部分与 residual mapping 相加
        out += identity
        # 经过 relu 后再输出
        out = self.relu(out)

        return out

三层残差块的实现

这个实现的是三层的残差块,用于 resnet50/101/152,比如:
在这里插入图片描述

# Bottleneck,针对深层网络提出的 block
class Bottleneck(nn.Module):
    # 输出通道数相对于输入通道数的放大倍数,具体可查看论文中的图和表
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = conv1x1(inplanes, planes)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = conv3x3(planes, planes, stride)
        self.bn2 = nn.BatchNorm2d(planes)
        # 第三层卷积输出层扩大了 expansion 倍
        self.conv3 = conv1x1(planes, planes * self.expansion)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        # 右侧曲线部分,identity mapping 指的就是本身的映射,也就是 x 自身
        identity = x

        # residual mapping,即残差映射部分
        # 第一层卷积
        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)

        # 下采样
        # 若为空,即实线部分,跳跃连接为“实线”,指的是 identity mapping 和 residual mapping 通道数相同。
        # 若不为空,即虚线部分,跳跃连接为“虚线”,指的是两者通道数不同,需要使用1x1卷积调整通道维度,使其可以相加。
        # 即通道数相同直接相加,不同则需经过下采样后再相加
        if self.downsample is not None:
            identity = self.downsample(x)

        # identity mapping 部分与 residual mapping 相加
        out += identity
        # 经过 relu 后再输出
        out = self.relu(out)

        return out

整个网络的实现

在这里插入图片描述

# ResNet 类根据列表大小来构建不同深度的 resnet 网络架构
# resnet一共有 5 个阶段
# 第一阶段是一个7x7的卷积,stride=2
# 第二阶段,经过池化层,得到的特征图大小变为原图的1/4。
# 第三阶段,使用_make_layer()函数用来产生 4 个 layer,即 4 个大块,可以根据输入的 layers 列表来创建小块
# 第四阶段,平均池化
# 第五阶段,1000-d 输出分类结果
class ResNet(nn.Module):
	# block:指明残差块是两层或三层
	# layers:指明每个卷积层需要的残差块数量
	# num_classes:指明分类数
	# zero_init_residual:是否初始化为0
    def __init__(self, block, layers, num_classes=1000, zero_init_residual=False):
        super(ResNet, self).__init__()
        # 输入层通道数
        self.inplanes = 64
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        # 输入层随层数逐渐翻倍
        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)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        # 各层权重初始化
        for m in self.modules():
            # 卷积层使用 kaiming 初始化
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            # 批正则化层使用常数初始化
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        # 零初始化每个剩余分支中的最后一个 BN
        # 以便残差分支以零开头,并且每个残差块的行为类似于标识。
        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)

    # 生成一个基本的大块,由多个基本的小块组成
    # _make_layer()函数用来产生 4 个 layer,可以根据输入的 layers 列表来创建网络。
    def _make_layer(self, block, planes, blocks, stride=1):
        # 默认不进行下采样
        downsample = None
        # 步长不为 1,或者虚线部分,需要经过 1x1 的卷积操作,使得 identity mapping 部分与 residual mapping 尺寸大小相同,能够相加
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                nn.BatchNorm2d(planes * block.expansion),
            )

        # 开始生成相同的小块
        # 层列表
        layers = []
        # 每个大块的第一个小块的输入与输出的通道数不同,需要下采样,即图中的虚线部分
        # 生成大块的第一块小块,输入为是上一个大块的输出
        # 比如 101-layer
        # 第一个大块的第一个小块输入为 64,且所有第一个大块都是默认 64 层
        layers.append(block(self.inplanes, planes, stride, downsample))
        # 根据 layers 列表生成大块的余下小块,此时的小块的输入与输出通道数是相同的,即图中的实线部分,无需进行下采样了
        # 接下来剩余要生成的小块的输入为上一个小块的输出
        self.inplanes = planes * block.expansion
        # 生成剩余相同的小块
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        # 第一阶段,7x7 卷积
        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 网络。
在这里插入图片描述

# 根据论文中的列表指定大块中的小块数量,从而生成多种不同的 resnet 网络
def resnet18(pretrained=False, **kwargs):
    """Constructs a ResNet-18 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
    return model


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

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


def resnet50(pretrained=False, **kwargs):
    """Constructs a ResNet-50 model.

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


def resnet101(pretrained=False, **kwargs):
    """Constructs a ResNet-101 model.

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


def resnet152(pretrained=False, **kwargs):
    """Constructs a ResNet-152 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
    return model


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值