简述通道注意力、空间注意力、混合注意力、分支注意力及其代表模块
时间: 2025-06-19 22:52:15 浏览: 10
### 不同类型的注意力机制及其代表性模块
#### 通道注意力(Channel Attention)
通道注意力专注于调整特征图中的各个通道的重要性。通过学习不同通道之间的依赖关系,可以增强有用的特征并抑制无用的信息。SENet 是最早引入通道注意力机制的网络之一,在卷积神经网络中取得了显著的效果[^1]。
```python
def channel_attention(input_feature, ratio=8):
batch_size, channels, height, width = input_feature.size()
avg_pool = nn.AdaptiveAvgPool2d(1)(input_feature).view(batch_size, channels)
max_pool = nn.AdaptiveMaxPool2d(1)(input_feature).view(batch_size, channels)
shared_mlp = nn.Sequential(
nn.Linear(channels, channels // ratio),
nn.ReLU(),
nn.Linear(channels // ratio, channels)
)
avg_out = shared_mlp(avg_pool)
max_out = shared_mlp(max_pool)
out = torch.sigmoid(avg_out + max_out).unsqueeze(2).unsqueeze(3).expand_as(input_feature)
return out * input_feature
```
#### 空间注意力(Spatial Attention)
空间注意力则关注于捕捉输入特征图的空间位置信息。该方法能够突出显示重要的区域,并减弱不重要部分的影响。CBAM 中的空间注意力建立在通道注意力的基础上进一步增强了模型的表现力[^2]。
```python
def spatial_attention(input_feature):
kernel_size = 7
avg_pool = torch.mean(input_feature, dim=1, keepdim=True)
max_pool, _ = torch.max(input_feature, dim=1, keepdim=True)
combined = torch.cat([avg_pool, max_pool], dim=1)
conv_layer = nn.Conv2d(in_channels=2,
out_channels=1,
kernel_size=kernel_size,
stride=1,
padding=(kernel_size-1)//2,
bias=False)
output = conv_layer(combined)
output = torch.sigmoid(output)
return output.expand_as(input_feature) * input_feature
```
#### 混合注意力(Mixed Attention)
混合注意力是指将多个维度上的注意力结合起来共同作用的方式。例如 CBAM 同时利用了通道和空间两个方面的特性来构建更强大的表示能力;而 DANet 则采用了 position attention module 和 channel attention module 来实现更加灵活有效的全局上下文建模[^3]。
```python
class MixedAttention(nn.Module):
def __init__(self):
super(MixedAttention, self).__init__()
def forward(self, x):
ca_output = channel_attention(x)
sa_output = spatial_attention(ca_output)
return sa_output
```
#### 分支注意力(Branch Attention)
分支注意力通常指的是在一个架构内部设置不同的路径分别处理特定的任务或子任务,每条路径可能采用独立的注意力机制来进行优化。这种设计允许网络根据不同需求动态分配资源给各分支,从而提高整体性能。虽然这里没有具体的例子说明这一概念的应用场景,但在实际项目开发过程中可以根据具体问题定制化地加入此类组件以提升效果。
阅读全文
相关推荐
