计算机视觉之 SE 注意力模块

计算机视觉之 SE 注意力模块

一、简介

SEBlock 是一个自定义的神经网络模块,主要用于实现 Squeeze-and-Excitation(SE)注意力机制。SE 注意力机制通过全局平均池化和全连接层来重新校准通道的权重,从而增强模型的表达能力。

原论文:《Squeeze-and-Excitation Networks

二、语法和参数

语法
python 复制代码
class SEBlock(nn.Module):
    def __init__(self, in_channels, reduction=16):
        ...
    def forward(self, x):
        ...
参数
  • in_channels:输入特征的通道数。
  • reduction:通道缩减比例,默认为 16。

三、实例

3.1 初始化和前向传播
  • 代码
python 复制代码
import torch
import torch.nn as nn

class SEBlock(nn.Module):
    def __init__(self, in_channels, reduction=16):
        super(SEBlock, self).__init__()
        reduced_channels = max(in_channels // reduction, 1)
        self.global_avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Linear(in_channels, reduced_channels, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(reduced_channels, in_channels, bias=False),
            nn.Sigmoid()
        )

    def forward(self, x):
        batch_size, channels, _, _ = x.size()
        # Squeeze
        y = self.global_avg_pool(x).view(batch_size, channels)
        # Excitation
        y = self.fc(y).view(batch_size, channels, 1, 1)
        # Scale
        return x * y.expand_as(x)
  • 输出

    加权图像输出

3.2 应用在示例数据上
  • 代码
python 复制代码
import torch

# 创建示例输入数据
input_tensor = torch.randn(1, 64, 32, 32)  # (batch_size, in_channels, height, width)

# 初始化 SEBlock 模块
se_block = SEBlock(in_channels=64, reduction=16)

# 前向传播
output_tensor = se_block(input_tensor)
print(output_tensor.shape)
  • 输出

    torch.Size([1, 64, 32, 32])

四、注意事项

  1. SEBlock 模块通过全局平均池化和全连接层来重新校准通道的权重,从而增强模型的表达能力。
  2. 在使用 SEBlock 时,确保输入特征的通道数和缩减比例设置合理,以避免计算开销过大。
  3. 该模块主要用于图像数据处理,适用于各种计算机视觉任务,如图像分类、目标检测等。

相关推荐
资源大全免费分享5 分钟前
清华大学第五版《DeepSeek与AI幻觉》附五版合集下载方法
人工智能
龚大龙19 分钟前
机器学习(李宏毅)——RL(强化学习)
人工智能·机器学习
LaughingZhu24 分钟前
PH热榜 | 2025-02-23
前端·人工智能·经验分享·搜索引擎·产品运营
java_heartLake1 小时前
基于deepseek的AI知识库系统搭建
人工智能·deepseek
阿里云云原生2 小时前
山石网科×阿里云通义灵码,开启研发“AI智造”新时代
网络·人工智能·阿里云·ai程序员·ai程序员体验官
diemeng11193 小时前
AI前端开发技能变革时代:效率与创新的新范式
前端·人工智能
有Li3 小时前
跨中心模型自适应牙齿分割|文献速递-医学影像人工智能进展
人工智能
牧歌悠悠8 小时前
【深度学习】Unet的基础介绍
人工智能·深度学习·u-net
坚毅不拔的柠檬柠檬8 小时前
AI革命下的多元生态:DeepSeek、ChatGPT、XAI、文心一言与通义千问的行业渗透与场景重构
人工智能·chatgpt·文心一言
坚毅不拔的柠檬柠檬8 小时前
2025:人工智能重构人类文明的新纪元
人工智能·重构