python コピー
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class AngleLinear(nn.Module):
"""SphereFace の分類の層:重みを長さ 1 にそろえ、バイアスは持たない"""
def __init__(self, in_features, num_classes):
super().__init__()
self.weight = nn.Parameter(torch.empty(num_classes, in_features))
nn.init.xavier_uniform_(self.weight)
def forward(self, x):
w = F.normalize(self.weight, dim=1) # ‖W_j‖ = 1
cos = F.linear(F.normalize(x, dim=1), w) # cos θ_j
return cos.clamp(-1 + 1e-7, 1 - 1e-7), x.norm(dim=1, keepdim=True)
def psi(theta, m):
"""式 (7):ψ(θ) = (−1)^k cos(mθ) − 2k、θ ∈ [kπ/m, (k+1)π/m]"""
k = torch.floor(theta * m / math.pi).clamp(max=m - 1)
sign = 1.0 - 2.0 * torch.remainder(k, 2) # (−1)^k
return sign * torch.cos(m * theta) - 2.0 * k
class ASoftmaxLoss(nn.Module):
def __init__(self, m=4):
super().__init__()
self.m = m
def forward(self, cos, x_norm, labels, lam=0.0):
# 論文は倍角の公式で cos(mθ) を計算する。ここでは θ = arccos(cos θ) から求める(同じ値)
cos_t = cos.gather(1, labels[:, None])
theta_t = torch.acos(cos_t)
# 付録 G の焼きなまし:(λ cos θ + ψ(θ)) / (1 + λ)。λ が大きいほどふつうのソフトマックスに近い
target = (lam * cos_t + psi(theta_t, self.m)) / (1.0 + lam)
logits = cos.scatter(1, labels[:, None], target) * x_norm # 特徴の長さ ‖x‖ を掛ける
return F.cross_entropy(logits, labels)
# 特徴を出すネットワーク(最後の層の後に ReLU を置かない)と、分類の層
backbone = nn.Sequential(nn.Flatten(), nn.Linear(3 * 112 * 96, 512), nn.PReLU(), nn.Linear(512, 512))
head = AngleLinear(512, num_classes=10575)
criterion = ASoftmaxLoss(m=4)
optimizer = torch.optim.SGD(list(backbone.parameters()) + list(head.parameters()), lr=0.1, momentum=0.9)
backbone.train()
for it in range(3):
images = torch.randn(8, 3, 112, 96)
labels = torch.randint(0, 10575, (8,))
# λ を大きな値から 5 まで下げる(論文は減らし方の式を書いていない。これは一例)
lam = max(5.0, 1000.0 / (1 + 0.1 * it))
cos, x_norm = head(backbone(images))
loss = criterion(cos, x_norm, labels, lam=lam)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# テスト:分類の層は使わず、特徴のコサイン類似度で照合する
backbone.eval()
with torch.no_grad():
a, b = backbone(torch.randn(1, 3, 112, 96)), backbone(torch.randn(1, 3, 112, 96))
score = F.cosine_similarity(a, b) # しきい値より大きければ同じ人と判定