殘差網絡---ResNet


 目錄

     一、殘差塊(Residual Block)

  二、 殘差網絡為什么有用

  三、ResNet網絡結構

  四、代碼實現

———————————————————————————————————————————————————————————————————————————————

       最近用到了ResNet殘差網絡,查看了原文和一些資料,在網易雲課堂上學習了吳恩達老師介紹的殘差網絡,這里對學習的內容做一個簡單的總結。我們都知道網絡的寬度和深度可以很好的提高網絡的性能,深的網絡一般都比淺的的網絡效果好,但訓練一個很深的網絡是非常困難的,一方面是網絡越深越容易出現梯度消失和梯度爆炸問題, 然而這個問題通過BN層和ReLU激活函數等方法在很大程度上已經得到解決;另一方面當網絡層數達到一定的數目以后,網絡的性能就會趨於飽和,再增加網絡層數的話性能就會開始退化,這說明當網絡變得很深以后,網絡就變得難以訓練了。ResNet是2015年由何愷明等提出來的,曾在ImageNet中斬獲圖像分類、檢測、定位三項的冠軍,ResNet的提出很大程度上解決了網絡退化問題(吳恩達老師解釋的是梯度消失和爆炸問題)。

一、殘差塊(Residual Block)

      這里吳恩達老師課程中對殘差塊的介紹比較好理解,以一個兩層神經網絡為例,普通網絡輸入$ a^{[l]} $ 首先經過線性變換生成$ z^{[l+1]} $,然后通過ReLU激活層輸出$ a^{[l+1]} $ ,同樣再經過一個線性變換生成$ z^{[l+2]} $,最后通過ReLU生成$ a^{[l+2]} $,最終$$ a^{[l+2]} = g(z^{[l+2]}). $$

      殘差網絡中直接將$ a{[l]} $連接到第二個線性變換和第二個ReLU激活層之間,形成一條更便捷的路徑(short cut),此時$$ a^{[l+2]} = g(z^{[l+2]}). $$變為$$ a^{[l+2]} = g(z^{[l+2]} + a^{[l]}). $$,也就是加上$ a^{[l]} $后形成了一個殘差塊

 

二、殘差網絡為什么有用?

  • 前向

  假設輸入$ x $通過一個很深的網絡后通過ReLU激活函數輸出為$a^{[l]}$,根據ReLU的特性此時$a \geq 0$,再其后面再接一個兩層的殘差塊輸出$a^{[l+2]}$,則$a^{[l+2]}$可以表示為$$ a^{[l+2]} = g(w^{[l+2]}a^{[l+1]} + b^{[l+2]} + a^{[l]}).$$

當$w^{[l+2]}$和偏置$w^{[l+2]}$都為0時,$$ a^{[l+2]} = g(a^{[l]})=a^{[l]}.$$,這說明殘差塊學習這個恆等變換並不難,另外如果中間這兩層學習到了一些其他有用的特征信息的話,它可能比學習恆等變換的效果更好,但是如果不加入殘差塊的話隨着網絡的不斷加深,學習一個恆等變換的參數都可能變得很難,因此殘差網絡能在不減慢學習效率(恆等變換)的情況下還有可能提高模型的性能

 

  原文中如下圖所示,設$ x $ 為淺層輸出,$ H(x) $為深層輸出,$ F(x) $為中間層結果,當$ x $ 表示的特征已經達到一個很好的程度時,中間層繼續學習會導致損失增大,$ F(x) $就會慢慢趨近於0,$ x $將從short cut路徑繼續往下傳播,這樣就實現了當淺層特征很好時,后面的深層網絡能達到一個恆等變換的效果。

  • 反向傳播

        一方面是殘差塊將輸出$ y = H(x) $ 分成了 $ F(x) + x $,變換后$ F(x) = H(x) - x$,即從原來學習一個$ x $到$ y $的映射變為學習 $ y $與$ x $ 之間的差值,這樣學習任務變得更簡單。 另一方面因為前向過程中存在short cut路徑下的恆等映射,因此在反向傳播過程中也存在這樣一條捷徑,只需要通過一個ReLU函數就可以將梯度傳到上一個模塊

三、ResNet網絡結構

        ResNet就是用這種殘差塊來作為網絡的基本結構,在論文中,作者給出了不同層數的ResNet網絡,包括18層、34層、50層、101層和152層,50層及以上的稱為深度殘差網絡,它們網絡結構如下圖所示。深度殘差網絡和淺層殘差網絡的主要區別在於基本結構由原來的殘差塊(Residual Block)變為了瓶頸殘差塊(Residual Bottleneck)瓶頸殘差塊輸出通道數為輸入的四倍,而殘差塊輸入和輸出通道數相等,以50層的殘差網絡為例,在conv2_x層中包括了3個瓶頸殘差塊,第一層和最后一層的通道數相差4倍, 由原來的64變為了256。

 

四、代碼實現

from __future__ import print_function, division, absolute_import
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo


__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',
}


def conv3x3(in_planes, out_planes, stride=1):
    "3x3 convolution with padding"
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=True)


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 Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=True)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=True)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=True)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        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

from torch.legacy import nn as nnl

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=True)
        #self.conv1 = nnl.SpatialConvolution(3, 64, 7, 7, 2, 2, 3, 3)
        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)
        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=True),
                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)
        self.conv1_input = x.clone()
        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):
    """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

  

參考連接

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM