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

相关推荐
深度学习机器6 分钟前
Ghostty终端使用体验
人工智能·命令行
Token炼金师7 分钟前
幂律的预言:Kaplan 与 Chinchilla 的算力账本 —— Scaling Laws 与最优配比
人工智能·深度学习·大模型架构·kv cache·scaling laws
云烟成雨TD24 分钟前
LangFlow 1.x 系列【5】可视化编辑页面功能说明
人工智能·python·agent
小宋102127 分钟前
Dify 前后端联调踩坑记录:`/console/api/account/profile` 登录失败排查
人工智能·dify
幸福指北1 小时前
现代化智能终端AShell,是否能够替代你的古法终端?让服务器运维更加高效智能化,快来试试看!
人工智能·ai·终端
女神下凡1 小时前
office系列软件 激活破解(office 2019, 2021, 2024)
人工智能·microsoft
2503_931712481 小时前
京东裸眼3D展示——30分钟建模绒感褶皱光泽都能还原
人工智能
星马梦缘1 小时前
机器学习与模式识别 第八章 MAP与偏方差 考点压缩
人工智能·机器学习·map·岭回归·mle·双重下降
一楼的猫1 小时前
AI写作合规技术方案:平台检测机制分析与规避策略
人工智能·学习·机器学习·ai写作
阿拉斯攀登2 小时前
Agent 核心架构:思考-行动-观察循环(ReAct)
人工智能·ai·agent·react