注意力機制論文:Squeeze-and-Excitation Networks及其PyTorch實現

Squeeze-and-Excitation Networks
PDF: https://arxiv.org/pdf/1709.01507.pdf
PyTorch代碼: https://github.com/shanglianlm0525/PyTorch-Networks

Squeeze-and-Excitation Networks(SENet)是由自動駕駛公司Momenta在2017年公佈的一種全新的圖像識別結構,它通過對特徵通道間的相關性進行建模,把重要的特徵進行強化來提升準確率。這個結構是2017 ILSVR競賽的冠軍,top5的錯誤率達到了2.251%,比2016年的第一名還要低25%,可謂提升巨大。

1 概述

  • SENet通過學習channel之間的相關性,篩選出了針對通道的注意力,稍微增加了一點計算量,但是效果提升較明顯
  • Squeeze-and-Excitation(SE) block是一個子結構,可以有效地嵌到其他分類或檢測模型中。
  • SENet的核心思想在於通過網絡根據loss去學習feature map的特徵權重來使模型達到更好的結果
  • SE模塊本質上是一種attention機制

2 Squeeze-and-Excitation模塊

Squeeze 操作對 C x H x W 進行global average pooling,得到大小爲 C x 1 x 1 的特徵圖

Excitation 操作 使用一個全連接神經網絡,對Sequeeze之後的結果做一個非線性變換

Reweight 操作 使用Excitation 得到的結果作爲權重,乘到輸入特徵上
在這裏插入圖片描述

3 SE模塊應用舉例

SE-Inception 和 SE-ResNet
在這裏插入圖片描述

class SE_Module(nn.Module):
    def __init__(self, channel,ratio = 16):
        super(SE_Module, self).__init__()
        self.squeeze = nn.AdaptiveAvgPool2d(1)
        self.excitation = nn.Sequential(
                nn.Linear(in_features=channel, out_features=channel // ratio),
                nn.ReLU(inplace=True),
                nn.Linear(in_features=channel // ratio, out_features=channel),
                nn.Sigmoid()
            )
    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.squeeze(x).view(b, c)
        z = self.excitation(y).view(b, c, 1, 1)
        return x * z.expand_as(x)

4 SENet

在這裏插入圖片描述

PyTorch代碼:

import torch
import torch.nn as nn
import torchvision


def Conv1(in_planes, places, stride=2):
    return nn.Sequential(
        nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),
        nn.BatchNorm2d(places),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
    )

class SE_Module(nn.Module):
    def __init__(self, channel,ratio = 16):
        super(SE_Module, self).__init__()
        self.squeeze = nn.AdaptiveAvgPool2d(1)
        self.excitation = nn.Sequential(
                nn.Linear(in_features=channel, out_features=channel // ratio),
                nn.ReLU(inplace=True),
                nn.Linear(in_features=channel // ratio, out_features=channel),
                nn.Sigmoid()
            )
    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.squeeze(x).view(b, c)
        z = self.excitation(y).view(b, c, 1, 1)
        return x * z.expand_as(x)


class SE_ResNetBlock(nn.Module):
    def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 4):
        super(SE_ResNetBlock,self).__init__()
        self.expansion = expansion
        self.downsampling = downsampling

        self.bottleneck = nn.Sequential(
            nn.Conv2d(in_channels=in_places,out_channels=places,kernel_size=1,stride=1, bias=False),
            nn.BatchNorm2d(places),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_channels=places, out_channels=places, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(places),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_channels=places, out_channels=places*self.expansion, kernel_size=1, stride=1, bias=False),
            nn.BatchNorm2d(places*self.expansion),
        )

        if self.downsampling:
            self.downsample = nn.Sequential(
                nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(places*self.expansion)
            )
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        residual = x
        out = self.bottleneck(x)

        if self.downsampling:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)
        return out

class SE_ResNet(nn.Module):
    def __init__(self,blocks, num_classes=1000, expansion = 4):
        super(SE_ResNet,self).__init__()
        self.expansion = expansion

        self.conv1 = Conv1(in_planes = 3, places= 64)

        self.layer1 = self.make_layer(in_places = 64, places= 64, block=blocks[0], stride=1)
        self.layer2 = self.make_layer(in_places = 256,places=128, block=blocks[1], stride=2)
        self.layer3 = self.make_layer(in_places=512,places=256, block=blocks[2], stride=2)
        self.layer4 = self.make_layer(in_places=1024,places=512, block=blocks[3], stride=2)

        self.avgpool = nn.AvgPool2d(7, stride=1)
        self.fc = nn.Linear(2048,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)

    def make_layer(self, in_places, places, block, stride):
        layers = []
        layers.append(SE_ResNetBlock(in_places, places,stride, downsampling =True))
        for i in range(1, block):
            layers.append(SE_ResNetBlock(places*self.expansion, places))

        return nn.Sequential(*layers)


    def forward(self, x):
        x = self.conv1(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 SE_ResNet50():
    return SE_ResNet([3, 4, 6, 3])

if __name__=='__main__':
    model = SE_ResNet50()
    print(model)

    input = torch.randn(1, 3, 224, 224)
    out = model(input)
    print(out.shape)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章