用于卷积神经网络的注意力机制(Attention)----CBAM: Convolutional Block Attention Module
主要思想:
对于一个中间层的feature map:, CBAM将会顺序推理出1维的channel attention map 以及2维的spatial attention map, 整个过程如下所示:
其中为element-wise multiplication,首先将channel attention map与输入的feature map相乘得到F’,之后计算F’的spatial attention map,并将两者相乘得到最终的输出F’’。下图为CBAM的示意图:
Channel attention module
feature map 的每个channel都被视为一个feature detector,channel attention主要关注于输入图片中什么(what)是有意义的。为了高效地计算channel attention,论文使用最大池化和平均池化对feature map在空间维度上进行压缩,得到两个不同的空间背景描述:和。使用由MLP组成的共享网络对这两个不同的空间背景描述进行计算得到channel attention map:。计算过程如下:
其中,后使用了Relu作为激活函数。
通道注意力机制:
```python
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 // 16, 1, bias=False)
self.relu1 = nn.ReLU()
self.fc2 = nn.Conv2d(in_planes // 16, 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)
# **空间注意力机制**
```python
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)
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)
感谢:https://www.jianshu.com/p/4fac94eaca91
https://zhuanlan.zhihu.com/p/99261200?from=singlemessage