Evaluating generative models: bits per dimension, FID, KID, precision and recall, CRPS and calibration
Before this lesson: lesson 01 (the model families and maximum likelihood as a KL divergence) and lesson 04 (exact log-likelihoods). You also need the multivariate Gaussian, the symmetric matrix square root and the KL divergence. Helpful: probabilistic forecasting and Gaussian processes and uncertainty (scoring rules). Time: about 110 minutes, plus the notebook.
Why this matters #
You cannot improve what you measure badly. Image generators are ranked by FID; likelihood models by bits per dimension; weather and climate ensembles (GenCast, the ECMWF ensemble) by the CRPS, the spread–skill ratio and rank histograms. Papers compare numbers computed with different sample sizes, feature networks and estimators, and draw wrong conclusions.
For a scientific generative model, all three questions apply. A model of weather fields must give realistic samples (question 2), and its ensembles must be calibrated forecasts (question 3). After few-step distillation (lesson 12), a model can become sharper but lose diversity. Only the right metric shows it.
1. Predict first #
2. The picture #
Three kinds of evaluation #
- Likelihood treats the model as a density and averages over test data. This is a cross-entropy: (lesson 01). It needs a model with a density or a bound on it (flows, autoregressive models, VAEs, diffusion ELBOs).
- Sample-based distances compare a set of generated samples with a set of real data in a feature space. They need no density, so they also work for GANs.
- Forecast scores compare a predictive distribution (often given by samples, an ensemble) with the single outcome that happened, and average over many cases.
The simplest case: 1-D Gaussians #
Data , model .
- The expected negative log-likelihood is . It is smallest at , .
- The Fréchet distance is . It is the squared 2-Wasserstein distance between the two Gaussians. FID computes it between Gaussians fitted to features of images.
- For one outcome , draw the forecast CDF and the step function . The CRPS is the integral of the squared gap between the two curves. It is small when is sharp and centered near .
Data , model . What is the Fréchet distance between them?
In 1-D the Fréchet distance is . It uses standard deviations, not variances: is the variance difference, which is wrong. forgets to square the mean difference, and ignores the spread.
Likelihood and samples measure different things #
A model can have a good likelihood and bad samples, or good samples and a bad likelihood. The figure shows three ways this happens in 1-D.
Pick a model and compare its test NLL with its samples. The blue area is the data density, the orange curve the model, and the orange ticks below are 60 model samples. Junk mixture: only a share comes from the true model and the rest from a broad "junk" Gaussian. With only about a quarter of the samples look like data, but the NLL rises by much less than nats. In dimensions the bound is bits per dimension: invisible in a likelihood table. One mode: perfect samples, huge NLL. Broad Gaussian: the maximum-likelihood fit covers both modes, and many samples fall between them. "Good samples" counts model mass where the data density is at least 5% of its peak; "data covered" the reverse.
3. Definitions and main results #
3.1 Likelihood and bits per dimension #
The problem. A continuous density on cannot be compared directly with a probability mass function. It can put arbitrarily high density on the integer points, so the "log-likelihood" of discrete data can go to and means nothing.
Uniform dequantization. Train on with . The density then defines a discrete model: the mass of the unit cube at ,
Theorem 1 (the dequantization bound) #
sums to at most 1 (to exactly 1 if lives on ), and for every
Proof.
- The cubes , , do not overlap and fill . So .
- has density 1 on the unit cube, so .
- is concave. Jensen's inequality gives .
So the dequantized negative log-likelihood is an upper bound on , the code length (in nats) of a real discrete model. Maximizing the continuous likelihood on dequantized data maximizes a lower bound on the discrete log-likelihood. Variational dequantization (Flow++) learns and tightens the bound to .
Rescaling and bits per dimension. Models usually see . By the change of variables, , so . Divide the nats per image by to get bits per dimension (bpd):
averaged over and over test images.
- The uniform density on has , so : the trivial code for 8-bit pixels.
- On CIFAR-10 test data: Glow 3.35, PixelCNN++ 2.92, the variational diffusion model (VDM) bound 2.65 bits/dim.
- For data scaled to , the bin width is , so the constant is .
- A model that only gives a lower bound on (a VAE ELBO, a diffusion ELBO) gives an upper bound on the bpd. It is still valid to report, as "".
A flow on grey images (, data rescaled to ) gives nats per image on dequantized test data. What are its bits per dimension?
, so the discrete NLL is at most nats; divided by this is bits per dimension. A positive log-density is normal for data squeezed into ; forgetting gives a negative "bpd". The last option forgets to convert nats to bits.
3.2 The Fréchet distance and FID #
Definition. Fit Gaussians and to the features of the real and the generated images (sample means; sample covariances with ). Then
This is the squared 2-Wasserstein distance between the two Gaussians. FID is this distance on Inception-v3 features (Heusel et al. 2017). Lower is better. The standard protocol is "FID-50k": 50,000 generated images against the statistics of the training set.
- 1-D: .
- Commuting covariances (same eigenvectors, eigenvalues and ): .
Why the symmetric form. Older code computes with a general matrix
square root. The product is not symmetric. If is invertible,
is similar to a symmetric
positive semidefinite (PSD) matrix. So both have the same eigenvalues, all , and the traces of
their square roots agree. The symmetric form can use an eigendecomposition (eigh), which is stable
and real (linear algebra lesson 16). A general sqrtm
of a non-symmetric, nearly singular matrix can return complex parts and lose accuracy.
Drag the orange mean and change the generated covariance. The blue and orange ellipses show 1 and 2 standard deviations of the real and the generated Gaussian; the dots are samples of each. The exact Fréchet distance splits into a mean term and a covariance term. Now press Same as real: the exact distance is 0, but the estimate from samples is positive, and its mean over many repeats is close to the second-order bias printed below it. Increase : the bias falls like .
Theorem 2 (the small-sample bias of FID) #
Draw two independent sets of samples from the same distribution and compute the plug-in estimate . To second order in the sampling errors,
Why this is true (intuition). The estimate is a squared distance between two noisy summaries. The noise in the two sets does not cancel; it adds. A sum of squares of noise has a positive mean.
Proof
- Mean term. , so (exact).
- Covariance term near . Write . For commuting matrices the trace term is , because . In general, to second order, it is .
- For the sample covariance of : and for . So .
- are independent with mean 0, so . Multiply by and add step 1.
For a general covariance with eigenvalues , the same argument (with the second-order Bures metric in the eigenbasis) gives . The widget prints this value; a simulation with gives against the predicted .
Consequences.
- The bias decays like and grows like for white features. Real Inception features are not white, so the formula with does not give the real bias. But the real bias is still large: between the CIFAR-10 train and test sets, Bińkowski et al. (2018) measure FID ≈ 8.1 at , still decreasing.
- Compare FID only at the same , feature network and preprocessing. No unbiased estimator of FID exists, and the bias depends on the distributions, so at small it can even change the ranking of two models. Chong and Forsyth (2020) extrapolate linearly in ().
- FID assumes Gaussian features, but Inception features are ReLU outputs, many of them exactly zero.
3.3 KID: an unbiased kernel distance #
Maximum mean discrepancy (MMD). For a kernel and independent , :
It is the squared distance between the mean feature vectors of and in the feature space of the kernel. KID (Bińkowski et al. 2018) uses the same Inception features and the cubic polynomial kernel . Its feature space contains all monomials up to degree 3, so KID compares means, covariances and third moments. (This kernel is not characteristic: only says that the moments up to order 3 agree.)
The unbiased estimator. With samples and :
Theorem 3 (KID is unbiased) #
for every .
Proof
- For , and are independent copies, so . The first sum has such terms. The same holds for the second sum.
- Every cross pair is independent, so each of the terms has mean .
- Linearity of expectation gives the result. The diagonal terms are left out because in general.
Consequences. When the expectation is 0, so single estimates scatter around 0 and are often negative. A negative KID is normal, not a bug. Values at different are comparable. The cost is , so in practice KID is averaged over many random subsets (for example of 1,000 samples each).
3.4 Precision and recall #
A model can fail in two ways: low fidelity (samples outside the data manifold) and low diversity (modes of the data are missing). One number such as FID cannot show which.
- Precision: the share of generated samples that lie in the support of the real distribution.
- Recall: the share of real samples that lie in the support of the model distribution.
The k-NN estimator (Kynkäänniemi et al. 2019). In a feature space, approximate the real support by the union of balls around the real features, each with radius equal to the distance to its -th nearest other real feature. Do the same for the generated features. Precision is the share of generated points inside the real union; recall is the share of real points inside the generated union. The paper uses VGG-16 features, and 50,000 samples per set.
Pick a generated set and change . Real data (blue) is the 8-Gaussians toy; generated points are orange. A filled dot lies inside the other set's support, a ring lies outside. Mode collapse covers only three modes: precision stays high, recall drops to about . Too wide does the opposite. Choose outliers and show the balls around the generated points: six far outliers get huge balls, which cover real points and inflate recall.
Weakness. An outlier has a far -th neighbor, so it gets a huge ball. Outliers among the generated samples inflate recall, and outliers among the real samples inflate precision (section 4 shows a 1-D case). "Density and coverage" (Naeem et al. 2020) are more robust variants.
A GAN produces very realistic images, but only of 3 of the 10 classes in the data. What do k-NN precision and recall show?
Every generated sample lies near real data, so precision is high. But most real samples (the 7 missing classes) are far from every generated sample, so they lie outside the generated support: recall is low. FID would rise too, but it cannot tell this failure from blurry samples; precision and recall can.
3.5 Why likelihood and sample quality can disagree #
- Good likelihood, bad samples (Theis, van den Oord and Bethge 2016). Mix a good model with a bad one : . Then . The log-likelihood drops by at most nats per image, which is bits/dim for . But 99% of the samples come from the bad model. (The first figure shows this.)
- Good samples, bad likelihood. A model that outputs near-copies of training images has perfect samples but a very poor test likelihood. GANs have no likelihood at all.
- The likelihood is dominated by low-level detail. Most bits encode local texture and noise, not semantics. Flows trained on CIFAR-10 give higher likelihood to SVHN images than to CIFAR-10 test images (Nalisnick et al. 2019).
- FID mixes both failure types. Mode dropping (low recall) and poor fidelity (low precision) can give the same FID. Report precision and recall next to it.
3.6 Proper scoring rules and the CRPS #
Setting. A forecast is a distribution ; then the outcome happens. A scoring rule is a number, here negatively oriented. Let be the expected score when the truth is . is proper if for all , and strictly proper if equality holds only for . In words: reporting what you believe is the best strategy.
- The log score is strictly proper, but it needs a density .
- The squared error of the forecast mean is proper but not strictly proper: it ignores the spread.
- The continuous ranked probability score (CRPS) is strictly proper on distributions with a finite mean:
It has the units of , and it becomes the absolute error for a point forecast at .
Theorem 4 (the kernel form of the CRPS) #
If are independent with CDF and , then
Proof.
- For real : , because the integrand is 1 exactly for between and , and 0 elsewhere.
- Take , then the expectation. The integrand is non-negative, so we may swap and (Tonelli). With and : .
- Take . By independence , so .
- Both integrals are finite because , so we may subtract them: .
Propriety in two lines. For and fixed , (bias plus variance of a Bernoulli). Integrate: . This is smallest exactly when .
The Gaussian closed form. For and , let be the standard normal density and CDF. , whose absolute value has mean (the folded normal). , so . With Theorem 4:
Ensemble estimators. For members :
The standard estimator is exactly the CRPS of the empirical CDF of the members (Theorem 4 applied to the empirical distribution). The fair one is from Ferro (2014).
Move the forecast mean , its spread and the outcome . The magenta area is the squared gap between the forecast CDF and the outcome step; its area is the CRPS, and it matches the closed form and the kernel form. Shrink toward 0: the CRPS becomes . The violet dashed steps are the CDF of one ensemble of members. Over 2000 ensembles the standard estimator is too large on average by about , while the fair estimator matches the exact CRPS. Try : the bias is largest.
Theorem 5 (the standard estimator is biased; the fair one is not) #
If the members are i.i.d. draws from , independent of , then
Proof
- .
- In , the diagonal terms are 0, and each of the other terms has mean .
- So the standard pair term has mean , and the fair pair term has mean . Use Theorem 4.
For a Gaussian the bias is : for .
- The standard estimator punishes small ensembles, so a 10-member and a 50-member ensemble are compared unfairly. As a training loss, its expected spread term is instead of . It rewards spread too little, so its optimum is under-dispersed.
- The fair version has a degenerate case: with it is 0 whenever lies between the two members. Some weather models (for example ECMWF's AIFS-CRPS) train with an "almost fair" mix of the two.
A deterministic model predicts (a point forecast, ), and the outcome is . What is its CRPS?
A point forecast has the step CDF . The squared gap to is 1 exactly between and , so the integral is . Equivalently, in the kernel form and . This is why the CRPS can compare deterministic and probabilistic forecasts in the same units.
3.7 Multivariate fields: energy score and variogram score #
For a field (values at sites), the average per-site CRPS sees only the marginal distributions. An ensemble with correct marginals but wrong spatial correlation gets the same score.
Energy score (Gneiting and Raftery 2007, section 4.3): with the Euclidean norm. It is strictly proper on distributions with a finite mean, and it equals the CRPS for . Its ensemble estimators have the same form as the CRPS estimators, with norms.
Weakness. The energy score detects errors in the mean well, errors in the variance less well, and errors in the correlation structure only weakly, more so in high dimension (Pinson and Tastu 2013; Scheuerer and Hamill 2015). The reason: adds up the errors at all sites, and a change in correlation changes this sum very little compared with its sampling noise.
Variogram score of order (Scheuerer and Hamill 2015):
It compares the expected differences between pairs of sites (the variogram) with the observed differences. is the usual choice, and the weights can decay with distance. It is proper but not strictly proper: it sees only differences, so it is blind to a shift of the whole field. Use it together with the CRPS or the energy score.
3.8 Calibration: rank histograms and the spread–skill ratio #
Calibration means that forecasts and outcomes are statistically consistent. For an ensemble: if the outcome behaves like one more member (it is exchangeable with the members), then its rank = (number of members below ) is uniform on . Reason: is equally likely to be in any of the positions of the sorted list of all values.
Rank histogram (Talagrand diagram): count the ranks over many cases, in bins.
- Flat: consistent with calibration.
- U shape: the outcome often falls outside the ensemble: under-dispersion (too narrow), or conditional biases.
- Dome: over-dispersion (too wide).
- Slope: a bias. Many low ranks mean that the members are too high.
A flat histogram is necessary, not sufficient (Hamill 2001). A climatological ensemble is calibrated but not sharp, and opposite biases in different regions can cancel. The goal is maximal sharpness subject to calibration (Gneiting, Balabdaoui and Raftery 2007), so look at proper scores too.
Theorem 6 (spread and skill of a perfect ensemble) #
Given the information at forecast time, let be i.i.d. with mean and variance . Let be the ensemble mean and the ensemble variance with . Then
Proof
. The two parts are independent with mean 0 and variances and , so the variance of the difference is . The variance estimator with is unbiased.
So spread / (RMSE of the ensemble mean) tends to for a perfect ensemble: for , for . The corrected spread–skill ratio (Fortin et al. 2014) is
over cases. It is about 1 for a calibrated ensemble, below 1 when under-dispersed and above 1 when over-dispersed. Average the variances and the squared errors over cases before taking roots. If the members have the right mean but a spread instead of , then and , so .
Change the spread factor and the bias of the members, or use the presets. The orange bars are the observed ranks of the outcome over many cases; the magenta dots are the exact probabilities, and the grey line is the flat value . Too narrow gives a U, too wide a dome, a bias a slope. The corrected spread–skill ratio is near 1 only for , ; there the uncorrected ratio is about . Use 200 cases: even a calibrated ensemble then gives a bumpy histogram.
The rank histogram of a 20-member ensemble over 5,000 cases is U-shaped: the outermost bins hold far more cases than the middle ones. What does it mean?
Rank 0 or means the outcome lies below all or above all members. This happens too often when the spread is too small. Over-dispersion gives the opposite, a dome; a constant bias gives a slope (many low ranks if the members are too high). Biases that switch sign between cases can also produce a U, so check the spread–skill ratio too.
Answers to section 1. (1) Positive. A Fréchet distance is never negative, and the estimate is not always 0, so its mean is positive: about for white features (Theorem 2). KID is unbiased (Theorem 3): its expectation is 0, and single values are often negative. (2) Above, by , which is for a Gaussian with (Theorem 5). The uncorrected spread–skill ratio is about (Theorem 6).
The family table of lesson 01, with how to evaluate
| family | likelihood | how to evaluate |
|---|---|---|
| autoregressive models, normalizing flows | exact | bits/dim on dequantized test data; plus sample metrics |
| VAEs, diffusion models | lower bound (ELBO) | bits/dim as an upper bound ("≤"); FID/KID, precision and recall |
| GANs, few-step distilled models | none | FID/KID, precision and recall; nearest-neighbor checks for memorization |
| energy-based models | unnormalized | sample metrics; likelihood only with an estimate of |
| forecast ensembles (any family) | — | fair CRPS, energy and variogram scores, rank histograms, spread–skill ratio |
4. Worked example #
(a) Bits per dimension. 8-bit grey images with , rescaled to . A flow gives nats (averaged over ). A positive log-density is normal on .
- .
- nats.
- .
(b) Fréchet distance. against .
- Mean term: .
- commutes with , whose eigenvalues are 3 and 1. Trace term: .
- .
(c) FID bias in 1-D. Two sets of from the same . Mean term ; standard-deviation term . So (a simulation with 200,000 repeats gives ).
(d) KID by hand. , so . Real , generated .
- Within real (): , mean 1.
- Within generated: , mean 27.
- Cross: , , , ; mean .
- .
(e) Precision and recall in 1-D, with . Real : every radius is 1, so the real union is . Generated : radii 1, 1 and 8.5 (the nearest neighbor of 10 is 1.5), so the generated union is .
- Precision: 0.5 and 1.5 are inside , 10 is not: .
- Recall: 0, 1, 2, 3 are all inside : .
- Without the outlier 10, the generated union is and the real point 3 is outside: recall . The outlier raised recall from 0.75 to 1.
(f) CRPS. Forecast , outcome , so , , : .
Ensemble , :
- .
- Distances of the 6 unordered pairs: 2, 3, 5, 1, 3, 2, sum 16; over ordered pairs, 32.
- Standard: . Fair: .
- The difference is the mean pairwise distance divided by . For Gaussian members with its expectation is .
(g) Calibration. A perfect 10-member ensemble has an uncorrected ratio of and a corrected ratio of 1. With half the right spread (): . Its rank histogram is U-shaped. For the bin probabilities are instead of each (code below).
5. In code #
NumPy and SciPy check the theory and the worked example: the dequantization bound, the Fréchet distance in its symmetric form, the bias of Theorem 2, the CRPS and its estimators, and exact rank histograms. The notebook has these cells and the exercises.
import numpy as np
from scipy.integrate import quad
from scipy.linalg import sqrtm
from scipy.stats import truncnorm
# Theorem 1 for a 4-level variable: a density on [0, 4) (a normal N(1.7, 0.6^2) truncated to [0, 4)).
p = truncnorm((0 - 1.7) / 0.6, (4 - 1.7) / 0.6, loc=1.7, scale=0.6)
for x in range(4):
P = quad(p.pdf, x, x + 1)[0] # induced discrete model P(x)
bound = quad(lambda u: p.logpdf(x + u), 0, 1)[0] # E_u log p(x + u), u ~ U[0, 1)
print(x, f"{bound:.4f} <= {np.log(P):.4f}")
# 0 -2.5215 <= -2.1232
# 1 -0.5770 <= -0.5601
# 2 -1.4104 <= -1.2238
# 3 -5.0215 <= -4.1929
def frechet(m1, S1, m2, S2):
"""Squared Frechet (2-Wasserstein) distance between two Gaussians, symmetric form with eigh."""
w, Q = np.linalg.eigh(S1)
R = Q @ np.diag(np.sqrt(np.clip(w, 0, None))) @ Q.T # S1^{1/2}
ev = np.clip(np.linalg.eigvalsh(R @ S2 @ R), 0, None) # eigenvalues of S1^{1/2} S2 S1^{1/2}
return np.sum((m1 - m2) ** 2) + np.trace(S1) + np.trace(S2) - 2 * np.sum(np.sqrt(ev))
S2 = np.array([[2.0, 1.0], [1.0, 2.0]])
print(f"{frechet(np.zeros(2), np.eye(2), np.ones(2), S2):.4f}") # 2.5359 (worked example b)
S1 = np.array([[4.0, 0.0], [0.0, 1.0]]) # does not commute with S2
general = np.trace(sqrtm(S1 @ S2)).real # what older FID code does
sym = np.trace(sqrtm(sqrtm(S1) @ S2 @ sqrtm(S1))).real
print(np.allclose(S1 @ S2, (S1 @ S2).T), f"{general:.6f} {sym:.6f}") # False 4.114390 4.114390
# Theorem 2: two samples of size N from the SAME distribution N(0, I_d).
rng = np.random.default_rng(0)
for d, N in [(1, 50), (16, 200), (16, 1000)]:
fd = [frechet(a.mean(0), np.atleast_2d(np.cov(a, rowvar=False)), b.mean(0), np.atleast_2d(np.cov(b, rowvar=False)))
for a, b in (rng.standard_normal((2, N, d)) for _ in range(2000))]
print(d, N, f"{np.mean(fd):.3f} {2 * d / N + d * (d + 1) / (2 * (N - 1)):.3f}")
# 1 50 0.059 0.060
# 16 200 0.844 0.843
# 16 1000 0.168 0.168
The CRPS, its two ensemble estimators, and rank histograms computed exactly (without simulation):
import numpy as np
from scipy.integrate import quad
from scipy.stats import binom, norm
mu, s, y = 1.0, 2.0, 0.0
F = lambda x: norm.cdf(x, mu, s)
crps_int = quad(lambda x: F(x) ** 2, -np.inf, y)[0] + quad(lambda x: (F(x) - 1) ** 2, y, np.inf)[0]
z = (y - mu) / s
crps_cf = s * (z * (2 * norm.cdf(z) - 1) + 2 * norm.pdf(z) - 1 / np.sqrt(np.pi))
print(f"{crps_int:.4f} {crps_cf:.4f}") # 0.6628 0.6628
def crps_ens(x, y, fair=False):
M = len(x)
pair = np.abs(x[:, None] - x[None, :]).sum()
return np.mean(np.abs(x - y)) - pair / (2 * M * (M - 1) if fair else 2 * M * M)
print(crps_ens(np.array([-1.0, 1.0, 2.0, 4.0]), 0.0), round(crps_ens(np.array([-1.0, 1.0, 2.0, 4.0]), 0.0, fair=True), 4)) # 1.0 0.6667
# Theorem 5 by simulation: M = 5 members from F = N(1, 2^2), outcome y = 0.
rng = np.random.default_rng(1)
X = rng.normal(mu, s, size=(400_000, 5))
a, pair = np.abs(X - y).mean(1), np.abs(X[:, :, None] - X[:, None, :]).sum((1, 2))
print(f"{np.mean(a - pair / 50):.3f} {np.mean(a - pair / 40):.3f} {crps_cf + s / (5 * np.sqrt(np.pi)):.3f}")
# 0.889 0.663 0.888: the standard mean is biased up by s/(M sqrt(pi)); the fair mean is the exact 0.663
# Rank histograms without simulation: P(rank = r) for M = 4 members ~ N(b, c^2), outcome ~ N(0, 1).
for name, b, c in [("calibrated", 0.0, 1.0), ("too narrow", 0.0, 0.5),
("too wide", 0.0, 2.0), ("biased high", 0.5, 1.0)]:
probs = [quad(lambda u: binom.pmf(r, 4, norm.cdf(u, b, c)) * norm.pdf(u), -12, 12)[0] for r in range(5)]
print(f"{name:12s}", np.round(probs, 3))
# calibrated [0.2 0.2 0.2 0.2 0.2]
# too narrow [0.314 0.13 0.113 0.13 0.314]
# too wide [0.113 0.24 0.294 0.24 0.113]
# biased high [0.335 0.235 0.183 0.143 0.104]
6. Where it shows up #
- Image and video generation. FID-50k with Inception-v3 is the standard table entry, with precision and recall (or density and coverage) next to it. Resizing and JPEG compression change FID (clean-fid, Parmar et al. 2022). Stein et al. (2023) propose DINOv2 features instead of Inception (, reported for example by EDM2).
- Likelihood models. Flows, autoregressive models and variational diffusion models report bits/dim; a diffusion ELBO gives an upper bound (lesson 08).
- Weather and climate. WeatherBench 2 uses the fair CRPS and the spread–skill ratio. GenCast, a diffusion ensemble, is compared with the ECMWF ensemble by the CRPS, the ensemble-mean RMSE, spread–skill ratios and rank histograms.
- Spatial fields in science. Per-site CRPS of the quantities of interest against observations; energy and variogram scores for the whole field; correlation against distance; rank histograms per station; power spectra of generated fields.
- After distillation (lesson 12). A sharper few-step student can lose diversity: check recall, the spread–skill ratio and rank histograms, not only FID.
- Practice. Report bootstrap confidence intervals, check memorization with nearest training neighbors, and keep , features and preprocessing fixed within one table.
7. Common mistakes #
- Forgetting , or using it for data on (there it is ). Reporting nats as bits. A continuous likelihood on data that was not dequantized means nothing.
- Comparing FID across sample sizes, feature networks or preprocessing pipelines.
sqrtmof with the imaginary part silently dropped. Use the symmetric PSD form.- Clipping negative KID values to 0. That makes the estimator biased again.
- Sign conventions. Gneiting and Raftery (2007) define the CRPS and the energy score with the opposite sign (positively oriented). Most code and this lesson use "lower is better".
- The standard ensemble CRPS for ensembles of different sizes, or as a training loss.
- Per-site CRPS alone for spatial fields. It cannot see correlation errors.
- Reading an uncorrected SSR of 0.91 for as under-dispersion, or a flat rank histogram as proof of a good forecast.
8. Check yourself #
- A flow is trained on 8-bit images scaled to and reports . Write the bits/dim.
Answer
The bin width is , so and . - Compute KID with between the set and itself. Why is a negative value possible?
Answer
Within terms: , mean 1, twice. Cross term: . Result . The within terms leave out the diagonal pairs, but the cross term contains them. The estimator is unbiased, so for equal distributions its mean is 0 and single values scatter on both sides of 0. - Two independent 1-D samples of size come from the same Gaussian. What FID do you expect?
And for white 16-dimensional features?
Answer
1-D: . For : . Both are pure bias: the true distance is 0. - Two members , outcome . Compute the standard and the fair ensemble CRPS.
Answer
; the ordered pair sum is . Standard: . Fair: . This is the degenerate case of the fair score: it is 0 whenever lies between two members. - A 10-member ensemble has the right mean but half the right spread. Which corrected and uncorrected
spread–skill ratios do you expect, and what does the rank histogram look like?
Answer
Corrected: . Uncorrected: . The rank histogram is U-shaped, because the outcome often falls outside the ensemble. - Your generated weather maps have the correct distribution at every grid point, but the points are
independent, while real maps are spatially correlated. Which scores notice?
Answer
The per-site CRPS does not: it depends only on marginals. The energy score notices only weakly. The variogram score does, because it compares with for pairs of sites. A plot of correlation against distance shows it too.
Give the bits-per-dimension formula for 8-bit data rescaled to .
, averaged over the dequantization noise and the test images.
Why does the dequantized continuous NLL bound the discrete NLL?
and is concave, so by Jensen .
Write the Fréchet distance used by FID.
.
Why is the FID estimate biased upward at small ?
It is a squared distance between noisy sample means and covariances; the sampling noise of the two sets adds and does not cancel, about for white features.
Why can KID be negative, and why is that fine?
KID is the unbiased U-statistic for MMD²; for equal distributions its mean is 0, so single estimates scatter on both sides of 0.
What do precision and recall measure for a generative model?
Precision: the share of generated samples inside the real support (fidelity). Recall: the share of real samples inside the generated support (diversity).
What is a proper scoring rule?
A score with for all : forecasting the true distribution is optimal (strictly proper: only it).
State the kernel form of the CRPS.
with independent.
What is the bias of the standard ensemble CRPS with members?
, which is for a Gaussian; the fair estimator with removes it.
Why does the spread–skill ratio need the factor ?
For a perfect ensemble while , so the raw ratio tends to .
9. Interview angle #
- "Why can't you compare FID numbers from two papers?" — Different (FID is biased like ), different feature extractors and preprocessing. No unbiased estimator of FID exists.
- "Why is KID sometimes negative?" — It is the unbiased U-statistic for MMD²; for equal distributions its mean is 0.
- "Model A has a better likelihood but a worse FID than model B. Is that possible?" — Yes. The mixture argument (the likelihood moves by at most while 99% of samples are bad), and the likelihood is dominated by low-level detail.
- "Derive the kernel form of the CRPS." — Theorem 4: , then .
- "How do you check that a weather ensemble is calibrated?" — Rank histograms, the corrected spread–skill ratio, the fair CRPS, and for fields the variogram score.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution:
- Bits per dimension of a Gaussian density on 8-bit data with uniform dequantization; check the bound of Theorem 1 against the exact discrete probabilities.
- The Fréchet distance with the symmetric square root; measure its bias against the sample size.
- Unbiased KID with the cubic kernel; compare it with FID on the same features at small .
- k-NN precision and recall on mode-collapsed and over-dispersed samples of the 8-Gaussians toy.
- CRPS: the Gaussian closed form against the standard and fair ensemble estimators; rank histograms and the corrected spread–skill ratio.
11. Watch and read #
- Murphy, Probabilistic Machine Learning: Advanced Topics (2023), section 20.4 "Evaluating generative models" (likelihood, distances in feature space, precision and recall).
- Theis, van den Oord and Bethge, A note on the evaluation of generative models (2016): section 3.1 (log-likelihood and dequantization), the mixture argument.
- Heusel et al., GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium (2017): the definition of FID.
- Bińkowski, Sutherland, Arbel and Gretton, Demystifying MMD GANs (2018): section 4 (the bias of FID, KID) and appendix D (why FID has no unbiased estimator).
- Kynkäänniemi et al., Improved Precision and Recall Metric for Assessing Generative Models (2019); Naeem et al., Reliable Fidelity and Diversity Metrics for Generative Models (2020).
- Stein et al., Exposing flaws of generative model evaluation metrics and their unfair treatment of diffusion models (2023).
- Gneiting and Raftery, Strictly Proper Scoring Rules, Prediction, and Estimation (JASA 2007, author's PDF): section 2 (propriety), section 4.2 (CRPS), section 4.3 (energy score).
- Rasp et al., WeatherBench 2 (2023): the fair CRPS, the spread–skill ratio and rank histograms for data-driven weather ensembles.
- The
scoringrulesPython library: CRPS, energy and variogram scores with their ensemble estimators.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.