Evaluating generative models: likelihood, FID, precision and recall
Study the limits of likelihood, including its mismatch with sample quality and the out-of-distribution paradox. Derive and compare Inception Score, FID, MMD, KID and precision-coverage metrics, their biases and feature-extractor dependence, then build an evaluation harness.
After this lesson you can
- Explain with examples why log-likelihood and sample quality can disagree.
- Implement FID, KID and precision-coverage from scratch and validate them with known Gaussians.
- Prove that the off-diagonal MMD² estimator is unbiased.
- Quantify FID bias as sample size changes and choose an evaluation protocol.
- Distinguish mode collapse from low fidelity using precision and coverage.
- Explain the out-of-distribution likelihood paradox using typicality.
Before you start
- 19Bits per dimensionImportance-sampled likelihood estimationMode collapseTruncation trick
- 04Wasserstein distance between Gaussians
- 13Reproducing kernel Hilbert spaceReproducing property
- 07Typical setAsymptotic equipartition property
- 05Bias of an estimatorBootstrap percentile and basic intervals
- 16Transfer learning in visionLayer-wise feature transferability
One score cannot answer every question
A generator may memorize a few convincing images or cover many different images with artifacts. Another may assign good held-out likelihood while producing visually poor samples. Before choosing a number, decide whether to measure compression, sample fidelity, coverage, correspondence to a condition or out-of-distribution detection.
For a discrete image with dimensions, bits per dimension are . A lower value means higher probability under that model and representation; comparison requires the same quantization, preprocessing and convention. A variational bound or importance estimate is not automatically exact log-likelihood. Theis, van den Oord and Bethge show likelihood and visual fidelity can vary largely independently in high dimensions. An implicit GAN alone need not provide evaluable density for bpd.
Table 1 of Ho, Jain and Abbeel gives a CIFAR-10 comparison: Gated PixelCNN reports 3.03 bpd and FID 65.93; diffusion with a variational objective reports an NLL bound of 3.70 bpd and FID 13.51. With the simplified objective, diffusion obtains a bound of 3.75 and FID 3.17. The paper calculates the latter FID against the training set and obtains 5.24 against test. The best reported bound does not coincide with lowest FID; moreover a bound alone cannot rank exact NLLs. Read numbers with their reference set and protocol, not as a universal ranking.
For example, Theis and colleagues consider 8-bit pixels with integer values 0 to 255 and add uniform noise in to each component for dequantization. Expected continuous log-density over that noise lower-bounds discrete log-probability obtained by integrating density in each cell; Jensen explains the inequality. Distinguish continuous density, bound and discrete probability before comparing bpd.
High density does not imply a typical image
In the experiment by Nalisnick and colleagues, Glow trained on Fashion-MNIST obtained mean 2.958 bits per dimension on Fashion-MNIST test and 1.833 on MNIST test; the paper also shows the phenomenon for PixelCNN and VAE. These are results of those models and protocol, not figures for every later training run. Behavior may also be asymmetric when datasets are swapped.
The typical set helps explain why density and mass differ. For , density is maximized at the origin, but : in high dimensions mass concentrates far from the origin in a region with much larger volume. A high-density point can belong to a region with little total mass. This observation does not explain every OOD case or replace detection evaluation; state the alternative, threshold and errors.
Concentration can be checked without images: has variance because coordinates are independent and each squared standard normal has variance two. By Chebyshev, . For fixed , that bound approaches zero as grows. Maximum density remains at zero, but typical norm scales as .
The asymptotic equipartition property justifies concentration of mean surprise for i.i.d. observations under its assumptions. A typicality test is two-sided: examples with either unusually small or unusually large mean surprise can fall outside the typical region. For batch , compare the mean of with a reference estimated on in-domain data and calibrate the threshold on independent validation. Nalisnick and colleagues, Table 3, report for Fashion-MNIST-trained Glow and batches of ten an OOD fraction of 1.00 for MNIST and 0.02 for in-domain data with their data-based estimator. This belongs to that protocol and batch size, not a per-image guarantee. Serrà and colleagues compare likelihood with an estimate of input complexity; both need calibration and can fail against unforeseen alternatives.
Inception Score: diversity of predicted labels
The expected KL is mutual information under the joint distribution of samples and classifier. A confident classifier per image and diverse marginal labels increase the score. With classes, and thus ; the maximum requires deterministic predictions and uniform marginal labels. This requires neither within-class diversity nor comparison with real data. A generator repeating one convincing image per class can score highly. The score also depends on classifier and the protocol of Salimans and colleagues.
FID: a distance between feature Gaussians
Covariances are symmetric positive semidefinite. The symmetric root of avoids treating nonsymmetric product as symmetric; this is the transport between Gaussians formula. The distance compares only first and second statistics in feature space: different non-Gaussian distributions can share them and have zero population FID. Heusel and colleagues introduce FID for generative-model comparison.
Finite-sample FID estimator bias depends on model and size; two sets from the same distribution generally do not give zero. Report example count, real split, extractor and weights, scaling, resizing and compression. Parmar and colleagues document resizing and compression differences. An ImageNet-feature FID for MNIST is not an absolute digit-quality measure. Selecting a checkpoint on the set used for reporting also introduces optimistic selection: reserve validation and test.
Table 1 of Parmar compares the same real FFHQ set resized from 1024 to 299 pixels: relative to PIL bicubic, PIL bilinear yields FID 0.64 and TensorFlow bilinear 4.34. The change comes from preprocessing the same images, not a generator improvement or deterioration.
In the figure simulation with 32-dimensional Gaussian features and identical distributions, population FID is zero. The mean of 1024 repetitions falls from 18.91 with 32 samples per set to 9.36 with 64, 4.66 with 128 and 2.32 with 256. In this particular family it approximately halves when sample size doubles; do not extrapolate that as an exact law for all distributions or extractors. The initial bars are bootstrap intervals for the mean of repetitions, not for one real and generated set.
MMD and KID
The reproducing property evaluates RKHS functions by inner product with ; MMD compares the means of these elements when they exist. Zero MMD does not imply equal distributions unless the kernel additionally is characteristic.
For , the off-diagonal estimator is
Each off-diagonal within-sample term has the distribution of two independent observations; by linearity, the estimator is unbiased for a fixed kernel and independent i.i.d. samples when expectations exist. It can be negative in finite samples even though population distance is nonnegative. Gretton and colleagues develop this test.
Kernel Inception Distance applies unbiased MMD² to Inception features with a polynomial kernel, for example ; Bińkowski and colleagues propose it for generative models. Unbiasedness concerns population MMD² for fixed extractor and kernel; finite samples still have uncertainty. For a cubic kernel, finite sixth-order moments suffice for the relevant variances to exist. A polynomial kernel need not distinguish every different distribution; an estimate near zero does not prove equality.
With few samples, KID avoids FID estimation bias and allows negative values; this does not guarantee lower error in one run because variance can be large. With 1000 images per group, report estimator and uncertainty, keep extractor, preprocessing and size fixed, and include fidelity and coverage metrics. Different-size comparisons require characterizing bias rather than attributing every difference to the generator.
Separating fidelity and coverage
A model with mode collapse can have high precision and low recall; diffuse off-data samples can have low precision. These fractions depend on feature space, , sample sizes and outliers. Kynkäänniemi and colleagues describe this variant; do not confuse recall with other metrics called coverage. For example, Naeem and colleagues define coverage as the fraction of real centers with a generated sample inside their own ball; density averages the number of real balls containing each generated sample and divides by . These definitions differ.
Kynkäänniemi and colleagues use 50000 samples per set and by default; in their StyleGAN comparison on FFHQ, reducing truncation increases coverage at the expense of precision. Those results do not automatically determine the behavior of a small trial in another domain.
The PRD curve of Sajjadi and colleagues describes feasible precision-recall pairs between discretized feature distributions as their trade-off varies. To summarize pair use , set to zero if both are zero; a curve can report the maximum. weights precision more and weights recall more. The gallery’s Choi figures are these PRD summaries, not the neighboring-ball fractions in the next figure.
Inception is not the only feature extractor. Stein and colleagues compare 17 metrics and 9 extractors, observe that usual metrics poorly reflect human-judged diffusion realism, and highlight DINOv2-ViT-L/14 as a richer representation in their study. This is transfer of learned features: their utility in the new domain must be evaluated. Changing extractor changes the metric: do not directly compare Fréchet computed with DINOv2 and Inception.
For text-to-image, an alignment measure encodes image and textual condition with CLIP and compares vectors by cosine. Hessel and colleagues’ CLIPScore for image captioning uses and averages over pairs; report model, text and scale when adapting it to generated images. The score alone does not measure coverage, diversity or visual fidelity and can depend on encoder biases. Human evaluation needs declared instructions, sampling and aggregation and does not automatically answer coverage or memorization.
The gallery includes a short conditional truncation trick trial: with 128 images per group and , kNN precision and recall are both zero; with they are 0.523 and 0.438, and with they are 0.555 and 0.563. The first case repeats one image and produces degenerate generated balls. These values do not show the expected trade-off and do not refute Kynkäänniemi’s study: they use different data, conditioning and size, with high uncertainty and limited covariance rank. Increase samples and vary seeds before concluding about truncation.
A useful protocol fixes validation and test sets, sample count, extraction and preprocessing, seeds, metric and selection criterion before training. Report distribution across runs and, where appropriate, percentile bootstrap intervals; a conditional bootstrap over fixed data does not automatically include retraining variability. For reuse, save metadata and each sample’s origin alongside figures.
Lab: metrics from scratch
Begin with low-dimensional features so every operation can be checked. A symmetric matrix root is obtained by diagonalizing covariance. Clip only negative eigenvalues compatible with stated numerical error; a clearly negative value signals an invalid covariance. Off-diagonal MMD requires at least two examples per set.
import numpy as np
def sqrt_psd(matrix, tol=1e-9):
matrix = np.asarray(matrix, dtype=float)
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
raise ValueError('se necesita una matriz cuadrada')
if not np.allclose(matrix, matrix.T, atol=tol, rtol=tol):
raise ValueError('la matriz debe ser simétrica')
matrix = (matrix + matrix.T) / 2
values, vectors = np.linalg.eigh(matrix)
scale = max(1.0, float(np.max(np.abs(values))))
if values.min() < -tol * scale:
raise ValueError('la matriz no es semidefinida positiva')
return (vectors * np.sqrt(np.maximum(values, 0))) @ vectors.T
def frechet(mu1, cov1, mu2, cov2):
mu1, mu2 = np.asarray(mu1), np.asarray(mu2)
a = sqrt_psd(cov1)
sqrt_psd(cov2) # Valida también la segunda covarianza.
middle = a @ cov2 @ a
result = (np.sum((mu1-mu2)**2) + np.trace(cov1) + np.trace(cov2)
- 2 * np.trace(sqrt_psd((middle+middle.T)/2)))
scale = max(1.0, float(np.sum((mu1-mu2)**2) + abs(np.trace(cov1)) + abs(np.trace(cov2))))
if result < -1e-8 * scale:
raise ValueError('la distancia es negativa más allá de la tolerancia')
return max(0.0, float(result)) # Solo elimina ruido numérico del resultado válido.
def mmd_unbiased(x, y):
n, m = len(x), len(y)
if n < 2 or m < 2:
raise ValueError('se necesitan al menos dos puntos por conjunto')
dimension = x.shape[1]
kxx = (x @ x.T / dimension + 1)**3
kyy = (y @ y.T / dimension + 1)**3
kxy = (x @ y.T / dimension + 1)**3
return ((kxx.sum()-np.trace(kxx))/(n*(n-1))
+ (kyy.sum()-np.trace(kyy))/(m*(m-1)) - 2*kxy.mean())
zero = np.zeros(4)
identity = np.eye(4)
print('FID exacto de N(0,I) y N(0,4I) en 4 dimensiones:',
round(frechet(zero, identity, zero, 4*identity), 6))
print('FID de una gaussiana consigo misma:', round(frechet(zero, identity, zero, identity), 6))
rng = np.random.default_rng(1911)
x = rng.normal(size=(96, 4))
y = rng.normal(size=(96, 4))
print('FID estimado con muestras independientes:', round(frechet(x.mean(0), np.cov(x, rowvar=False), y.mean(0), np.cov(y, rowvar=False)), 5))
print('MMD² polinómica insesgada:', round(float(mmd_unbiased(x, y)), 5))For neighbor balls, do not count the center as its own neighbor. With duplicates, other distinct points may be at distance zero and this must be defined. The next algorithm computes improved precision and recall in a plane: its distance matrix needs quadratic memory, so large sets require block searches or neighbor indices.
def precision_recall(real, generated, k=3):
real, generated = np.asarray(real), np.asarray(generated)
if k < 1 or len(real) <= k or len(generated) <= k:
raise ValueError('cada conjunto debe tener más de k elementos')
def distances(a, b):
return np.sqrt(np.sum((a[:, None, :] - b[None, :, :])**2, axis=2))
rr, gg, rg = distances(real, real), distances(generated, generated), distances(real, generated)
np.fill_diagonal(rr, np.inf)
np.fill_diagonal(gg, np.inf)
radii_r = np.partition(rr, k-1, axis=1)[:, k-1]
radii_g = np.partition(gg, k-1, axis=1)[:, k-1]
precision = (rg <= radii_r[:, None]).any(axis=0).mean()
recall = (rg <= radii_g[None, :]).any(axis=1).mean()
return float(precision), float(recall)
real = rng.normal(size=(100, 2))
same = real.copy()
shifted = real + np.array([10., 0.])
print('Mismo conjunto:', precision_recall(real, same))
print('Conjunto desplazado:', precision_recall(real, shifted))The first case’s exact match tests code, not generalization: using identical samples as real and generated can hide memorization. In the second case sets share no balls for this sample and displacement; this does not establish a property of all shifted Gaussians.
Local lab: evaluation harness on Fashion-MNIST
Install torch, torchvision, scipy and clean-fid==0.1.35. First run lesson 8’s Fashion lab, which saves ./dcgan-results/fashion/dcgan.pt by default. If saved elsewhere, set ORYON_DCGAN_CHECKPOINT. ORYON_FASHION_ROOT selects where to store or find Fashion-MNIST and ORYON_EVAL_OUTPUT changes the output folder.
The classifier trains only on Fashion-MNIST training data and returns 64-dimensional features; evaluation uses separate test data and new samples from the earlier generator. Because the extractor is custom, the resulting distance is Fréchet in Fashion features, not standard Inception FID, and the cubic kernel uses those same features rather than the standard KID protocol. Comparison with clean-fid checks formulas on identical vectors, not equivalence of preprocessing or extractors. Classifier accuracy helps judge usefulness but does not guarantee perceptual quality is well represented in its space.
The full protocol uses 1024 images per set, 5 classifier epochs, 3 neighbors and 100 bootstrap replicates. Features, a seeded report and classifier are saved. Intervals quantify only resampling of these sets with fixed extractor and generator: they do not capture variation across training runs or eliminate Fréchet bias. For precision and coverage, bootstrap duplicates alter neighbor radii; interpret intervals as procedure-sensitive diagnostics, not exact guarantees. Repeat comparison with the same extractor, preprocessing, size and seeds, and use test data independent of checkpoint selection.
ORYON_QUICK=1 uses 256 classifier-training images, 64 for each evaluation set, one epoch and 12 replicates. It checks the workflow and does not demonstrate model quality or produce publishable metrics. To reuse the harness, save the first part’s functions in a Python module and pass feature matrices extracted under a fixed protocol.
"""Métricas de muestras en un espacio de características declarado.
La distancia de Fréchet solo se llama FID cuando las características y el
preprocesado corresponden al protocolo Inception indicado.
"""
import numpy as np
from scipy.spatial.distance import cdist
def _features(x):
x = np.asarray(x, dtype=np.float64)
if x.ndim != 2 or len(x) < 2 or x.shape[1] == 0 or not np.isfinite(x).all():
raise ValueError('Se necesitan al menos dos vectores finitos por conjunto')
return x
def frechet_gaussians(mean1, covariance1, mean2, covariance2):
mean1, mean2 = np.asarray(mean1, dtype=np.float64), np.asarray(mean2, dtype=np.float64)
a = np.asarray(covariance1, dtype=np.float64)
b = np.asarray(covariance2, dtype=np.float64)
if mean1.ndim != 1 or mean1.size == 0 or mean1.shape != mean2.shape or a.shape != b.shape or a.shape != (len(mean1), len(mean1)):
raise ValueError('Dimensiones incompatibles')
if not all(np.isfinite(x).all() for x in (mean1, mean2, a, b)):
raise ValueError('Las medias y covarianzas deben ser finitas')
if not np.allclose(a, a.T, rtol=1e-9, atol=1e-9) or not np.allclose(b, b.T, rtol=1e-9, atol=1e-9):
raise ValueError('Las covarianzas deben ser simétricas')
a, b = (a + a.T) / 2, (b + b.T) / 2
values, vectors = np.linalg.eigh(a)
values_b = np.linalg.eigvalsh(b)
if values.min() < -1e-9 * max(1.0, np.abs(values).max()) or values_b.min() < -1e-9 * max(1.0, np.abs(values_b).max()):
raise ValueError('La covarianza no es semidefinida positiva')
root_a = (vectors * np.sqrt(np.maximum(values, 0))) @ vectors.T
middle = root_a @ b @ root_a
eigenvalues = np.linalg.eigvalsh((middle + middle.T) / 2)
if eigenvalues.min() < -1e-9 * max(1.0, np.abs(eigenvalues).max()):
raise ValueError('El producto de covarianzas no es semidefinido positivo')
result = float(np.sum((mean1 - mean2) ** 2) + np.trace(a) + np.trace(b)
- 2 * np.sqrt(np.maximum(eigenvalues, 0)).sum())
scale = max(1.0, np.sum((mean1 - mean2) ** 2) + abs(np.trace(a)) + abs(np.trace(b)))
if result < -1e-8 * scale:
raise ValueError('La distancia es negativa más allá de la tolerancia')
return max(0.0, result)
def frechet_features(real, generated):
real, generated = _features(real), _features(generated)
if real.shape[1] != generated.shape[1]:
raise ValueError('Las características deben tener la misma dimensión')
return frechet_gaussians(real.mean(0), np.atleast_2d(np.cov(real, rowvar=False)),
generated.mean(0), np.atleast_2d(np.cov(generated, rowvar=False)))
def polynomial_mmd2(real, generated):
real, generated = _features(real), _features(generated)
if real.shape[1] != generated.shape[1]:
raise ValueError('Las características deben tener la misma dimensión')
dim = real.shape[1]
a = (real @ real.T / dim + 1) ** 3
b = (generated @ generated.T / dim + 1) ** 3
cross = (real @ generated.T / dim + 1) ** 3
m, n = len(real), len(generated)
return float((a.sum() - np.trace(a)) / (m * (m - 1)) +
(b.sum() - np.trace(b)) / (n * (n - 1)) - 2 * cross.mean())
def precision_recall(real, generated, k=3):
real, generated = _features(real), _features(generated)
if real.shape[1] != generated.shape[1] or k < 1 or k >= min(len(real), len(generated)):
raise ValueError('Dimensiones o número de vecinos incompatibles')
def radii(x):
distance = cdist(x, x, metric='sqeuclidean')
np.fill_diagonal(distance, np.inf)
return np.partition(distance, k - 1, axis=1)[:, k - 1]
r_real, r_gen = radii(real), radii(generated)
distance = cdist(real, generated, metric='sqeuclidean')
precision = np.any(distance <= r_real[:, None], axis=0).mean()
recall = np.any(distance <= r_gen[None, :], axis=1).mean()
return float(precision), float(recall)
def evaluate(real, generated, k=3, repeats=100, seed=13):
real, generated = _features(real), _features(generated)
if repeats < 1:
raise ValueError('repeats debe ser positivo')
def metrics(x, y):
p, r = precision_recall(x, y, k)
return np.array([frechet_features(x, y), polynomial_mmd2(x, y), p, r])
observed = metrics(real, generated)
rng = np.random.default_rng(seed)
bootstrap = np.stack([metrics(real[rng.integers(len(real), size=len(real))],
generated[rng.integers(len(generated), size=len(generated))])
for _ in range(repeats)])
lower, upper = np.percentile(bootstrap, [2.5, 97.5], axis=0)
return {name: {'value': float(value), 'bootstrap_95': [float(low), float(high)]}
for name, value, low, high in zip(('frechet', 'mmd2_poly', 'precision', 'recall'),
observed, lower, upper)}
import json
import inspect
import os
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
import cleanfid.fid as clean_reference
quick = os.environ.get('ORYON_QUICK') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(2)
output = Path(os.environ.get('ORYON_EVAL_OUTPUT', './eval-generative-results'))
output.mkdir(parents=True, exist_ok=True)
checkpoint_path = Path(os.environ.get('ORYON_DCGAN_CHECKPOINT', './dcgan-results/fashion/dcgan.pt'))
if not checkpoint_path.is_file():
raise FileNotFoundError('Ejecuta el laboratorio Fashion de m19-l08 o define ORYON_DCGAN_CHECKPOINT')
# Compara las fórmulas, con las mismas características, no el extractor ni el redimensionado.
rng = np.random.default_rng(34)
sample_a = rng.normal(size=(100, 8))
sample_b = rng.normal(loc=0.3, scale=1.2, size=(100, 8))
our_frechet = frechet_features(sample_a, sample_b)
# clean-fid 0.1.35 usa disp=False, retirado en versiones recientes de SciPy.
# El adaptador conserva la raíz de SciPy y solo reconstruye la tupla histórica.
original_sqrtm = clean_reference.linalg.sqrtm
if 'disp' not in inspect.signature(original_sqrtm).parameters:
def compatible_sqrtm(matrix, disp=True):
result = original_sqrtm(matrix)
return result if disp else (result, None)
clean_reference.linalg.sqrtm = compatible_sqrtm
try:
ref_frechet = clean_reference.frechet_distance(
sample_a.mean(0), np.cov(sample_a, rowvar=False),
sample_b.mean(0), np.cov(sample_b, rowvar=False))
finally:
clean_reference.linalg.sqrtm = original_sqrtm
our_kid = polynomial_mmd2(sample_a, sample_b)
ref_kid = clean_reference.kernel_distance(sample_a, sample_b, num_subsets=1, max_subset_size=100)
assert np.allclose(our_frechet, ref_frechet, atol=1e-8, rtol=1e-8)
assert np.allclose(our_kid, ref_kid, atol=1e-10, rtol=1e-10)
assert np.allclose(frechet_gaussians(np.zeros(8), np.eye(8), np.ones(8), 4 * np.eye(8)), 16)
assert precision_recall(sample_a, sample_a, k=3) == (1.0, 1.0)
print('Fórmulas verificadas con clean-fid y gaussianas:', our_frechet, our_kid)
torch.manual_seed(101)
if device.type == 'cuda':
torch.cuda.manual_seed_all(101)
root = Path(os.environ.get('ORYON_FASHION_ROOT', './data'))
transform = transforms.Compose([transforms.Resize((64, 64)), transforms.ToTensor()])
train_all = datasets.FashionMNIST(root, train=True, download=True, transform=transform)
test_all = datasets.FashionMNIST(root, train=False, download=True, transform=transform)
train = Subset(train_all, range(256)) if quick else train_all
n_samples = 64 if quick else 1024
test = Subset(test_all, range(n_samples))
batch_size = 32 if quick else 128
epochs = 1 if quick else 5
loader = DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=0,
generator=torch.Generator().manual_seed(102))
test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)
class FashionFeatures(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d((4, 4)), nn.Flatten())
self.embedding = nn.Sequential(nn.Linear(32 * 4 * 4, 64), nn.ReLU())
self.classifier = nn.Linear(64, 10)
def features(self, images):
# Reales y generadas parten ambas de 64×64 y usan el mismo redimensionado.
x = F.interpolate(images, size=(28, 28), mode='bilinear', align_corners=False, antialias=True)
return self.embedding(self.conv(x))
def forward(self, images):
return self.classifier(self.features(images))
extractor = FashionFeatures().to(device)
optimizer = torch.optim.Adam(extractor.parameters(), lr=0.001)
for epoch in range(epochs):
extractor.train()
for images, labels in loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad(set_to_none=True)
class_loss = F.cross_entropy(extractor(images), labels)
class_loss.backward()
optimizer.step()
# Es la arquitectura exacta de la celda DCGAN Fashion de m19-l08.
class PreviousGenerator(nn.Module):
def __init__(self, latent, width):
super().__init__()
self.net = nn.Sequential(
nn.ConvTranspose2d(latent, width * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(width * 8), nn.ReLU(True),
nn.ConvTranspose2d(width * 8, width * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(width * 4), nn.ReLU(True),
nn.ConvTranspose2d(width * 4, width * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(width * 2), nn.ReLU(True),
nn.ConvTranspose2d(width * 2, width, 4, 2, 1, bias=False),
nn.BatchNorm2d(width), nn.ReLU(True),
nn.ConvTranspose2d(width, 1, 4, 2, 1, bias=False), nn.Tanh(),
)
def forward(self, z):
return self.net(z)
checkpoint = torch.load(checkpoint_path, map_location='cpu', weights_only=True)
if checkpoint['channels'] != 1:
raise ValueError('Se necesita el checkpoint Fashion de m19-l08, con un canal')
generator = PreviousGenerator(checkpoint['latent'], checkpoint['width']).to(device)
generator.load_state_dict(checkpoint['generador'])
generator.eval()
extractor.eval()
real_batches, fake_batches = [], []
correct = 0
noise_rng = torch.Generator().manual_seed(103)
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
features = extractor.features(images)
correct += (extractor.classifier(features).argmax(1) == labels).sum().item()
real_batches.append(features.cpu().numpy())
z = torch.randn(len(images), checkpoint['latent'], 1, 1, generator=noise_rng).to(device)
fake = ((generator(z) + 1) / 2).clamp(0, 1)
fake_batches.append(extractor.features(fake).cpu().numpy())
real_features, fake_features = np.concatenate(real_batches), np.concatenate(fake_batches)
accuracy = correct / n_samples
metrics = evaluate(real_features, fake_features, k=3, repeats=12 if quick else 100, seed=104)
report = {'extractor': 'FashionFeatures, 64 dimensiones; no Inception',
'dataset_real': 'Fashion-MNIST test', 'checkpoint': str(checkpoint_path),
'samples_per_set': n_samples, 'k': 3, 'classifier_epochs': epochs,
'classifier_test_accuracy': accuracy, 'metrics': metrics,
'resize': 'ambos 64x64 a 28x28, bilinear con antialias',
'quick': quick, 'seed_model': 101, 'seed_noise': 103}
print(json.dumps(report, ensure_ascii=False, indent=2))
np.savez_compressed(output / 'caracteristicas.npz', real=real_features, generada=fake_features)
(output / 'informe.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
torch.save({'state_dict': extractor.state_dict(), 'preprocess': report['resize'],
'quick': quick, 'epochs': epochs}, output / 'clasificador.pt')
del images, labels, features, z, fake, class_loss, extractor, generator, optimizer
if device.type == 'cuda':
torch.cuda.empty_cache()
npm run lab and open the connection link.Exercises
Step 1 of 3. What distribution does (X_i, X_j) have when i≠j?
Step 1 of 3. What is the marginal of Y?
import numpy as np
def frechet_distance(mu1, S1, mu2, S2):
passGenerative evaluation is a protocol, not merely a number. Likelihood, feature distances and coverage metrics answer different questions and inherit assumptions from their data and extractors.