神经网络 || 注意力机制的Pytorch代码实现

本文介绍了注意力机制在计算机视觉中的应用,重点讲解了SeNet(Squeeze-and-Excitation Networks)模型,该模型在2017年ImageNet比赛中夺冠。SeNet通过全局平均池化和通道注意力机制提升特征表达能力。文中提供了SeNet的Pytorch代码实现,展示了模型的前向传播过程。
摘要由CSDN通过智能技术生成

1 注意力机制的诞生

  1. 注意力机制,起初是作为自然语言处理中的工作为大家熟知,文章Attention is all you need详细介绍了“什么是注意力机制”,有兴趣的小伙伴可以下载原文看看。
    在这里插入图片描述
  2. SeNet-Squeeze-and-Excitation Networks是注意力机制在计算机视觉中应用的早期工作之一,并获得了2017年的imagenet,也就是最后一届imagenet比赛的冠军。
    在这里插入图片描述

2 介绍SeNet模型及Pytorch代码实现

import numpy as np
import torch
from torch import nn
from torch.nn import init


class SEAttention(nn.Module):

    def __init__(self, channel=512, reduction=16):
        super().__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)  # 全局均值池化  输出的是c×1×1
        self.fc = nn.Sequential(
            nn.Linear(channel, channel // reduction, bias=False),  # channel // reduction代表通道压缩
            nn.ReLU(inplace=True),
            nn.Linear(channel // reduction, channel, bias=False),  # 还原
            nn.Sigmoid()
        )

    def init_weights(self):
        for m in self.modules():
            print(m)  # 没运行到这儿
            if isinstance(m, nn.Conv2d):  # 判断类型函数——:m是nn.Conv2d类吗?
                init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                init.constant_(m.weight, 1)
                init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                init.normal_(m.weight, std=0.001)
                if m.bias is not None:
                    init.constant_(m.bias, 0)

    def forward(self, x):
        b, c, _, _ = x.size()  # 50×512×7×7
        y = self.avg_pool(x).view(b, c)  # ① maxpool之后得:50×512×1×1 ② view形状得到50×512
        y = self.fc(y).view(b, c, 1, 1)  # 50×512×1×1
        return x * y.expand_as(x)  # 根据x.size来扩展y


if __name__ == '__main__':
    input = torch.randn(50, 512, 7, 7)
    se = SEAttention(channel=512, reduction=8)  # 实例化模型se
    output = se(input)
    print(output.shape)


  • 也有说SeNet的模型是这样的:(我觉得过于简单了)
class SELayer(nn.Module):
    def __init__(self, channel, reduction=16):
        super(SELayer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Linear(channel, channel // reduction, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channel // reduction, channel, bias=False),
            nn.Sigmoid()
        )

    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x).view(b, c)
        y = self.fc(y).view(b, c, 1, 1)
        return x * y.expand_as(x)

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值