python
import torch
import torch.nn as nn
"""
ShuffleNet(V1)のユニットとネットワークを、論文の図 2・表 1 のとおりに組む。
torchvision には V1 の組み込みはない(shufflenet_v2_* は別の構造の ShuffleNet V2)。
"""
def channel_shuffle(x, groups):
# (N, g·n, H, W) → (N, g, n, H, W) → 転置して (N, n, g, H, W) → (N, g·n, H, W)(3.1 節)
n_batch, ch, h, w = x.shape
x = x.view(n_batch, groups, ch // groups, h, w)
x = x.transpose(1, 2).contiguous()
return x.view(n_batch, ch, h, w)
class ShuffleUnit(nn.Module):
def __init__(self, in_ch, out_ch, groups, stride, first_group=True):
super().__init__()
self.stride = stride
self.groups = groups
# 縮小するユニットは入力と連結するので、主の経路は (出力 − 入力) チャネルを作る
main_out = out_ch - in_ch if stride == 2 else out_ch
mid = out_ch // 4 # ボトルネックは出力の 1/4
g1 = groups if first_group else 1 # Stage2 の最初の 1×1 はグループに分けない
self.gconv1 = nn.Sequential(
nn.Conv2d(in_ch, mid, 1, groups=g1, bias=False), nn.BatchNorm2d(mid), nn.ReLU(inplace=True)
)
self.g1 = g1
self.dwconv = nn.Sequential( # 深さ方向の畳み込みの後は BN だけ(ReLU なし)
nn.Conv2d(mid, mid, 3, stride=stride, padding=1, groups=mid, bias=False), nn.BatchNorm2d(mid)
)
self.gconv2 = nn.Sequential( # この後にはシャッフルしない
nn.Conv2d(mid, main_out, 1, groups=groups, bias=False), nn.BatchNorm2d(main_out)
)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
out = self.gconv1(x)
if self.g1 > 1:
out = channel_shuffle(out, self.g1)
out = self.gconv2(self.dwconv(out))
if self.stride == 2: # 平均プーリングのショートカットと連結(図 2(c))
short = nn.functional.avg_pool2d(x, 3, stride=2, padding=1)
return self.relu(torch.cat([short, out], dim=1))
return self.relu(x + out) # 足してから ReLU(図 2(b))
class ShuffleNetV1(nn.Module):
STAGE_CH = {1: 144, 2: 200, 3: 240, 4: 272, 8: 384} # 表 1 の Stage2 の出力のチャネル数
def __init__(self, groups=3, num_classes=1000):
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, 24, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(24), nn.ReLU(inplace=True),
nn.MaxPool2d(3, stride=2, padding=1),
)
layers, in_ch, out_ch = [], 24, self.STAGE_CH[groups]
for stage, repeat in enumerate([4, 8, 4]): # Stage2〜4 のユニットの数
for i in range(repeat):
layers.append(ShuffleUnit(in_ch, out_ch, groups, stride=2 if i == 0 else 1,
first_group=not (stage == 0 and i == 0)))
in_ch = out_ch
out_ch *= 2 # 次の段でチャネル数を 2 倍にする
self.stages = nn.Sequential(*layers)
self.pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Linear(in_ch, num_classes)
def forward(self, x):
x = self.pool(self.stages(self.stem(x)))
return self.fc(torch.flatten(x, 1))
model = ShuffleNetV1(groups=3)
model.eval() # BN は学習中に貯めた平均と分散を使う
with torch.no_grad():
print(model(torch.randn(1, 3, 224, 224)).shape) # torch.Size([1, 1000])
model.train() # 学習では BN はミニバッチの平均と分散を使う