pytorch代码实现模型加CBAM注意力模块
时间: 2023-07-31 17:04:29 浏览: 247
CBAM(Convolutional Block Attention Module)是一种用于卷积神经网络的注意力模块,可以增强模型的表达能力和准确性。下面是一个使用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.ca = ChannelAttention(in_planes, ratio)
self.sa = SpatialAttention(kernel_size)
def forward(self, x):
out = x * self.ca(x)
return out * self.sa(out)
```
上述代码中,定义了一个CBAM类,包括了ChannelAttention模块和SpatialAttention模块。其中,ChannelAttention模块用于提取通道信息,SpatialAttention模块用于提取空间信息。在CBAM模块的forward()函数中,先使用ChannelAttention模块提取通道信息,然后再使用SpatialAttention模块提取空间信息。最后将两种信息结合起来得到最终输出。
使用该CBAM模块时,只需在需要使用注意力机制的卷积层后面添加一个CBAM实例即可。例如:
```python
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
self.cbam1 = CBAM(64)
self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
self.cbam2 = CBAM(128)
def forward(self, x):
x = self.conv1(x)
x = self.cbam1(x)
x = F.relu(x)
x = self.conv2(x)
x = self.cbam2(x)
x = F.relu(x)
return x
```
阅读全文