Pytorch:源码笔记 ResNet

本文深入探讨了PyTorch中ResNet34和ResNet50的网络结构,重点解析了BasicBlock和Bottleneck的设计原理。
摘要由CSDN通过智能技术生成

 源码:

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

# 由于ResNet中只有3*3和1*1两种卷积核,所以封装一下方便后面使用
def conv3x3(in_channels, out_channels, stride=1):
    return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1,bias=False)
def conv1x1(in_channels, out_channels, stride=1):
    return nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)

# 用于ResNet18 和 ResNet34
class BasicBlock(nn.Module):
    expansion = 1
    # in_channels表示block的输入特征通道数,expansion * out_channels表示block的输出特征通道数
    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(in_channels, out_channels, stride)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(out_channels, out_channels)
        self.bn2 = nn.BatchNorm2d(out_channels)
        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

# 用于ResNet50、ResNet101和ResNet152
class Bottleneck(nn.Module):
    expansion = 4
    # in_channels表示block的输入特征通道数,expansion * out_channels表示block的输出特征通道数
    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        # 调整通道数 : in_channels -> out_channels
        self.conv1 = conv1x1(in_channels, out_channels)
        self.bn1 = nn.BatchNorm2d(out_channels)
        # 调整分辨率
        self.conv2 = conv3x3(out_channels, out_channels, stride)
        self.bn2 = nn.BatchNorm2d(out_channels)
        # 调整通道数 : out_channels -> expansion * out_channels
        self.conv3 = conv1x1(out_channels, out_channels * self.expansion)
        self.bn3 = nn.BatchNorm2d(out_channels * self.expansion)
        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

class ResNet(nn.Module):
    '''
        which_block : 使用BasicBlock 还是 Bottleneck
        list_layers : layer[1-4]的 block个数,用来定义ResNet深度
        num_classes :分类数
    '''
    def __init__(self, which_block, list_layers, num_classes=1000):
        super(ResNet, self).__init__()
        self.in_channels = 64  # 每个layer的输入通道
        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(which_block, 64, list_layers[0])
        self.layer2 = self._make_layer(which_block, 128, list_layers[1], stride=2)
        self.layer3 = self._make_layer(which_block, 256, list_layers[2], stride=2)
        self.layer4 = self._make_layer(which_block, 512, list_layers[3], stride=2)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * which_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.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    # 把block组合成layer
    # 输出特征通道数 = out_channels * which_block.expansion
    def _make_layer(self, which_block, out_channels, num_blocks, stride=1):
        downsample = None

        # 如果[输入特征分辨率跟输出特征分辨率不同]或者[输入特征通道数跟输出特征通道数不同]
        if stride != 1 or self.in_channels != out_channels * which_block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.in_channels, out_channels * which_block.expansion, stride),
                nn.BatchNorm2d(out_channels * which_block.expansion),
            )

        layers = []
        # 每个layer的第一个block负责改变分辨率和通道数
        layers.append(which_block(self.in_channels, out_channels, stride, downsample))
        self.in_channels = out_channels * which_block.expansion
        # 每个layer的第二个block开始不改变输入特征的分辨率和通道数
        for _ in range(1, num_blocks):
            layers.append(which_block(self.in_channels, out_channels))
        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

model_urls = {
    'resnet18': 'https://download.pytorch.org/mod
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值