欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ResNet

程序员文章站 2022-03-16 12:41:57
...

ResNet意义

在深层网络能够收敛的前提下,随着网络深度的增加,正确率开始饱和甚至下降,称之为网络的退化(degradation)问题。而网络退化的根本原因是优化问题。 因此为了解决优化的难题,提出了残差网络ResNet。其中ResNet提出了两种mapping:一是identity mapping,指的就是图中”弯曲线”,另一种residual mapping,指的就是除了”弯曲线“那部分,所以最后的输出是

ResNet
identity mapping顾名思义,就是指本身,也就是公式中的xx,而residual mapping指的是“差”,也就是y−xy−x,所以残差指的就是F(x)F(x)部分。

ResNet

网络结构

ResNet
上图说明:

  1. 图左为基本residual block,residual mapping为两个64通道的3x3卷积,输入输出均为64通道,可直接相加。该block主要使用在相对浅层网络,比如ResNet-34;

  2. 图右为针对深层网络提出的block,称为“bottleneck” block,主要目的就是为了降维。首先通过一个1x1卷积将256维通道(channel)降到64通道,最后通过一个256通道的1x1卷积恢复。

代码实现

class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=1000):
        self.inplanes = 64
        super(ResNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)#7x7,64
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)#maxpool
        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.AvgPool2d(7, stride=1)#average pool
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        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))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        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))
        self.inplanes = planes * 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介绍
ResNet解析-详细精华版
ResNet理论基础与具体实现(详细教程)