Resnet代码实现+为什么使用全局平均池化

1.ResNet直接使用stride=2的卷积做下采样,并且用global average pool层替换了全连接层。

GAP的真正意义是:对整个网路在结构上做正则化防止过拟合。但是值得我们注意的是,使用gap可能会造成收敛速度减慢。用一个GAP将N个feature map降维成1*N大小的feature map,再用class个1*1卷积核将1*N的feature map卷成1*class的向量。

①摘取重点于:为什么使用全局平均池化。

在卷积神经网络的初期,卷积层通过池化层(一般是MaxPooling)后总是要一个或n个全连接层,全连接网络可以使feature map的维度减少,进而输入到softmax分类。其特征就是全连接层的参数超多,模型本身非常臃肿,又会造成过拟合。(现在已经很少大量使用fc层),用pooling来代替全连接。就解决了之前的问题:要不要在fc层使用dropout。使用AVP就不要了。

(作者自己思考的部分,不知对错)全局平均池化层代替全连接层虽然有好处,但是不利于迁移学习。因为参数较为“固化”在卷积的诸层网络中。增加新的分类,那就意味着相当数量的卷积特征要做调整。而全连接层模型则可以更好的迁移学习,因为它的参数很大一部分调整在全连接层,迁移的时候卷积层可能也会调整,但是相对来讲要小的多了。

再对比:论文R-FCN(全卷积+位置敏感型“Score Map”) (目标检测)(two-stage)(深度学习)(NIPS 2016)中的Position-sensitive score map

②小例子1  ③④

2.ResNet的一个重要设计原则是:当feature map大小降低一半时,feature map的数量增加一倍,这保持了网络层的复杂度。

那么我是否也要一致呢?

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

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

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

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)
        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.AvgPool2d(7, stride=1)
        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

def resnet18(pretrained=False, **kwargs):
  trained (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

 

你可能感兴趣的:(姿态估计逐步,深度学习)