python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops import SqueezeExcitation
"""
1. 論文の式(2)〜(4)のとおりに SE ブロックを組み、ResNet のボトルネックに入れる(SE-ResNet のモジュール)
2. torchvision.ops.SqueezeExcitation(同じ計算を 1×1 畳み込みで書いたもの)を使う
"""
class SEBlock(nn.Module):
def __init__(self, channels, reduction=16):
super().__init__()
self.fc1 = nn.Linear(channels, channels // reduction, bias=False) # W1:C → C/r(論文は ResNet ではバイアスなしが良かった)
self.fc2 = nn.Linear(channels // reduction, channels, bias=False) # W2:C/r → C
def forward(self, u): # u:[N, C, H, W]
z = u.mean(dim=(2, 3)) # Squeeze:全体平均プーリング → [N, C]
s = torch.sigmoid(self.fc2(F.relu(self.fc1(z)))) # Excitation:σ(W2 δ(W1 z)) → 0〜1
return u * s[:, :, None, None] # Scale:チャネル c に s_c を掛ける
class SEBottleneck(nn.Module):
"""SE-ResNet のボトルネック:1×1 → 3×3 → 1×1 の後、ショートカットと足す前に SE ブロック"""
def __init__(self, in_ch, mid_ch, stride=1, reduction=16):
super().__init__()
out_ch = mid_ch * 4
self.residual = nn.Sequential(
nn.Conv2d(in_ch, mid_ch, 1, bias=False), nn.BatchNorm2d(mid_ch), nn.ReLU(inplace=True),
nn.Conv2d(mid_ch, mid_ch, 3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(mid_ch), nn.ReLU(inplace=True),
nn.Conv2d(mid_ch, out_ch, 1, bias=False), nn.BatchNorm2d(out_ch),
)
self.se = SEBlock(out_ch, reduction)
self.shortcut = nn.Identity()
if stride != 1 or in_ch != out_ch: # 形が変わるときだけ 1×1 畳み込みのショートカット
self.shortcut = nn.Sequential(nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=False), nn.BatchNorm2d(out_ch))
def forward(self, x):
return F.relu(self.se(self.residual(x)) + self.shortcut(x)) # SE は足し算の前(SE-POST にしない)
block = SEBottleneck(in_ch=256, mid_ch=64) # conv2_x のブロック:SE の全結合は 256 → 16 → 256
x = torch.randn(8, 256, 56, 56)
block.train() # BN はミニバッチの統計を使う
y = block(x)
print(y.shape) # [8, 256, 56, 56]
print(sum(p.numel() for p in block.se.parameters())) # 2 × 256 × 16 = 8192(式(5)の 1 ブロック分)
# --- torchvision の部品 ---
# squeeze_channels は縮小率 r ではなく、間の層のチャネル数(C/r)を渡す。1×1 畳み込みにはバイアスがある
se = SqueezeExcitation(input_channels=256, squeeze_channels=256 // 16)
se.eval()
with torch.no_grad():
print(se(x).shape) # [8, 256, 56, 56]