python
import torch
import torch.nn as nn
"""
MobileNet(V1)を論文の表 1・図 3 のとおりに組む。
torchvision には MobileNetV2・V3 はあるが、V1 の組み込みはない。
"""
class DepthwiseSeparable(nn.Module):
"""3×3 深さ方向の畳み込み → BN → ReLU → 1×1 の畳み込み → BN → ReLU(図 3 の右)"""
def __init__(self, in_ch, out_ch, stride):
super().__init__()
self.depthwise = nn.Sequential(
# groups=in_ch で、チャネルごとに別のフィルターをかける(深さ方向の畳み込み)
nn.Conv2d(in_ch, in_ch, 3, stride=stride, padding=1, groups=in_ch, bias=False),
nn.BatchNorm2d(in_ch),
nn.ReLU(inplace=True),
)
self.pointwise = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 1, bias=False), # 1×1 でチャネルを混ぜる(点ごとの畳み込み)
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
def forward(self, x):
return self.pointwise(self.depthwise(x))
class MobileNetV1(nn.Module):
# (出力のチャネル数, 深さ方向の畳み込みのストライド)。表 1 の 13 個のブロック
# 表 1 の最後のブロックの「s2」は 7×7 → 7×7 なので、ストライド 1 にする
CFG = [(64, 1), (128, 2), (128, 1), (256, 2), (256, 1), (512, 2),
(512, 1), (512, 1), (512, 1), (512, 1), (512, 1), (1024, 2), (1024, 1)]
def __init__(self, num_classes=1000, alpha=1.0):
super().__init__()
ch = lambda c: max(8, int(c * alpha)) # 幅の係数 α:すべての層のチャネル数を α 倍にする
layers = [
nn.Conv2d(3, ch(32), 3, stride=2, padding=1, bias=False), # 最初の層だけ通常の畳み込み
nn.BatchNorm2d(ch(32)),
nn.ReLU(inplace=True),
]
in_ch = ch(32)
for out_ch, stride in self.CFG:
layers.append(DepthwiseSeparable(in_ch, ch(out_ch), stride))
in_ch = ch(out_ch)
self.features = nn.Sequential(*layers)
self.pool = nn.AdaptiveAvgPool2d(1) # 全体平均プーリング
self.fc = nn.Linear(in_ch, num_classes) # 活性化なし。ソフトマックスは損失関数の中で計算する
def forward(self, x):
x = self.pool(self.features(x))
return self.fc(torch.flatten(x, 1))
# 解像度の係数 ρ は、入力の画像の大きさ(224・192・160・128)で決める
model = MobileNetV1(num_classes=1000, alpha=0.75)
x = torch.randn(2, 3, 192, 192) # 0.75 MobileNet-192
model.eval() # BN は学習中に貯めた平均と分散を使う
with torch.no_grad():
print(model(x).shape) # torch.Size([2, 1000])
# 深さ方向の畳み込みの重みには Weight Decay をかけない(論文 3.2 節)
dw_params, other_params = [], []
for m in model.modules():
if isinstance(m, nn.Conv2d) and m.groups == m.in_channels and m.groups > 1:
dw_params += list(m.parameters())
elif isinstance(m, (nn.Conv2d, nn.Linear, nn.BatchNorm2d)):
other_params += list(m.parameters())
optimizer = torch.optim.RMSprop(
[{"params": dw_params, "weight_decay": 0.0},
{"params": other_params, "weight_decay": 4e-5}],
lr=0.045, alpha=0.9, momentum=0.9,
)
model.train() # 学習では BN はミニバッチの平均と分散を使う