SENet、CBAM区别和应用以及对应的pytorch代码
时间: 2023-06-27 22:04:53 浏览: 116
pytorch SENet实现案例
SENet和CBAM都是用于图像分类的注意力机制模块,可以提高模型的性能。
SENet(Squeeze-and-Excitation Networks)通过引入一个称为“Squeeze-and-Excitation block”的模块来增强卷积神经网络的表示能力。SE block包含两个步骤:第一步是全局平均池化,将每个通道的特征图转换为一个标量;第二步是使用两个全连接层来学习每个通道的权重,以增强有用信息并削减噪声。SENet的优化是通过提高通道相关性来实现的。
CBAM(Convolutional Block Attention Module)是另一种注意力机制模块,它通过在通道和空间维度上使用注意力来提高卷积神经网络的性能。CBAM模块包含两个分支:一个分支用于学习通道级别的注意力,另一个分支用于学习空间级别的注意力。通过这种方式,CBAM可以提高模型的表示能力并消除噪声。
以下是SENet和CBAM的Pytorch实现代码:
SENet:
```python
import torch.nn as nn
import torch
class SEBlock(nn.Module):
def __init__(self, channel, reduction=16):
super(SEBlock, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inplace=True),
nn.Linear(channel // reduction, channel, bias=False),
nn.Sigmoid()
)
def forward(self, x):
b, c, _, _ = x.size()
y = self.avg_pool(x).view(b, c)
y = self.fc(y).view(b, c, 1, 1)
return x * y.expand_as(x)
```
CBAM:
```python
import torch.nn as nn
import torch
class ChannelAttention(nn.Module):
def __init__(self, channel, reduction=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.fc1 = nn.Conv2d(channel, channel // reduction, 1, bias=False)
self.relu1 = nn.ReLU()
self.fc2 = nn.Conv2d(channel // reduction, channel, 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, channel, reduction=16, kernel_size=7):
super(CBAM, self).__init__()
self.ChannelGate = ChannelAttention(channel, reduction=reduction)
self.SpatialGate = SpatialAttention(kernel_size=kernel_size)
def forward(self, x):
x_out = self.ChannelGate(x) * x
x_out = self.SpatialGate(x_out) * x_out
return x_out
```
阅读全文