通道注意力+像素注意力 pytorch实现

本文介绍了两种用于深度学习卷积神经网络的通道注意力机制:Squeeze-and-Excitation Networks(SENet)和ECA Layer。SELayer通过全局平均池化和全连接层来调整通道权重,而ECALayer则使用自适应平均池化和一维卷积来实现快速而有效的通道注意力。这两种机制能够增强模型对特征的捕获能力,提高网络性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Squeeze-and-Excitation Networks

在这里插入图片描述

import torch
from torch import nn


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)

if __name__ == "__main__":
    model =  SELayer(64)
    B,C,H ,W = 2,64,4,4
    x = torch.randn(B,C,H,W)
    res = model(x)
import torch
from torch import nn


class ECALayer(nn.Module):
    """Constructs a ECA module.
    Args:
        channel: Number of channels of the input feature map
        k_size: Adaptive selection of kernel size
    """
    def __init__(self, channel, k_size=3):
        super(ECALayer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.conv = nn.Conv1d(1, 1, kernel_size=k_size, padding=(k_size - 1) // 2, bias=False)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        # feature descriptor on the global spatial information
        y = self.avg_pool(x)

        # Two different branches of ECA module
        y = self.conv(y.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1)

        # Multi-scale information fusion
        y = self.sigmoid(y)

        return x * y.expand_as(x)

if __name__ == "__main__":
    model =  ECALayer(64)
    B,C,H ,W = 2,64,4,4
    x = torch.randn(B,C,H,W)
    res = model(x)
  • 全局池化的实现:将nn.AdaptiveAvgPool2d()的参数值设置为1,即输出1×1大小的数值
https://pytorch.org/docs/stable/generated/torch.nn.AdaptiveAvgPool2d.html?highlight=adaptiveavgpool2d#torch.nn.AdaptiveAvgPool2d
# target output size of 5x7
m = nn.AdaptiveAvgPool2d((5,7))
input = torch.randn(1, 64, 8, 9)
output = m(input)
# target output size of 7x7 (square)
m = nn.AdaptiveAvgPool2d(7)
input = torch.randn(1, 64, 10, 9)
output = m(input)
# target output size of 10x7
m = nn.AdaptiveAvgPool2d((None, 7))
input = torch.randn(1, 64, 10, 9)
output = m(input)

CBAM

在这里插入图片描述

https://github.com/luuuyi/CBAM.PyTorch/blob/master/model/resnet_cbam.py
out = self.ca(out) * out
out = self.sa(out) * out
class ChannelAttention(nn.Module):
    def __init__(self, in_planes, ratio=16):
        super(ChannelAttention, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.max_pool = nn.AdaptiveMaxPool2d(1)
           
        self.fc = nn.Sequential(nn.Conv2d(in_planes, in_planes // 16, 1, bias=False),
                               nn.ReLU(),
                               nn.Conv2d(in_planes // 16, in_planes, 1, bias=False))
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avg_out = self.fc(self.avg_pool(x))
        max_out = self.fc(self.max_pool(x))
        out = avg_out + max_out
        return self.sigmoid(out)

class SpatialAttention(nn.Module):
    def __init__(self, kernel_size=7):
        super(SpatialAttention, self).__init__()

        self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=kernel_size//2, bias=False)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avg_out = torch.mean(x, dim=1, keepdim=True)
        max_out, _ = torch.max(x, dim=1, keepdim=True)
        x = torch.cat([avg_out, max_out], dim=1)
        x = self.conv1(x)
        return self.sigmoid(x)

参考与更多

CBAM

Squeeze-and-Excitation Networks

从pytorch代码讲讲通道注意力SENet和ECANet

### 像素注意力机制的概念及实现 像素注意力机制是计算机视觉领域中的一种注意力机制,其核心思想是对图像中的每个像素点进行单独的关注度计算,从而突出重要区域并抑制不相关的信息。这种机制能够帮助模型更有效地捕捉局部和全局的特征关系[^1]。 在像素注意力机制中,通常会通过以下方式实现: 1. **像素级特征提取** 首先,模型会对输入图像的每个像素生成对应的特征向量。这些特征向量可以由卷积神经网络(CNN)提取,例如通过多层卷积操作得到特征图。特征图中的每个像素位置对应于原始图像的一个局部区域。 2. **注意力权重计算** 像素注意力机制通过计算每个像素与其他像素之间的相似性来生成注意力权重。这通常可以通过点积或加权函数实现。例如,给定一个特征图 \( F \in \mathbb{R}^{H \times W \times C} \),其中 \( H \) 和 \( W \) 分别表示特征图的高度和宽度,\( C \) 表示通道数,可以使用以下公式计算注意力权重: ```python def pixel_attention(feature_map): # 计算像素间的关系矩阵 attention_weights = feature_map @ feature_map.transpose(-1, -2) # 归一化权重 attention_weights = torch.softmax(attention_weights, dim=-1) return attention_weights ``` 3. **加权聚合** 生成的注意力权重会被用来对原始特征图进行加权聚合,从而增强重要区域的特征表示。这一过程可以视为一种自适应特征选择机制,使模型更加关注与任务相关的部分。 ```python def apply_attention(feature_map, attention_weights): # 应用注意力权重到特征图 attended_features = attention_weights @ feature_map return attended_features ``` #### 像素注意力机制的应用 像素注意力机制在计算机视觉中有广泛的应用,包括但不限于以下几个方面: 1. **目标检测** 在目标检测任务中,像素注意力可以帮助模型更好地聚焦于目标对象的关键区域,同时减少背景噪声的影响。例如,在两阶段检测器(如 Faster R-CNN)中,可以通过像素注意力增强感兴趣区域(ROI)的特征表示[^4]。 2. **语义分割** 对于语义分割任务,像素注意力可以提高模型对边界区域的敏感性,从而改善分割精度。通过为每个像素分配适当的注意力权重,模型能够更准确地区分相邻类别之间的差异[^5]。 3. **图像修复** 在图像修复任务中,像素注意力可以用于预测缺失区域的像素值。通过对已知区域的像素进行加权聚合,模型可以生成更自然、更连贯的修复结果。 4. **超分辨率重建** 像素注意力机制还可以应用于图像超分辨率重建任务中,通过增强高频细节信息来提升重建质量。这种方法特别适用于处理复杂纹理或边缘区域[^3]。 ```python # 示例:结合像素注意力的简单CNN模型 import torch import torch.nn as nn class PixelAttentionModule(nn.Module): def __init__(self, in_channels): super(PixelAttentionModule, self).__init__() self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=1) def forward(self, x): # 特征图转换为 [B, C, H*W] B, C, H, W = x.size() y = x.view(B, C, -1) # 计算注意力权重 attention_weights = torch.softmax(y @ y.transpose(-1, -2), dim=-1) # 应用注意力 attended_features = attention_weights @ y attended_features = attended_features.view(B, C, H, W) # 融合原始特征 out = self.conv(attended_features + x) return out ``` ### 注意事项 尽管像素注意力机制具有显著的优势,但其计算复杂度较高,特别是在处理高分辨率图像时。这是因为需要为每个像素计算与其他所有像素的相似性,导致时间复杂度和空间复杂度均为 \( O(n^2) \)[^4]。因此,在实际应用中,可能需要引入近似方法或稀疏化策略以降低计算开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值