Module contents
Lesson 11 of 28Core 100 min

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

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 DD dimensions, bits per dimension are −log⁡p(x)/(Dlog⁡2)-\log p(x)/(D\log2). 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 [0,1)[0,1) 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.

InteractiveWhen metrics disagree

CIFAR-10 without conditioning. The ranking uses results from the selected study. Lower FID, KID and NLL are better, while higher IS, precision and recall are better.

Diffusion: simplified objectiveFID: 3.17
FID 3.17 · IS 9.46 ± 0.11 · KID no data · PRD no data · NLL ≤ 3.75 (bound) · Bound on the test NLL
StyleGAN2 + ADAFID: 3.26
FID 3.26 · IS 9.74 ± 0.05 · KID no data · PRD no data · NLL no data · Unconditional model; NLL unavailable
Diffusion: objective LFID: 13.51
FID 13.51 · IS 7.67 ± 0.13 · KID no data · PRD no data · NLL ≤ 3.70 (bound) · Bound on the test NLL
SNGANFID: 21.70
FID 21.70 · IS 8.22 ± 0.05 · KID no data · PRD no data · NLL no data · NLL unavailable
Gated PixelCNNFID: 65.93
FID 65.93 · IS 4.60 · KID no data · PRD no data · NLL 3.03 · Reported test NLL

Source: Ho, Jain and Abbeel, Table 1 and Section 4.1. Their table compiles results from several papers. The dataset alone does not establish that feature extraction or sampling protocols match. For the simplified diffusion objective, the FID of 3.17 uses the training set as its reference. The paper reports 5.24 against the test set. NLL bounds remain separate from the exact-value rankings. Missing values are left blank and each panel uses a single study. The gallery displays recorded scores.

Compare available measurements and their protocols. An absent cell indicates that the figure was not evaluated with the described method.

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 X∼N(0,Id)X\sim\Normal(0,I_d), density is maximized at the origin, but E∥X∥2=d\E\|X\|^2=d: 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: ∥X∥2=∑iXi2\|X\|^2=\sum_i X_i^2 has variance 2d2d because coordinates are independent and each squared standard normal has variance two. By Chebyshev, P(∣∥X∥2/d−1∣≥ϵ)≤2/(dϵ2)\Pr(|\|X\|^2/d-1|\geq\epsilon)\leq2/(d\epsilon^2). For fixed ϵ>0\epsilon>0, that bound approaches zero as dd grows. Maximum density remains at zero, but typical norm scales as d\sqrt d.

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 x1,…,xMx_1,\ldots,x_M, compare the mean of −log⁡p(xi)-\log p(x_i) 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.

InteractiveOut-of-distribution likelihood

The bars count test images. Fewer bits per dimension means the model assigns higher per-pixel probability.

  • Fashion-MNIST, in distribution
  • MNIST, out of distribution
  • Threshold

Short run: the logistic-mixture PixelCNN from lesson 3, with width 16, three blocks, five mixture components, and three epochs on 4,096 Fashion-MNIST training images. Each histogram uses the first 1,024 images in its official test split, at 28 × 28 pixels and with a fixed conditioning label of 0, ignoring clothing and digit classes. Means and rates use individual measurements from this run. The standard rule flags high bpd as out of distribution. Reversing the rule illustrates this particular result. The histograms alone cannot establish that typicality explains the reversal.

2.70
Flag as out of distribution
MNIST flagged as out of distribution
0.5 %
Fashion-MNIST false alarms
77.4 %
Fashion-MNIST mean
3.567 bpd
MNIST mean
1.675 bpd
Move the threshold and compare distributions and errors of the described experiment. OOD conclusions depend on both datasets and the model.

Inception Score: diversity of predicted labels

The expected KL is mutual information I(X;Y)I(X;Y) under the joint distribution of samples and classifier. A confident classifier per image and diverse marginal labels increase the score. With KK classes, I(X;Y)≤H(Y)≤log⁡KI(X;Y)\leq H(Y)\leq\log K and thus 1≤IS⁡≤K1\leq\operatorname{IS}\leq K; 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 Σr1/2ΣgΣr1/2\Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2} avoids treating nonsymmetric product ΣrΣg\Sigma_r\Sigma_g 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.

InteractiveFID and sample size

The horizontal axis shows 32, 64, 128 and 256 samples per set from left to right. The highlighted point matches the selected size.

In the first mode, each point is the mean of 1,024 independent pairs of N(0, I) samples. The bars show percentiles from 2,000 resamples of those 1,024 measurements. In the second, the point is an additional independent pair and the bars show percentiles from resampling observations within that pair 200 times. Both use the 2.5th and 97.5th percentiles. They describe different sources of uncertainty, and bootstrapping does not remove FID bias.

Resampling observations introduces duplicates, and its percentiles may exclude the original estimate. In particular, under the equality hypothesis for MMD², this naive bootstrap does not guarantee correct coverage. Use it to diagnose how resampling behaves.

MMD² uses the kernel (1 + x·y/d)³ and excludes within-group diagonal terms. Its expected value is 0 in this experiment. A finite-sample mean or its interval may still miss 0, and an unbiased estimate can be negative. The inputs are synthetic Gaussian features. NumPy seeds: 191101 for the repeated runs and 191102 for individual samples.

Statistic
Resampling unit
Dimension
64
Mean of 1,024 repetitions0.8217
Bootstrap of the mean0.8109 to 0.8325
Population value0
Compare bootstrap intervals for the mean of 1024 repetitions with resampling observations from one individual pair.

MMD and KID

The reproducing property evaluates RKHS functions by inner product with k(x,⋅)k(x,\cdot); MMD compares the means of these elements when they exist. Zero MMD does not imply equal distributions unless the kernel additionally is characteristic.

For n,m≥2n,m\geq2, the off-diagonal estimator is

MMD⁡^u2=∑i≠jk(xi,xj)n(n−1)+∑i≠jk(yi,yj)m(m−1)−2∑i,jk(xi,yj)nm.\widehat{\operatorname{MMD}}_u^2=\frac{\sum_{i\ne j}k(x_i,x_j)}{n(n-1)}+\frac{\sum_{i\ne j}k(y_i,y_j)}{m(m-1)}-\frac{2\sum_{i,j}k(x_i,y_j)}{nm}.

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 k(x,y)=(x⊤y/d+1)3k(x,y)=(x^\top y/d+1)^3; 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, kk, 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 kk. These definitions differ.

Kynkäänniemi and colleagues use 50000 samples per set and k=3k=3 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 (P,R)(P,R) use Fβ=(1+β2)PR/(β2P+R)F_\beta=(1+\beta^2)PR/(\beta^2P+R), set to zero if both are zero; a curve can report the maximum. F1/8F_{1/8} weights precision more and F8F_8 weights recall more. The gallery’s Choi figures are these PRD summaries, not the neighboring-ball fractions in the next figure.

InteractiveFidelity and coverage separately
  • Reference points and balls
  • Generated points and balls

The reference is a uniform mixture of three 2D Gaussian distributions centered at (−2, 0), (0, 0) and (2, 0) with σ = 0.28. The generated distribution uses the draggable centers and selected spread. In collapsed mode it uses only the middle center. Each set has 120 independent samples, with seeds 191112 and 191113. The controls transform the same base samples.

Each point has a ball that extends to its kth nearest neighbor within the same set, excluding the point itself. Precision is the fraction of generated points inside any reference ball. Recall is the fraction of reference points inside any generated ball. The density-and-coverage formulation defines a separate coverage metric. Values depend on k, the sample and its extreme points.

The displayed FID applies the Fréchet formula to the sample means and covariances of the 2D coordinates, without extracting Inception features. A single score can hide changes in shape or modes and can miss some cases of mode collapse.

Generated modes
0.28
3
Precision92.5 %
Recall93.3 %
FID on 2D features0.011
Modify the generator in the 2D mixture and compare balls and metrics calculated by the 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 xx and textual condition tt with CLIP and compares vectors by cosine. Hessel and colleagues’ CLIPScore for image captioning uses 2.5max⁡(0,cos⁡(fimagen(x),ftexto(t)))2.5\max(0,\cos(f_{\mathrm{imagen}}(x),f_{\mathrm{texto}}(t))) 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 ψ=0\psi=0, kNN precision and recall are both zero; with ψ=0.5\psi=0.5 they are 0.523 and 0.438, and with ψ=1\psi=1 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.

[ ]FID and MMD from scratchBrowser
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.

[ ]Precision and recall in two dimensionsBrowser
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.

[ ]Evaluate a DCGAN with Fashion featuresLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofExcluding diagonals
Prove: Prove that the off-diagonal MMD² estimator is unbiased for independent i.i.d. samples and a fixed kernel with finite expectations.
0
Consider within-sample pairs and cross-set pairs separately.

Step 1 of 3. What distribution does (X_i, X_j) have when i≠j?

ProofIS as mutual information
Prove: Prove log IS = I(X;Y) and bound IS for a classifier with K classes.
0
The joint distribution is p(x)p(y|x).

Step 1 of 3. What is the marginal of Y?

NumericTwo isotropic Gaussians
In dimension 2048, calculate population FID between N(0,I) and N(0,4I).
CodeSymmetric roots and covariances
Implement frechet_distance(mu1, S1, mu2, S2). Covariances must be square, symmetric and positive semidefinite. Accept residual imaginary parts below 1e−9, reject larger ones, and clip only negative eigenvalues compatible with 1e−9 relative error. Use the symmetric roots of S1 and S1^(1/2) S2 S1^(1/2); do not use the root of a nonsymmetric product as if it were symmetric.
import numpy as np

def frechet_distance(mu1, S1, mu2, S2):
  pass
Shift+Enter to run
QuizChoosing an evaluation
You want to detect missing modes, compare explicit-model likelihoods and evaluate with only 1000 samples. Which combination is most defensible?
QuizHigh density and low mass
A very high-dimensional standard Gaussian has maximum density at the origin. What does this imply for detecting atypical observations?
Key idea

Generative 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.