python コピー
import torch
import torch.nn as nn
"""
MobileNetV3 のブロック(図 4)を、論文の式のとおりに組む。
ネットワーク全体は torchvision に組み込みがある(最後に示す)。
"""
def h_swish(x):
# h-swish(x) = x · ReLU6(x + 3) / 6(5.2 節)。nn.Hardswish と同じ
return x * torch.clamp(x + 3, 0, 6) / 6
class SqueezeExcite(nn.Module):
"""平均プーリング → 全結合(1/4、ReLU)→ 全結合(hard-sigmoid)→ チャネルごとに掛ける"""
def __init__(self, ch):
super().__init__()
self.pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(ch, ch // 4, 1) # 中の幅は広げた層の 1/4 に固定(5.3 節)
self.fc2 = nn.Conv2d(ch // 4, ch, 1)
self.gate = nn.Hardsigmoid() # ReLU6(x + 3) / 6
def forward(self, x):
w = self.gate(self.fc2(torch.relu(self.fc1(self.pool(x)))))
return x * w
class V3Block(nn.Module):
def __init__(self, in_ch, exp_ch, out_ch, kernel, stride, use_se, use_hs):
super().__init__()
act = nn.Hardswish if use_hs else nn.ReLU
self.use_shortcut = stride == 1 and in_ch == out_ch
layers = []
if exp_ch != in_ch: # 広げる 1×1(広げないブロックでは省く)
layers += [nn.Conv2d(in_ch, exp_ch, 1, bias=False), nn.BatchNorm2d(exp_ch), act()]
layers += [
nn.Conv2d(exp_ch, exp_ch, kernel, stride=stride, padding=kernel // 2, groups=exp_ch, bias=False),
nn.BatchNorm2d(exp_ch),
act(),
]
if use_se:
layers.append(SqueezeExcite(exp_ch)) # SE は深さ方向の畳み込みの後に置く
layers += [nn.Conv2d(exp_ch, out_ch, 1, bias=False), nn.BatchNorm2d(out_ch)] # 線形(活性化なし)
self.block = nn.Sequential(*layers)
def forward(self, x):
out = self.block(x)
return x + out if self.use_shortcut else out
# 表 1 の 14×14 の段の 5 番目のブロック(112 → 672 → 112、3×3、SE あり、h-swish)
block = V3Block(112, 672, 112, kernel=3, stride=1, use_se=True, use_hs=True)
block.eval()
with torch.no_grad():
print(block(torch.randn(1, 112, 14, 14)).shape) # torch.Size([1, 112, 14, 14])
# ネットワーク全体は torchvision の組み込みを使う
from torchvision.models import mobilenet_v3_large, MobileNet_V3_Large_Weights, mobilenet_v3_small
model = mobilenet_v3_large(weights=MobileNet_V3_Large_Weights.IMAGENET1K_V1) # weights=None なら重みはランダム
small = mobilenet_v3_small(weights=None)
model.classifier[3] = nn.Linear(model.classifier[3].in_features, 10) # 10 クラスの分類に付け替える
model.train() # 学習中は BN がミニバッチの統計量を使い、分類層の前のドロップアウトも働く
model.eval() # 推論では BN は貯めた統計量を使い、ドロップアウトは働かない