计算机视觉之 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. 该模块主要用于图像数据处理,适用于各种计算机视觉任务,如图像分类、目标检测等。

相关推荐
AI浩29 分钟前
VSSD:具有非因果状态空间对偶性的视觉Mamba模型
人工智能·目标检测·计算机视觉
lqqjuly1 小时前
Lidar调试记录Ⅳ之Ubuntu22.04+ROS2+Livox_SDK2环境下编译Livox ROS Driver 2
人工智能·机器人·自动驾驶
qq_436962181 小时前
数据中台:打破企业数据孤岛,实现全域资产化的关键一步
数据库·人工智能·信息可视化·数据挖掘·数据分析
宇若-凉凉2 小时前
BERT 完整教程指南
人工智能·深度学习·bert
JD技术委员会2 小时前
如何在跨部门沟通失误后进行协调与澄清
人工智能
PcVue China2 小时前
PcVue X 工控——工厂数字化转型与落地巡回研讨会圆满举行
人工智能·软件工程·scada·监控平台·工控网
StarPrayers.3 小时前
自蒸馏学习方法
人工智能·算法·学习方法
咚咚王者3 小时前
人工智能之编程进阶 Python高级:第十一章 过渡项目
开发语言·人工智能·python
深度学习lover3 小时前
<数据集>yolo航拍斑马线识别数据集<目标检测>
人工智能·深度学习·yolo·目标检测·计算机视觉·数据集·航拍斑马线识别
大力财经3 小时前
百度开启AI新纪元,让智能从成本变成超级生产力
人工智能·百度