python コピー
import torch
import torch.nn as nn
from torchvision.models import shufflenet_v2_x1_0, ShuffleNet_V2_X1_0_Weights
"""
ShuffleNet V2 のユニットを、論文の図 3(c)(d) のとおりに組む。
torchvision の shufflenet_v2_x1_0 などは、論文の表 5 の 4 つの大きさに対応する組み込みのモデル。
"""
def channel_shuffle(x, groups=2):
# (N, g·n, H, W) → (N, g, n, H, W) → 転置 → (N, g·n, H, W)。V2 では 2 つの枝を混ぜるので g = 2
n_batch, ch, h, w = x.shape
x = x.view(n_batch, groups, ch // groups, h, w).transpose(1, 2).contiguous()
return x.view(n_batch, ch, h, w)
def conv_bn(c_in, c_out, k, stride=1, groups=1, relu=True):
layers = [nn.Conv2d(c_in, c_out, k, stride, k // 2, groups=groups, bias=False), nn.BatchNorm2d(c_out)]
if relu:
layers.append(nn.ReLU(inplace=True))
return nn.Sequential(*layers)
class ShuffleV2Unit(nn.Module):
def __init__(self, c_in, c_out, stride):
super().__init__()
self.stride = stride
half = c_out // 2 # 各枝の出力は、出力のチャネル数の半分
if stride == 2: # 図 3(d):分割せず、入力を両方の枝に入れる
self.branch1 = nn.Sequential(
conv_bn(c_in, c_in, 3, stride=2, groups=c_in, relu=False), # 深さ方向(BN のみ)
conv_bn(c_in, half, 1), # 1×1(BN・ReLU)
)
b2_in = c_in
else: # 図 3(c):半分はそのまま通す
assert c_in == c_out and c_in % 2 == 0
b2_in = half
self.branch2 = nn.Sequential( # 3 つとも入力と出力のチャネル数が同じ(G1)
conv_bn(b2_in, half, 1), # 1×1(グループにしない:G2)
conv_bn(half, half, 3, stride=stride, groups=half, relu=False), # 3×3 深さ方向(BN のみ)
conv_bn(half, half, 1), # 1×1(BN・ReLU)
)
def forward(self, x):
if self.stride == 1:
x1, x2 = x.chunk(2, dim=1) # チャネル分割(c' = c/2)
out = torch.cat([x1, self.branch2(x2)], dim=1) # 足し算ではなく連結
else:
out = torch.cat([self.branch1(x), self.branch2(x)], dim=1) # チャネル数は 2 倍
return channel_shuffle(out, 2)
unit = ShuffleV2Unit(116, 116, stride=1)
print(unit(torch.randn(1, 116, 28, 28)).shape) # torch.Size([1, 116, 28, 28])
down = ShuffleV2Unit(116, 232, stride=2)
print(down(torch.randn(1, 116, 28, 28)).shape) # torch.Size([1, 232, 14, 14])
# torchvision の組み込み(ShuffleNet V2 1×、ImageNet で学習した重み)
model = shufflenet_v2_x1_0(weights=ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1)
model.eval() # BN は学習中に貯めた平均と分散を使う
with torch.no_grad():
print(model(torch.randn(1, 3, 224, 224)).shape) # torch.Size([1, 1000])
model.train() # 学習では BN はミニバッチの平均と分散を使う