python コピー
import torch
import torch.nn as nn
# 空間ピラミッドプーリング:段ごとに AdaptiveMaxPool2d(n) をかけてつなげる
# AdaptiveMaxPool2d のマスの範囲は [floor(i*h/n), ceil((i+1)*h/n))(論文の付録 A と同じ決め方)
class SpatialPyramidPooling(nn.Module):
def __init__(self, levels=(6, 3, 2, 1)): # 論文の分類の実験の 4 段(50 マス)
super().__init__()
self.pools = nn.ModuleList([nn.AdaptiveMaxPool2d(n) for n in levels])
self.num_bins = sum(n * n for n in levels)
def forward(self, x): # x: [B, C, h, w](h, w は自由)
return torch.cat([p(x).flatten(1) for p in self.pools], dim=1) # [B, C * マスの数]
# 頭の図と同じ値(1 チャネル × 6 × 6)。段は 3×3・2×2・1×1
x = torch.tensor([[[[1., 0, 2, 4, 1, 0],
[3, 2, 0, 1, 5, 2],
[0, 6, 1, 0, 2, 1],
[2, 1, 3, 2, 0, 4],
[1, 0, 2, 7, 1, 0],
[4, 2, 0, 1, 3, 2]]]])
spp = SpatialPyramidPooling(levels=(3, 2, 1))
print(spp(x)) # [3, 4, 5, 6, 3, 4, 4, 7, 3, 6, 5, 4, 7, 7] の 14 個
# 特徴マップの大きさが違っても、出力の長さは同じ
print(spp(torch.randn(1, 256, 13, 13)).shape) # torch.Size([1, 3584]) = 256 × 14
print(spp(torch.randn(1, 256, 10, 17)).shape) # torch.Size([1, 3584])
# SPP-net の形:畳み込み層 → SPP(最後のプーリング層の代わり)→ 全結合層
class SPPNet(nn.Module):
def __init__(self, num_classes=1000, levels=(6, 3, 2, 1)):
super().__init__()
self.features = nn.Sequential( # 例として小さめの畳み込み層
nn.Conv2d(3, 96, 7, stride=2, padding=1), nn.ReLU(), nn.MaxPool2d(3, 2),
nn.Conv2d(96, 256, 5, stride=2, padding=1), nn.ReLU(), nn.MaxPool2d(3, 2),
nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(),
)
self.spp = SpatialPyramidPooling(levels)
self.classifier = nn.Sequential(
nn.Linear(256 * self.spp.num_bins, 4096), nn.ReLU(), nn.Dropout(0.5), # fc6
nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(0.5), # fc7
nn.Linear(4096, num_classes),
)
def forward(self, x):
return self.classifier(self.spp(self.features(x)))
model = SPPNet()
model.eval() # Dropout があるので推論では eval()。SPP 自体は train/eval で同じ
with torch.no_grad():
# 大きさの違う画像をそのまま入れられる(ミニバッチの中では大きさをそろえる)
print(model(torch.randn(2, 3, 224, 224)).shape) # torch.Size([2, 1000])
print(model(torch.randn(1, 3, 180, 300)).shape) # torch.Size([1, 1000])