Skip to content

ResNet 残差网络实现与变体

ResNet 通过残差连接解决了深层网络的梯度消失问题,是深度学习中最具影响力的架构之一。

ResNet 架构

残差连接

python
class BasicBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, 3, stride, 1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.shortcut = nn.Sequential()
        if stride != 1 or in_channels != out_channels:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channels, out_channels, 1, stride, bias=False),
                nn.BatchNorm2d(out_channels)
            )
    
    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)  # 残差连接
        return F.relu(out)

残差连接的意义

残差连接使得梯度可以"跳跃"传播,解决了深层网络梯度消失的问题。这看似简单的加法操作使网络深度从几十层扩展到了上千层。

相关资源

最近更新