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

相关推荐
会飞的Anthony几秒前
基于Python的自然语言处理系列(14):TorchText + biGRU + Attention + Teacher Forcing
人工智能·自然语言处理
jun7788952 分钟前
机器学习-监督学习:朴素贝叶斯分类器
人工智能·学习·机器学习
FL16238631294 分钟前
基于yolov5的混凝土缺陷检测系统python源码+onnx模型+评估指标曲线+精美GUI界面
人工智能·python·yolo
Kenneth風车8 分钟前
【第十三章:Sentosa_DSML社区版-机器学习聚类】
人工智能·低代码·机器学习·数据分析·聚类
jndingxin15 分钟前
OpenCV运动分析和目标跟踪(4)创建汉宁窗函数createHanningWindow()的使用
人工智能·opencv·目标跟踪
机器之心16 分钟前
o1 带火的 CoT 到底行不行?新论文引发了论战
android·人工智能
机器之心22 分钟前
从架构、工艺到能效表现,全面了解 LLM 硬件加速,这篇综述就够了
android·人工智能
jndingxin1 小时前
OpenCV特征检测(1)检测图像中的线段的类LineSegmentDe()的使用
人工智能·opencv·计算机视觉
@月落1 小时前
alibaba获得店铺的所有商品 API接口
java·大数据·数据库·人工智能·学习
z千鑫1 小时前
【人工智能】如何利用AI轻松将java,c++等代码转换为Python语言?程序员必读
java·c++·人工智能·gpt·agent·ai编程·ai工具