python
import torch
import torch.nn as nn
# 全体平均プーリング:PyTorch では nn.AdaptiveAvgPool2d(1)(出力の縦横を 1 × 1 にする)
gap = nn.AdaptiveAvgPool2d(1)
# 頭の図と同じ値(3 チャネル × 4 × 4)。形は [バッチ, チャネル, 縦, 横]
x = torch.tensor([[
[[2., 4, 3, 1], [5, 6, 4, 2], [3, 5, 2, 1], [1, 2, 1, 2]],
[[0., 1, 0, 0], [1, 3, 2, 0], [0, 2, 1, 0], [0, 0, 0, 2]],
[[1., 0, 2, 1], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1]],
]])
print(gap(x).flatten()) # tensor([2.7500, 0.7500, 0.6250])
print(x.mean(dim=(2, 3))) # 同じ値(縦と横の平均)
# 分類のネットワークの最後:全体平均プーリング → 全結合層(ResNet などの形)
class Classifier(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(),
)
self.pool = nn.AdaptiveAvgPool2d(1) # パラメータなし
self.fc = nn.Linear(128, num_classes) # 重みは 128 × クラスの数だけ
def forward(self, x):
h = self.pool(self.features(x)).flatten(1) # [B, 128]。入力の縦横によらない
return self.fc(h)
model = Classifier()
model.eval() # BatchNorm があるので推論では eval()。全体平均プーリング自体は train/eval で同じ
with torch.no_grad():
print(model(torch.randn(2, 3, 32, 32)).shape) # torch.Size([2, 10])
print(model(torch.randn(2, 3, 64, 48)).shape) # 大きさが違っても torch.Size([2, 10])
# NIN の形:最後の畳み込みの出力をクラスの数のチャネルにし、平均をそのままソフトマックスへ
nin_head = nn.Sequential(nn.Conv2d(128, 10, kernel_size=1), nn.AdaptiveAvgPool2d(1), nn.Flatten())
print(nin_head(torch.randn(2, 128, 8, 8)).softmax(dim=1).shape) # torch.Size([2, 10])
# CAM:全結合層の重みで特徴マップを足し合わせ、クラスごとの地図にする
with torch.no_grad():
feats = model.features(torch.randn(1, 3, 32, 32)) # [1, 128, 16, 16]
c = model(torch.randn(1, 3, 32, 32)).argmax(dim=1).item()
cam = torch.einsum("k,bkhw->bhw", model.fc.weight[c], feats) # M_c(x, y) = Σ_k w_k^c f_k(x, y)
print(cam.shape) # torch.Size([1, 16, 16])