python
import torch
import torch.nn as nn
# 拡張畳み込み:PyTorch では nn.Conv2d の dilation で拡張率を指定する
x = torch.randn(1, 16, 64, 64) # [バッチ, チャネル, 高さ, 幅]
# 拡張率 2 の 3×3 畳み込み。大きさを保つにはパディングを拡張率と同じにする
conv = nn.Conv2d(16, 16, kernel_size=3, dilation=2, padding=2)
print(conv(x).shape) # torch.Size([1, 16, 64, 64])
# padding=1 のままだと、(64 + 2 - 2*2 - 1) / 1 + 1 = 62 に縮む
print(nn.Conv2d(16, 16, kernel_size=3, dilation=2, padding=1)(x).shape) # [1, 16, 62, 62]
# 重みの数は拡張率によらず同じ(16 * 16 * 3 * 3 + 16)
count = lambda m: sum(p.numel() for p in m.parameters())
print(count(nn.Conv2d(16, 16, 3, dilation=1, padding=1)), count(conv)) # 2320 2320
# Yu & Koltun の基本の文脈モジュール(表 1):拡張率 1, 1, 2, 4, 8, 16, 1 の 3×3 と、最後の 1×1
# 論文は入力の周りに余白を足して中間ではパディングしないが、ここでは各層でパディングして大きさを保つ
class ContextModule(nn.Module):
def __init__(self, channels, dilations=(1, 1, 2, 4, 8, 16, 1)):
super().__init__()
layers = []
for l in dilations:
layers += [nn.Conv2d(channels, channels, 3, dilation=l, padding=l), nn.ReLU()]
layers.append(nn.Conv2d(channels, channels, 1)) # 最後の層は ReLU なし
self.body = nn.Sequential(*layers)
self.identity_init()
def identity_init(self):
# 式 4 の恒等写像の初期化:中心の重みだけ、同じ番号のチャネルどうしを 1 にする
for m in self.body:
if isinstance(m, nn.Conv2d):
nn.init.zeros_(m.weight)
nn.init.zeros_(m.bias)
c = m.kernel_size[0] // 2
for i in range(m.out_channels):
m.weight.data[i, i, c, c] = 1.0
def forward(self, x):
return self.body(x)
# 21 クラスのスコアの特徴マップ(例)を入れても、大きさは変わらない
module = ContextModule(21)
scores = torch.relu(torch.randn(1, 21, 64, 64))
print(module(scores).shape) # torch.Size([1, 21, 64, 64])
print(torch.allclose(module(scores), scores)) # 初期状態では入力をそのまま返す:True