c2f模块加入cbam
时间: 2025-05-17 20:03:52 浏览: 16
### CBAM注意力机制在C2F模块中的应用
CBAM(Convolutional Block Attention Module)是一种轻量级的注意力机制,它通过通道注意和空间注意两个阶段来增强特征图的有效信息[^2]。为了将CBAM应用于C2F模块中,可以按照以下方式构建代码。
以下是基于PyTorch框架的一个可能实现:
```python
import torch
import torch.nn as 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)
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 C2FModuleWithCBAM(nn.Module):
def __init__(self, in_channels, out_channels):
super(C2FModuleWithCBAM, self).__init__()
# 基础卷积层
self.conv_layer = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
# 添加CBAM注意力模块
self.channel_attention = ChannelAttention(out_channels)
self.spatial_attention = SpatialAttention()
def forward(self, x):
x = self.conv_layer(x) # 卷积操作
channel_att = self.channel_attention(x) * x # 应用通道注意力
spatial_att = self.spatial_attention(channel_att) * channel_att # 应用空间注意力
return spatial_att
# 测试模型
if __name__ == "__main__":
input_tensor = torch.randn((1, 64, 128, 128)) # 输入张量形状 [batch_size, channels, height, width]
model = C2FModuleWithCBAM(in_channels=64, out_channels=128)
output = model(input_tensor)
print(output.shape) # 输出张量形状验证
```
#### 实现说明
- **ChannelAttention**: 这部分实现了CBAM的通道注意力计算逻辑,通过对输入特征图进行全局平均池化和最大池化操作提取重要信息,并通过全连接网络调整权重。
- **SpatialAttention**: 此处定义了CBAM的空间注意力组件,利用均值和最大值聚合的方式生成二通道特征图并进一步处理得到最终的空间掩码。
- **C2FModuleWithCBAM**: 将基础卷积层与CBAM相结合,在完成常规卷积运算之后依次施加通道注意力和空间注意力以提升性能[^1]。
阅读全文
相关推荐


















