python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops import batched_nms
'''
YOLO(最初の版)を論文の図 3 と式(3)どおりに組む小さな実装。torchvision には YOLO の組み込みのモデルはない。
出力は (バッチ, 7, 7, 30)。各マスの 30 個は、枠 1 (x, y, √w, √h, 信頼度)・枠 2 (同じ)・20 クラスの確率
'''
S, B, C = 7, 2, 20 # マスの数、マスごとの枠の数、クラスの数(PASCAL VOC)
def conv(c_in, c_out, k, stride=1):
return [nn.Conv2d(c_in, c_out, k, stride, k // 2), nn.LeakyReLU(0.1)] # 活性化は傾き 0.1 の Leaky ReLU(式 2)
class YOLOv1(nn.Module):
def __init__(self):
super().__init__()
pool = lambda: nn.MaxPool2d(2, 2)
layers = conv(3, 64, 7, 2) + [pool()] # 448 → 112
layers += conv(64, 192, 3) + [pool()] # → 56
layers += conv(192, 128, 1) + conv(128, 256, 3) + conv(256, 256, 1) + conv(256, 512, 3) + [pool()] # → 28
for _ in range(4):
layers += conv(512, 256, 1) + conv(256, 512, 3)
layers += conv(512, 512, 1) + conv(512, 1024, 3) + [pool()] # → 14
for _ in range(2):
layers += conv(1024, 512, 1) + conv(512, 1024, 3)
layers += conv(1024, 1024, 3) + conv(1024, 1024, 3, 2) # → 7
layers += conv(1024, 1024, 3) + conv(1024, 1024, 3) # 畳み込みは全部で 24 層
self.features = nn.Sequential(*layers)
self.head = nn.Sequential(
nn.Flatten(),
nn.Linear(1024 * S * S, 4096), nn.LeakyReLU(0.1),
nn.Dropout(0.5), # 1 つ目の全結合層の後ろ(model.eval() で止まる)
nn.Linear(4096, S * S * (B * 5 + C)), # 最後の層は線形
)
def forward(self, x): # x: (N, 3, 448, 448)
return self.head(self.features(x)).view(-1, S, S, B * 5 + C)
def grid_offsets(device, dtype):
g = torch.arange(S, device=device, dtype=dtype)
gy, gx = torch.meshgrid(g, g, indexing='ij')
return gx, gy
def iou(a, b): # (..., 4) = (cx, cy, w, h)、画像に対する割合
a1, a2 = a[..., :2] - a[..., 2:] / 2, a[..., :2] + a[..., 2:] / 2
b1, b2 = b[..., :2] - b[..., 2:] / 2, b[..., :2] + b[..., 2:] / 2
inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(min=0).prod(-1)
return inter / (a[..., 2:].prod(-1) + b[..., 2:].prod(-1) - inter + 1e-9)
def yolo_loss(pred, target, lambda_coord=5.0, lambda_noobj=0.5):
'''
pred: (N, S, S, B*5 + C)
target: (N, S, S, 5 + C) = (x, y, w, h, 物体の有無) と one-hot のクラス。
x, y はマスの中の位置(0〜1)、w, h は画像に対する割合。物体の中心が入るマスだけ値を持つ
'''
boxes = pred[..., :B * 5].view(*pred.shape[:3], B, 5)
bx, by, bw, bh, conf = boxes.unbind(-1) # bw, bh は √w, √h を予測している
tx, ty, tw, th, obj = target[..., :5].unbind(-1)
gx, gy = grid_offsets(pred.device, pred.dtype)
# 受け持つ枠(1^obj_ij):マスの B 個の枠のうち、正解との IoU が最も大きい枠
pred_img = torch.stack([(bx + gx[..., None]) / S, (by + gy[..., None]) / S, bw ** 2, bh ** 2], -1)
true_img = torch.stack([(tx + gx) / S, (ty + gy) / S, tw, th], -1)[..., None, :]
ious = iou(pred_img, true_img) # (N, S, S, B)
resp = F.one_hot(ious.argmax(-1), B).to(pred.dtype) * obj[..., None]
noobj = 1 - resp
coord = (bx - tx[..., None]) ** 2 + (by - ty[..., None]) ** 2 \
+ (bw - tw.sqrt()[..., None]) ** 2 + (bh - th.sqrt()[..., None]) ** 2
loss = lambda_coord * (resp * coord).sum() # 座標(幅と高さは平方根で比べる)
loss = loss + (resp * (conf - ious.detach()) ** 2).sum() # 受け持つ枠の信頼度は IoU に近づける
loss = loss + lambda_noobj * (noobj * conf ** 2).sum() # 受け持たない枠の信頼度は 0 に近づける
loss = loss + (obj[..., None] * (pred[..., B * 5:] - target[..., 5:]) ** 2).sum() # クラスは物体のあるマスだけ
return loss / pred.shape[0]
@torch.no_grad()
def decode(pred, score_thresh=0.2, iou_thresh=0.5):
'''1 枚分の (S, S, B*5 + C) から検出結果を作る。閾値の値は論文に書かれていないので例'''
boxes = pred[..., :B * 5].view(S, S, B, 5)
gx, gy = grid_offsets(pred.device, pred.dtype)
cx = (boxes[..., 0] + gx[..., None]) / S
cy = (boxes[..., 1] + gy[..., None]) / S
w, h = boxes[..., 2] ** 2, boxes[..., 3] ** 2
xyxy = torch.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], -1).view(-1, 4)
# クラスごとの点数 = Pr(Class | Object) × 信頼度(式 1)
scores = (pred[..., None, B * 5:] * boxes[..., 4:5]).view(-1, C) # (98, 20)
best, labels = scores.max(-1)
keep = best > score_thresh
xyxy, best, labels = xyxy[keep], best[keep], labels[keep]
keep = batched_nms(xyxy, best, labels, iou_thresh) # クラスごとの非最大値抑制
return xyxy[keep], labels[keep], best[keep]
model = YOLOv1()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3, momentum=0.9, weight_decay=0.0005)
# 学習率:最初の数エポックで 1e-3 から 1e-2 へ上げ、1e-2 で 75、1e-3 で 30、1e-4 で 30 エポック(論文 2.2 節)
def lr_factor(epoch, warmup=5):
if epoch < warmup:
return 10 ** (epoch / warmup) # 1 → 10 倍(1e-3 → 1e-2)
epoch -= warmup
return 10.0 if epoch < 75 else 1.0 if epoch < 105 else 0.1
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_factor)
# 1 ステップの例(データの読み込みとデータ拡張は省略。バッチは論文では 64)
images = torch.randn(2, 3, 448, 448)
target = torch.zeros(2, S, S, 5 + C)
target[0, 3, 3, :5] = torch.tensor([0.4, 0.6, 0.3, 0.5, 1.0]) # 中央のマスに物体が 1 つ
target[0, 3, 3, 5 + 11] = 1.0 # クラス 11(dog)
model.train()
loss = yolo_loss(model(images), target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval() # Dropout を止める
boxes, labels, scores = decode(model(images[:1])[0])