python コピー
import torch
import torch.nn as nn
from torchvision.models import mnasnet1_0, MNASNet1_0_Weights
"""
MnasNet-A1 の層(MBConv・SE)と全体を、論文の図 7 のとおりに組む。
torchvision の mnasnet1_0 などは SE を使わない MnasNet-B1 の構造(論文の A1 とは別)。
"""
class SE(nn.Module):
# プーリング → 全結合 → ReLU → 全結合 → シグモイド → チャネルごとに掛ける(図 7(b))
def __init__(self, ch, squeeze_ch):
super().__init__()
self.fc = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Conv2d(ch, squeeze_ch, 1), nn.ReLU(inplace=True),
nn.Conv2d(squeeze_ch, ch, 1), nn.Sigmoid())
def forward(self, x):
return x * self.fc(x)
class MBConv(nn.Module):
def __init__(self, c_in, c_out, k, stride, expand, se=False):
super().__init__()
mid = c_in * expand
layers = [nn.Conv2d(c_in, mid, 1, bias=False), nn.BatchNorm2d(mid), nn.ReLU(inplace=True), # 広げる
nn.Conv2d(mid, mid, k, stride, k // 2, groups=mid, bias=False), nn.BatchNorm2d(mid),
nn.ReLU(inplace=True)] # 深さ方向
if se:
layers.append(SE(mid, max(1, int(c_in * 0.25)))) # SE の比率 0.25
layers += [nn.Conv2d(mid, c_out, 1, bias=False), nn.BatchNorm2d(c_out)] # 狭める(線形)
self.body = nn.Sequential(*layers)
self.use_res = stride == 1 and c_in == c_out # 形が同じときだけ入力を足す
def forward(self, x):
out = self.body(x)
return x + out if self.use_res else out
def mnasnet_a1(num_classes=1000):
# (拡張率, カーネル, 出力チャネル, 繰り返し, 最初のストライド, SE):図 7(a) のブロック 2〜7
cfg = [(6, 3, 24, 2, 2, False), (3, 5, 40, 3, 2, True), (6, 3, 80, 4, 2, False),
(6, 3, 112, 2, 1, True), (6, 5, 160, 3, 2, True), (6, 3, 320, 1, 1, False)]
layers = [nn.Conv2d(3, 32, 3, 2, 1, bias=False), nn.BatchNorm2d(32), nn.ReLU(inplace=True),
# ブロック 1:SepConv(3×3 深さ方向 → 1×1)
nn.Conv2d(32, 32, 3, 1, 1, groups=32, bias=False), nn.BatchNorm2d(32), nn.ReLU(inplace=True),
nn.Conv2d(32, 16, 1, bias=False), nn.BatchNorm2d(16)]
c = 16
for e, k, c_out, n, s, se in cfg:
for i in range(n):
layers.append(MBConv(c, c_out, k, s if i == 0 else 1, e, se))
c = c_out
return nn.Sequential(*layers, nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Dropout(0.2), nn.Linear(c, num_classes)) # 最後の層に Dropout 0.2
model = mnasnet_a1()
model.eval() # Dropout を止め、BN は貯めた平均と分散を使う
with torch.no_grad():
print(model(torch.randn(1, 3, 224, 224)).shape) # torch.Size([1, 1000])
# torchvision の組み込み(MnasNet-B1 の構造、幅 1.0)
tv = mnasnet1_0(weights=MNASNet1_0_Weights.IMAGENET1K_V1)
tv.eval()