paper:Global Attention Mechanism: Retain Information to Enhance Channel-Spatial Interactions
1、Global Attention Module
论文提出了一种全局注意力机制,通过减少信息减少和放大全局交互表示来提高深度神经网络的性能。引入了3D置换与多层感知器的通道注意力和卷积空间注意力子模块。减少信息约简和放大全局的交互功能,整体上,Global Attention采用了CBAM的整体结构,即通道-空间注意力机制,但是重新设计了子模块。
Global Attention Module 结构图:
2、Channel Attention & Spatial Attention
在Global Attention中:
- 通道注意力子模块:使用三维排列在三个维度上保留信息。然后,用一个两层的MLP(多层感知器)放大跨维通道-空间依赖性。
- 空间注意力子模块:为了关注空间信息,使用两个卷积层进行空间信息融合。还从通道注意力子模块中使用了与BAM相同的缩减比。与此同时,由于最大池化操作减少了信息的使用,产生了消极的影响。这里删除了池化操作以进一步保留特性映射。因此,空间注意力模块会显著增加参数的数量。此时为了防止参数显著增加,在ResNet50中采用带Channel Shuffle的Group卷积。
Channel Attention & Spatial Attention 结构图
3、代码实现
import torch
import torch.nn as nn
class GAM(nn.Module):
def __init__(self, channels, rate=4):
super(GAM, self).__init__()
mid_channels = channels // rate
self.channel_attention = nn.Sequential(
nn.Linear(channels, mid_channels),
nn.ReLU(inplace=True),
nn.Linear(mid_channels, channels)
)
self.spatial_attention = nn.Sequential(
nn.Conv2d(channels, mid_channels, kernel_size=7, stride=1, padding=3),
nn.BatchNorm2d(mid_channels),
nn.ReLU(inplace=True),
nn.Conv2d(mid_channels, channels, kernel_size=7, stride=1, padding=3),
nn.BatchNorm2d(channels)
)
def forward(self, x):
b, c, h, w = x.shape
# channel attention
x_permute = x.permute(0, 2, 3, 1).view(b, -1, c)
x_att_permute = self.channel_attention(x_permute).view(b, h, w, c)
x_channel_att = x_att_permute.permute(0, 3, 1, 2)
x = x * x_channel_att
# spatial attention
x_spatial_att = self.spatial_attention(x).sigmoid()
out = x * x_spatial_att
return out
if __name__ == '__main__':
x = torch.randn(4, 512, 7, 7).cuda()
model = GAM(512).cuda()
out = model(x)
print(out.shape)
本文只是对论文中的即插即用模块做了整合,对论文中的一些地方难免有遗漏之处,如果想对这些模块有更详细的了解,还是要去读一下原论文,肯定会有更多收获。