python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet101, ResNet101_Weights
"""
DeepLab v3+ を論文の 3.1 節・4.1 節どおりに組む小さな実装(バックボーンは ResNet-101)。
torchvision には DeepLab v3+ の組み込みがないので、ResNet に ASPP とデコーダを足して組む
"""
def conv_bn_relu(c_in, c_out, kernel, dilation=1, separable=False):
pad = 0 if kernel == 1 else dilation
if separable and kernel > 1:
# 拡張分離畳み込み:深さ方向の 3×3(拡張率 r)→ 点方向の 1×1
# (ASPP・デコーダの中のバッチ正規化と ReLU の位置は論文に書かれていない。ここでは各段の後に置く)
return nn.Sequential(
nn.Conv2d(c_in, c_in, kernel, padding=pad, dilation=dilation, groups=c_in, bias=False),
nn.BatchNorm2d(c_in), nn.ReLU(inplace=True),
nn.Conv2d(c_in, c_out, 1, bias=False),
nn.BatchNorm2d(c_out), nn.ReLU(inplace=True),
)
return nn.Sequential(
nn.Conv2d(c_in, c_out, kernel, padding=pad, dilation=dilation, bias=False),
nn.BatchNorm2d(c_out), nn.ReLU(inplace=True),
)
class ASPP(nn.Module):
"""DeepLab v3 の ASPP。出力ストライド 16 では拡張率 (6, 12, 18)"""
def __init__(self, c_in=2048, c_out=256, rates=(6, 12, 18), separable=False):
super().__init__()
self.branches = nn.ModuleList(
[conv_bn_relu(c_in, c_out, 1)] +
[conv_bn_relu(c_in, c_out, 3, dilation=r, separable=separable) for r in rates]
)
self.image_pool = nn.Sequential(nn.AdaptiveAvgPool2d(1), conv_bn_relu(c_in, c_out, 1))
self.project = conv_bn_relu(c_out * (len(rates) + 2), c_out, 1)
def forward(self, x):
outs = [b(x) for b in self.branches]
outs.append(F.interpolate(self.image_pool(x), size=x.shape[-2:], mode='bilinear', align_corners=False))
return self.project(torch.cat(outs, dim=1))
class DeepLabV3Plus(nn.Module):
def __init__(self, num_classes=21, separable=False):
super().__init__()
# 最後の段(layer4)の間引きを拡張畳み込みに置き換え、出力ストライド 16 にする
r = resnet101(weights=ResNet101_Weights.IMAGENET1K_V1, replace_stride_with_dilation=[False, False, True])
self.stem = nn.Sequential(r.conv1, r.bn1, r.relu, r.maxpool)
self.layer1 = r.layer1 # 浅い特徴:画像の 1/4、256 チャネル(論文の Conv2)
self.rest = nn.Sequential(r.layer2, r.layer3, r.layer4) # 画像の 1/16、2048 チャネル
self.aspp = ASPP(separable=separable) # エンコーダの出力:256 チャネル
self.reduce = conv_bn_relu(256, 48, 1) # 浅い特徴を 48 チャネルに減らす
self.refine = nn.Sequential( # 連結した後の 3×3(256)を 2 回
conv_bn_relu(256 + 48, 256, 3, separable=separable),
conv_bn_relu(256, 256, 3, separable=separable),
)
self.classifier = nn.Conv2d(256, num_classes, 1)
def forward(self, x): # x: (N, 3, H, W)
size = x.shape[-2:]
low = self.layer1(self.stem(x)) # 1/4
enc = self.aspp(self.rest(low)) # 1/16
enc = F.interpolate(enc, size=low.shape[-2:], mode='bilinear', align_corners=False) # 4 倍に広げる
h = self.refine(torch.cat([enc, self.reduce(low)], dim=1))
h = self.classifier(h)
return F.interpolate(h, size=size, mode='bilinear', align_corners=False) # さらに 4 倍に広げる
model = DeepLabV3Plus(num_classes=21, separable=True)
criterion = nn.CrossEntropyLoss(ignore_index=255) # VOC の境界などの「無視する画素」は 255
# DeepLab v3 と同じ学習の設定:初期の学習率 0.007、poly(べき 0.9)、513×513 の切り出し
max_iter = 30000 # 回数は例の値
optimizer = torch.optim.SGD(model.parameters(), lr=0.007, momentum=0.9) # モーメンタムは例の値
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda it: (1 - it / max_iter) ** 0.9)
images = torch.randn(2, 3, 513, 513)
masks = torch.randint(0, 21, (2, 513, 513))
model.train() # バッチ正規化はミニバッチの統計を使う
loss = criterion(model(images), masks)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()
model.eval() # バッチ正規化は学習中に貯めた統計を使う
with torch.no_grad():
pred = model(images).argmax(1) # (N, 513, 513):画素ごとのクラス