python コピー
import torch
import torch.nn.functional as F
def inception_score(probs, splits=10):
"""Salimans ら(2016)の IS = exp(E_x KL(p(y|x) || p(y)))。
probs:(画像の枚数, クラスの数) の p(y|x)(Inception モデルの softmax の出力)。
よく使われる実装に合わせ、画像を splits 組に分けて組ごとに IS を求め、平均と標準偏差を返す。"""
scores = []
for part in probs.chunk(splits, dim=0):
py = part.mean(dim=0, keepdim=True) # 周辺分布 p(y) の推定
kl = (part * (torch.log(part + 1e-12) - torch.log(py + 1e-12))).sum(dim=1)
scores.append(torch.exp(kl.mean()))
scores = torch.stack(scores)
return scores.mean(), scores.std()
# p(y|x) を求める:ImageNet で学習した Inception-v3(torchvision)。評価なので eval() にする
from torchvision.models import inception_v3, Inception_V3_Weights
net = inception_v3(weights=Inception_V3_Weights.IMAGENET1K_V1).eval()
generator.eval()
probs = []
with torch.no_grad():
for _ in range(num_batches): # 論文では 50,000 枚
z = torch.randn(batch_size, latent_dim)
x = generator(z) # 例:[-1, 1] の (B, 3, H, W)
x = F.interpolate((x + 1) / 2, size=(299, 299), mode="bilinear", align_corners=False)
x = (x - torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)) / torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
probs.append(F.softmax(net(x), dim=1))
mean, std = inception_score(torch.cat(probs))
# torchmetrics の場合(torch-fidelity が必要)。元の TensorFlow 版に合わせた Inception を使い、
# normalize=False なら uint8 の [0, 255] の画像を受け取る。compute() は (平均, 標準偏差) を返す
from torchmetrics.image.inception import InceptionScore
metric = InceptionScore(splits=10, normalize=False)
metric.update(fake_images_uint8) # (B, 3, H, W)、uint8
print(metric.compute())