python
import torch
import torch.nn as nn
import torch.nn.functional as F
# PyTorch に組み込みの層はないので、論文の式 (4)〜(6) どおりに書く
class StochasticPool2d(nn.Module):
"""確率的プーリング(Zeiler & Fergus, 2013)。値は 0 以上(ReLU のあと)を前提にする"""
def __init__(self, kernel_size=3, stride=2):
super().__init__()
self.k = kernel_size
self.s = stride
def forward(self, x):
B, C, H, W = x.shape
k, s = self.k, self.s
H_out, W_out = (H - k) // s + 1, (W - k) // s + 1
# 窓を切り出す:[B, C*k*k, L] -> [B, C, L, k*k](L は窓の数)
win = F.unfold(x, kernel_size=k, stride=s)
win = win.view(B, C, k * k, -1).transpose(2, 3)
a = win.clamp(min=0) # 念のため負の値を 0 に(式 (4) の前提)
total = a.sum(dim=-1, keepdim=True) # 窓の合計 Σ a_k
if self.training:
# 式 (4):p_i = a_i / Σ a_k。すべて 0 の窓は、どれを選んでも 0 なので一様にしておく
p = torch.where(total > 0, a / total.clamp_min(1e-12), torch.full_like(a, 1.0 / (k * k)))
# 式 (5):確率 p に従って位置を 1 つ選ぶ(窓ごと・チャネルごと・例ごとに別々)
idx = torch.multinomial(p.reshape(-1, k * k), num_samples=1).view(B, C, -1, 1)
out = win.gather(-1, idx).squeeze(-1) # 勾配は選んだ位置にだけ流れる
else:
# 式 (6):Σ p_i a_i = Σ a_i^2 / Σ a_k(すべて 0 の窓は 0)
out = (a * a).sum(dim=-1) / total.squeeze(-1).clamp_min(1e-12)
return out.view(B, C, H_out, W_out)
# 頭の図と同じ 3×3 の窓。形は [バッチ, チャネル, 縦, 横]
x = torch.tensor([[[[0., 1., 0.],
[3., 0., 2.],
[0., 4., 0.]]]])
pool = StochasticPool2d(kernel_size=3, stride=2)
pool.eval()
print(pool(x).item()) # 3.0(= 0.1·1 + 0.3·3 + 0.2·2 + 0.4·4)
pool.train()
samples = torch.stack([pool(x).flatten() for _ in range(10000)]).flatten()
for v in [1., 2., 3., 4.]:
print(v, (samples == v).float().mean().item()) # およそ 0.1, 0.2, 0.3, 0.4
print(samples.mean().item()) # 期待値はおよそ 3.0(推論のときの値と一致)
# 論文の実験に近い形:畳み込み(5×5、64 マップ)→ ReLU → 確率的プーリング(3×3、ストライド 2)を 3 回
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
layers, c_in = [], 3
for _ in range(3):
layers += [nn.Conv2d(c_in, 64, kernel_size=5, padding=2), nn.ReLU(),
StochasticPool2d(kernel_size=3, stride=2)]
c_in = 64
self.features = nn.Sequential(*layers)
self.fc = nn.LazyLinear(num_classes)
def forward(self, x):
return self.fc(self.features(x).flatten(1))
model = SmallCNN()
images = torch.randn(8, 3, 32, 32) # CIFAR-10 と同じ大きさ
model.train() # 学習:窓ごとにランダムに選ぶ
print(model(images).shape) # torch.Size([8, 10])
model.eval() # 推論:確率で重み付けした和(毎回同じ結果)
with torch.no_grad():
print(torch.equal(model(images), model(images))) # True