cbam代码pytorch
时间: 2023-07-09 22:47:32 浏览: 89
Python-BAM和CBAM的官方PyTorch代码
以下是基于PyTorch实现的CBAM模块代码示例:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
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 CBAM(nn.Module):
def __init__(self, in_planes, ratio=16, kernel_size=7):
super(CBAM, self).__init__()
self.channel_att = ChannelAttention(in_planes, ratio)
self.spatial_att = SpatialAttention(kernel_size)
def forward(self, x):
out = self.channel_att(x) * x
out = self.spatial_att(out) * out
return out
```
这是一个包含Channel Attention和Spatial Attention的CBAM模块的实现。其中,Channel Attention和Spatial Attention分别用于对通道和空间维度进行注意力加权。Channel Attention使用全局平均池化和全局最大池化来提取特征,并通过两个全连接层获得通道维度的权重,最后使用Sigmoid函数进行归一化。Spatial Attention则使用通道维度上的加权特征对空间维度进行注意力加权,其中包含了平均池化和最大池化操作,以及一个卷积层和Sigmoid函数。CBAM模块将Channel Attention和Spatial Attention结合起来,对输入特征图进行加权。
阅读全文