CBAM的理解、Pytorch实现及用法

1. 总述

对于卷积神经网络生成的feature map,CBAM从通道和空间两个维度计算feature map的attention map,然后将attention map与输入的feature map相乘来进行特征的自适应学习。CBAM是一个轻量的通用模块,可以将其融入到各种卷积神经网络中进行端到端的训练。也就是说由于CBMA模块输入和输出的featuremap大小是一致的,因此可用于网络的各层。

2. CBAM模块

在这里插入图片描述

2.1 CAM模块

在这里插入图片描述

2.2 SAM模块

在这里插入图片描述

3. CBAM的Pytorch实现

# ------------------------#
# CBAM模块的Pytorch实现
# ------------------------#

# 通道注意力模块
class ChannelAttentionModule(nn.Module):
    def __init__(self, channel, reduction=16):  
        super(ChannelAttentionModule, self).__init__()
        mid_channel = channel // reduction
        # 使用自适应池化缩减map的大小,保持通道不变  
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.max_pool = nn.AdaptiveMaxPool2d(1)
        
        self.shared_MLP = nn.Sequential(
            nn.Linear(in_features=channel, out_features=mid_channel),
            nn.ReLU(),
            nn.Linear(in_features=mid_channel, out_features=channel)
        )
        self.sigmoid = nn.Sigmoid()
        # self.act=SiLU()
    
    def forward(self, x):
        avgout = self.shared_MLP(self.avg_pool(x).view(x.size(0),-1)).unsqueeze(2).unsqueeze(3)
        maxout = self.shared_MLP(self.max_pool(x).view(x.size(0),-1)).unsqueeze(2).unsqueeze(3)
        return self.sigmoid(avgout + maxout)
        
# 空间注意力模块
class SpatialAttentionModule(nn.Module):
    def __init__(self):
        super(SpatialAttentionModule, self).__init__()
        self.conv2d = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=7, stride=1, padding=3) 
        # self.act=SiLU()
        self.sigmoid = nn.Sigmoid()
    
    def forward(self, x):
        # map尺寸不变,缩减通道
        avgout = torch.mean(x, dim=1, keepdim=True)
        maxout, _ = torch.max(x, dim=1, keepdim=True)
        out = torch.cat([avgout, maxout], dim=1)
        out = self.sigmoid(self.conv2d(out))
        return out

# CBAM模块
class CBAM(nn.Module):
    def __init__(self, channel): 
        super(CBAM, self).__init__()
        self.channel_attention = ChannelAttentionModule(c1)
        self.spatial_attention = SpatialAttentionModule()

    def forward(self, x):
        out = self.channel_attention(x) * x
        out = self.spatial_attention(out) * out
        return out

4. ResNet中与一个ResBlock集成的CBAM的用法

在这里插入图片描述

4.1 个人理解

在这里插入图片描述在这里插入图片描述

4.2 Pytorch代码实现

# ------------------#
# ResBlock+CBAM
# ------------------#
import torch
import torch.nn as nn
import torchvision


class ChannelAttentionModule(nn.Module):
    def __init__(self, channel, ratio=16):
        super(ChannelAttentionModule, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.max_pool = nn.AdaptiveMaxPool2d(1)

        self.shared_MLP = nn.Sequential(
            nn.Conv2d(channel, channel // ratio, 1, bias=False),
            nn.ReLU(),
            nn.Conv2d(channel // ratio, channel, 1, bias=False)
        )
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avgout = self.shared_MLP(self.avg_pool(x))
        print(avgout.shape)
        maxout = self.shared_MLP(self.max_pool(x))
        return self.sigmoid(avgout + maxout)


class SpatialAttentionModule(nn.Module):
    def __init__(self):
        super(SpatialAttentionModule, self).__init__()
        self.conv2d = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=7, stride=1, padding=3)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avgout = torch.mean(x, dim=1, keepdim=True)
        maxout, _ = torch.max(x, dim=1, keepdim=True)
        out = torch.cat([avgout, maxout], dim=1)
        out = self.sigmoid(self.conv2d(out))
        return out


class CBAM(nn.Module):
    def __init__(self, channel):
        super(CBAM, self).__init__()
        self.channel_attention = ChannelAttentionModule(channel)
        self.spatial_attention = SpatialAttentionModule()

    def forward(self, x):
        out = self.channel_attention(x) * x
        print('outchannels:{}'.format(out.shape))
        out = self.spatial_attention(out) * out
        return out


class ResBlock_CBAM(nn.Module):
    def __init__(self,in_places, places, stride=1,downsampling=False, expansion = 4):
        super(ResBlock_CBAM,self).__init__()
        self.expansion = expansion
        self.downsampling = downsampling

        self.bottleneck = nn.Sequential(
            nn.Conv2d(in_channels=in_places,out_channels=places,kernel_size=1,stride=1, bias=False),
            nn.BatchNorm2d(places),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_channels=places, out_channels=places, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(places),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_channels=places, out_channels=places*self.expansion, kernel_size=1, stride=1, bias=False),
            nn.BatchNorm2d(places*self.expansion),
        )
        self.cbam = CBAM(channel=places*self.expansion)

        if self.downsampling:
            self.downsample = nn.Sequential(
                nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(places*self.expansion)
            )
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        residual = x
        out = self.bottleneck(x)
        print(x.shape)
        out = self.cbam(out)
        if self.downsampling:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)
        return out


model = ResBlock_CBAM(in_places=16, places=4)
print(model)

input = torch.randn(1, 16, 64, 64)
out = model(input)
print(out.shape)

参考文献

  • 9
    点赞
  • 83
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
CBAM是一种用于卷积神经网络的注意力机制模块,可以在不同层次上适应性地学习特征。在PyTorch实现CBAM可以按照以下步骤进行: 1. 创建CBAM模块:CBAM包括通道注意力模块(CAM)和空间注意力模块(SAM)。首先,创建一个通道注意力模块,它计算输入特征图的通道注意力图。然后,创建一个空间注意力模块,它计算输入特征图的空间注意力图。最后,将通道注意力图和空间注意力图相乘得到CBAM的输出特征图。 2. 实现CBAMPyTorch代码:在PyTorch中,可以使用torch.nn模块来构建CBAM模块。可以使用卷积、全局平均池化、全连接等操作来实现通道注意力模块和空间注意力模块。具体实现的代码可以参考引用中的PyTorch实现部分。 3. 将CBAM集成到ResNet的ResBlock中:CBAM可以用于网络的各个层。在ResNet中,可以将CBAM模块添加到ResBlock中。具体实现的步骤包括:首先,在ResBlock的输入之前添加CBAM模块;然后,将CBAM的输出与ResBlock的输入相加作为ResBlock的输出。 4. 理解个人理解和代码实现:在使用CBAM时,可以根据个人理解调整CBAM模块的参数,如通道注意力模块和空间注意力模块的卷积核大小、全连接层的隐藏单元数等。同时,可以使用PyTorch提供的相关函数和操作来实现CBAM的功能。 综上所述,CBAMPyTorch实现包括创建CBAM模块、实现CBAMPyTorch代码、将CBAM集成到ResNet的ResBlock中,并根据个人理解和需求进行参数调整。具体的实现步骤和代码可以参考引用中的内容。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* *2* [CBAM理解Pytorch实现用法](https://blog.csdn.net/weixin_41790863/article/details/123413303)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值