SENet(Squeeze-and-Excitation Network)是一种用于深度卷积神经网络(CNN)的注意力机制,旨在增强网络在特征通道上的表示能力。它通过学习每个通道的重要性权重,然后使用这些权重来重新加权特征图,从而增强有用信息的表示,抑制不相关信息。
下面是详细介绍SENet注意力机制的步骤:
1. Squeeze(压缩)阶段:
在这个阶段,对输入的特征图进行全局平均池化,以压缩通道维度。假设输入特征图为 X
,形状为 (C, H, W)
,其中 C
是通道数,H
和 W
分别是高度和宽度。全局平均池化会得到一个大小为 (C, 1, 1)
的张量。
2. Excitation(激励)阶段:
在这个阶段,通过一个两层的全连接网络来学习通道的重要性权重。这个全连接网络由一个压缩操作和一个激励操作组成。
a. 压缩操作:将上一步中得到的 (C, 1, 1)
的张量输入到一个全连接层,将通道数压缩到一个较小的值,称为 middle_channels
。
b. 激励操作:将压缩后的特征输入到一个 ReLU 激活函数,得到一个 (middle_channels,)
的向量。
3. 重标定(Re-calibration)阶段:
将上一步中得到的激励向量扩展为 (C, 1, 1)
的张量,与原始特征图 X
逐元素相乘,从而获得每个通道上的加权特征图。
以下是用 PyTorch 实现的示例代码:
import torch
import torch.nn as nn
class SEBlock(nn.Module):
def __init__(self,in_channels,ratio):
super(SEBlock, self).__init__()
middle_channels=in_channels//ratio
self.squeeze=nn.AdaptiveAvgPool2d(1)
self.excitation = nn.Sequential(
nn.Conv2d(in_channels, middle_channels, kernel_size=1),
nn.ReLU(inplace=True),
nn.Conv2d(middle_channels, in_channels, kernel_size=1),
nn.Sigmoid()
)
def forward(self, x):
# Squeeze phase
squeezed = self.squeeze(x)
print("Squeezed shape:", squeezed.shape)
# Excitation phase
weights = self.excitation(squeezed)
print("Excitation weights shape:", weights.shape)
# Re-calibration phase
output = x * weights
print("Output shape:", output.shape)
return output
if __name__ == '__main__':
model=SEBlock(64,8)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
input_tensor=torch.randn(1,64,224,224).to(device)
output_tensor=model(input_tensor)
这段代码定义了一个名为 SEBlock
的模块,用于在给定的输入特征图上应用SENet注意力机制。在创建模型时,你可以将这个模块插入到你的卷积神经网络中,以增强特征表示能力。