python
import numpy as np
import torch
import torch.nn as nn
from scipy import ndimage
"""
U-Net を論文の 2 章・3 章どおりに組む小さな実装。
3×3 畳み込みは余白なし(valid)なので、出力は入力より小さい(572×572 → 388×388)。
多くの実装は padding=1 にして、入力と出力の大きさをそろえる(そのときは切り取りが不要)
"""
def double_conv(c_in, c_out):
"""3×3 畳み込み(余白なし)+ReLU を 2 回"""
return nn.Sequential(
nn.Conv2d(c_in, c_out, 3), nn.ReLU(inplace=True),
nn.Conv2d(c_out, c_out, 3), nn.ReLU(inplace=True),
)
def center_crop(x, size):
"""収縮経路の特徴マップの中央を、拡張経路の大きさに切り取る"""
h, w = x.shape[-2:]
top, left = (h - size[0]) // 2, (w - size[1]) // 2
return x[..., top:top + size[0], left:left + size[1]]
class UNet(nn.Module):
def __init__(self, in_channels=1, num_classes=2, dropout=0.5):
super().__init__()
chs = [64, 128, 256, 512, 1024]
self.down = nn.ModuleList()
c = in_channels
for ch in chs: # 収縮経路:64 → 128 → 256 → 512 → 1024
self.down.append(double_conv(c, ch))
c = ch
self.pool = nn.MaxPool2d(2, stride=2)
self.drop = nn.Dropout2d(dropout) # 収縮経路の最後の Dropout(論文は率を書いていない)
self.up = nn.ModuleList()
self.up_conv = nn.ModuleList()
for ch in reversed(chs[:-1]): # 拡張経路:512 → 256 → 128 → 64
self.up.append(nn.ConvTranspose2d(ch * 2, ch, 2, stride=2)) # 2 倍に広げ、チャネルを半分に
self.up_conv.append(double_conv(ch * 2, ch)) # 連結した後の 2 回の畳み込み
self.head = nn.Conv2d(64, num_classes, 1) # 1×1 畳み込みでクラスの点数へ
for m in self.modules(): # 標準偏差 sqrt(2/N) の正規分布(He の初期化)
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu')
nn.init.zeros_(m.bias)
def forward(self, x): # x: (N, C, 572, 572) など
skips = []
for i, block in enumerate(self.down):
x = block(x)
if i < len(self.down) - 1:
skips.append(x) # 同じ段の特徴を拡張経路に渡す
x = self.pool(x)
x = self.drop(x)
for up, conv, skip in zip(self.up, self.up_conv, reversed(skips)):
x = up(x)
x = torch.cat([center_crop(skip, x.shape[-2:]), x], dim=1) # 切り取って連結
x = conv(x)
return self.head(x) # (N, num_classes, 388, 388)
def weight_map(labels, wc, w0=10.0, sigma=5.0):
"""式 (2) の重みの地図。labels は細胞ごとに 1, 2, ... の番号を付けた整数の地図(背景は 0)、
wc はクラスの頻度の補正の地図。背景の画素で、近い 2 つの細胞の境界までの距離 d1・d2 を使う"""
ids = [i for i in np.unique(labels) if i != 0]
if len(ids) < 2:
return wc
dists = np.stack([ndimage.distance_transform_edt(labels != i) for i in ids]) # 各細胞までの距離
dists.sort(axis=0)
d1, d2 = dists[0], dists[1]
border = w0 * np.exp(-((d1 + d2) ** 2) / (2 * sigma ** 2))
return wc + border * (labels == 0)
model = UNet(in_channels=1, num_classes=2)
criterion = nn.CrossEntropyLoss(reduction='none') # 画素ごとの損失を出し、重みを掛けてから足す
# ミニバッチは 1 枚、モーメンタム 0.99(論文の 3 章)。学習率は論文に書かれていないので例の値
optimizer = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.99)
image = torch.randn(1, 1, 572, 572)
target = torch.randint(0, 2, (1, 388, 388)) # 正解の地図も出力の大きさ(中央の 388×388)にそろえる
w = torch.ones(1, 388, 388) # 実際は weight_map で前もって計算しておく
model.train() # Dropout が効く
loss = (criterion(model(image), target) * w).sum() # E = -Σ w(x) log p_l(x)(x)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval() # Dropout を止める
with torch.no_grad():
pred = model(image).argmax(1) # (1, 388, 388):画素ごとのクラス