CBAM-2018学习笔记

名称:

Convolutional Block Attention Module (CBAM)

来源:

CBAM: Convolutional Block Attention Module

相关工作:

#ResNet #GoogleNet #ResNeXt #Network-engineering #Attention-mechanism

创新点:

贡献:

  • 提出CBAM
  • 验证了其有效性
  • 改善提高了以往模型的性能

代码:

python 复制代码
  
import torch  
from torch import nn  
  
  
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.fc1 = nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False)  
        self.relu1 = nn.ReLU()  
        self.fc2 = nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False)  
        self.sigmoid = nn.Sigmoid()  
  
    def forward(self, x):  
        avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))  
        max_out = self.fc2(self.relu1(self.fc1(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__()  
  
        assert kernel_size in (3, 7), 'kernel size must be 3 or 7'  
        padding = 3 if kernel_size == 7 else 1  
  
        self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)  # 7,3     3,1  
        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)  
  
  
class CBAM(nn.Module):  
    def __init__(self, in_planes, ratio=16, kernel_size=7):  
        super(CBAM, self).__init__()  
        self.ca = ChannelAttention(in_planes, ratio)  
        self.sa = SpatialAttention(kernel_size)  
  
    def forward(self, x):  
        out = x * self.ca(x)  
        result = out * self.sa(out)  
        return result  
  
  
# 输入 N C H W,  输出 N C H Wif __name__ == '__main__':  
    block = CBAM(64)  
    input = torch.rand(3, 64, 32, 32)  
    output = block(input)  
    print(input.size(), output.size())
相关推荐
西岸行者3 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky3 天前
Django入门笔记
笔记·django
勇气要爆发3 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意3 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发3 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
别催小唐敲代码3 天前
嵌入式学习路线
学习
qianshanxue113 天前
计算机操作的一些笔记标题
笔记
土拨鼠烧电路3 天前
笔记11:数据中台:不是数据仓库,是业务能力复用的引擎
数据仓库·笔记
毛小茛3 天前
计算机系统概论——校验码
学习
土拨鼠烧电路3 天前
笔记14:集成与架构:连接孤岛,构建敏捷响应能力
笔记·架构