12 / 34 · Evaluation
Precision and recall for generative models
FID mixes implausible samples and missing parts of the data into one number. Precision and recall separate the two failures, through clusters, nearest-neighbour balls, or density and coverage, which resist outliers.
On this page 9
A common view of the models in this course is that a VAE produces blurry samples but covers the whole data set, while the GANs later in the course produce sharp samples but drop part of the data. If both models get the same FID, the number cannot confirm or refute this, because it mixes two different failures into one distance. A generator can fail by producing images that look like no real image, or by producing only part of what the data contains, faces of one age or one pose.
The words for the two failures come from classification. Precision is the share of generated samples that look like real data. Recall is the share of the real data that the model can produce.
Two failures, one number#
Take real features in two dimensions and models . By the isotropic case of the FID note,
The value depends only on , so and score the same, .
The two models fail in opposite ways. The first is collapsed. Its samples are plausible points of , but it rarely leaves the centre: the disc of radius 0.90 holds only the inner third of , yet of the model’s samples. Both numbers come from integrating the density of over the disc in polar coordinates:
which at is for and for . The second is spread out: it reaches everything, but many of its samples land where real data almost never are. Telling the two apart takes two numbers.
Precision and recall of distributions#
The idealized definition compares supports, the regions where each distribution puts mass, with the real distribution and the model:
Precision is the probability that a generated sample falls where real data can occur; recall is the probability that a real sample falls where the model can generate.
Taken literally, exact supports cannot tell the two Gaussians apart. A Gaussian has positive density everywhere, so both supports are the whole plane and precision and recall are 1 for every . The definition is useful as a picture of something weaker, the region where each distribution puts most of its mass. Read that way, the collapsed model has high precision and low recall, and the spread-out model the opposite.
That region has to be estimated from samples, in a feature space where distances mean something, usually the features of a pretrained network as in FID. Every number below is a value of such an estimator. The two methods that follow estimate the regions differently.
The PRD curve#
Sajjadi et al. (2018) define precision and recall through a shared component. has precision at recall if both distributions contain a common part :
A fraction of the data is covered by the shared part, and a fraction of the model’s mass lies in it. For distributions on a finite set of outcomes , the best attainable pairs form a curve traced by , and every pair below it is attainable too (Sajjadi et al., 2018, Theorem 2):
Where the curve comes from. Fix the ratio . The decomposition needs and at every outcome, so that the rest parts and are non-negative. With both conditions read . Summing over , and using that sums to 1, gives ; the choice reaches it, and is .
The ends of the curve recover the support definition. As , tends to wherever and to 0 elsewhere, so the largest precision is ; as , the largest recall is (Theorem 1 of the paper).
To make images finite, the real and generated Inception features are clustered together by k-means into 20 clusters, and and become two histograms over the clusters. The clustering is random, so the curve is averaged over several runs.
A small example. With two clusters, real and a collapsed model , the curve is and . Up to it runs at recall 0.5 up to precision 1; beyond, precision stays 1 and recall falls. Every sample lies in a cluster the data use, so precision reaches 1, but the second cluster, half of the data, is out of reach, so recall never exceeds 0.5.
A curve is hard to compare across many models, so Sajjadi et al. summarise it by two numbers, the largest values along it of
for , which leans toward recall, and , which leans toward precision. Over hundreds of trained models on Fashion-MNIST they found that VAEs tend to have lower precision or higher recall than GANs: the folklore of the opening, measured.
Nearest neighbours as a support estimate#
Twenty clusters are coarse: a model that reaches each cluster but only part of it looks perfect. Kynkäänniemi et al. (2019) estimate each support directly as a union of balls. Write for the distance from a feature vector to its -th nearest neighbour in its own set, and for the ball of radius around . Around every real sample put the ball reaching to its -th nearest real neighbour; their union is the estimate of where real data live. With
and real features and generated features ,
Precision is the share of generated samples inside the real estimate; recall, the share of real samples inside the generated estimate. The radii adapt to the local density: small balls where samples are dense, large ones where they are sparse. The paper uses , 50,000 samples on each side and the features of the second fully connected layer of VGG-16.
Worked example: one dimension, k = 1#
Real samples , generated samples , .
Each real sample has a neighbour at distance 1, so each real ball has radius 1 and their union is . Three generated samples lie inside it and 7 does not: precision is .
The generated radii are the distances to the nearest generated neighbour: 0.6 for 0.2, 0.3 for 0.8 and for 1.1, and 5.9 for 7. Real 0 and 1 are covered by the small balls around 0.2 and 0.8. Real 2 is 0.9 from 1.1, outside its ball, and real 3 is far from all three small balls, yet both lie within 5.9 of the outlier 7. Recall is . Remove the outlier and recall drops to : the model’s actual samples sit between 0.2 and 1.1 and say nothing about 2 or 3.
k-NN balls, and an outlier
An isolated sample is far from its neighbours, so it gets a large ball, and that ball claims a whole region for its distribution. A single generated outlier raises recall; a single real outlier inflates the real support and raises precision. Outliers are not rare in practice: they are exactly the odd samples a generator produces when it fails.
Density and coverage#
Naeem et al. (2020) keep only the balls around real samples, where outliers are rarer and the data are trusted, and count instead of testing membership:
Density replaces precision. It asks how many real balls contain each generated sample, divided by . When the model equals the data its expected value is exactly 1, whatever the distribution or the dimension (Naeem et al., 2020, Lemma 1). The reason is symmetry. Take a generated and the ball of a real . That ball contains when is among the nearest of ‘s candidates, the other real samples and . All candidates are independent draws from one continuous distribution, so every ordering of their distances to is equally likely, and ranks among the first with probability . Linearity of expectation over the pairs gives
Values below 1 mean samples in sparse or empty regions; values above 1, samples crowded into the densest ones.
Coverage replaces recall: the share of real samples whose own ball contains at least one generated sample. A generated outlier cannot raise it, because it can only fall into balls that real samples own. For identical distributions the same symmetry gives its expected value (Lemma 2 of the paper). The ball of misses every generated sample when the nearest of the other points are all real. Every assignment of the labels “real” and “generated” to the ordered distances is equally likely, so this is the chance that draws without replacement from real and generated points are all real:
The paper’s choice of with 10,000 samples on each side gives .
In the one-dimensional example with , the samples 0.2, 0.8 and 1.1 each fall into 2 real balls and 7 into none, so density is : the model piles its samples into the left part of the data. Coverage is , since the balls of 0, 1 and 2 contain a generated sample and the ball of 3 does not. Removing the outlier leaves coverage at , where recall jumped between and .
The two Gaussians again#
The figure draws 2,000 real points from and 2,000 from each model, and scores them with for precision and recall and for density and coverage:
| Model | FID | Precision | Recall | Density | Coverage |
|---|---|---|---|---|---|
| collapsed, | 0.98 | 0.98 | 0.48 | 0.97 | 0.37 |
| matched, | 0 | 0.97 | 0.98 | 1.00 | 0.98 |
| spread out, | 0.98 | 0.88 | 0.99 | 0.81 | 0.90 |
The same FID, opposite precision and recall
Precision and recall separate the two models that FID could not: the collapsed one keeps its precision and loses half its recall, the spread-out one keeps its recall and loses precision. The loss of precision looks small, 0.88, because the real balls at the edge of the data are large and accept many far samples; density, 0.81, reports the same failure more clearly. Coverage reports the collapse most clearly, 0.37: only a third of the real points have a generated sample in their own neighbourhood.
Where the trade-off appears#
Many generators have a knob that trades one property for the other. A VAE can draw its codes from with a temperature instead of the prior: narrower codes give more typical images. That is the of the toy models. The GANs later in the course use the truncation trick: BigGAN truncates its latent distribution along the coordinate axes, and StyleGAN pulls its intermediate latent linearly toward the mean. In each case precision rises as the knob narrows and recall falls. Kynkäänniemi et al. trace this curve for several truncation strategies of StyleGAN, where FID gives a single number per setting.
So precision and recall are reported as a pair, or as a curve over the knob, never averaged into one number. Which end of the curve is right depends on the use: a tool that must never show a broken face wants precision, a data augmenter that must cover rare cases wants recall.
Where it breaks#
The estimates depend on the dimension of the features, and in the wrong direction for real use. Draw real and generated samples from the same standard Gaussian, 2,000 of each, so a perfect metric would report precision and recall of 1:
| Feature dimension | Precision | Recall | Density | Coverage |
|---|---|---|---|---|
| 2 | 0.98 | 0.98 | 1.03 | 0.98 |
| 16 | 0.79 | 0.78 | 1.02 | 0.97 |
| 64 | 0.61 | 0.60 | 1.07 | 0.97 |
In 64 dimensions a perfect model loses 40% of both. The mechanism starts with the distances. For independent , each coordinate difference is , so its square has mean 2 and variance (a squared standard normal has variance 2, as in the shell). Summing independent coordinates, has mean and standard deviation , a relative spread : 1.00 in 2 dimensions, 0.35 in 16 and 0.18 in 64. All distances crowd around .
In such a crowd a shared offset decides membership. Write . The term , with spread , half that of a distance, shifts the distance from to every real point at once. A generated sample slightly nearer the centre than usual falls into many balls; one slightly farther, into none. The expected count stays , by the symmetry argument of density, but it is spread unevenly. In the 64-dimensional run, samples with lie in some ball 90% of the time, the others only 30%, and one lies in 74 balls. Precision counts only whether the count is above 0, so it falls; recall falls by the same argument with the roles swapped.
Real features have hundreds or thousands of dimensions, so the absolute values of k-NN precision and recall mean little, and only comparisons with the same features, and sample size are meaningful. Density and coverage, whose expected values were derived above without using the dimension, stay near 1 and 0.97 (Naeem et al., 2020).
The other dependences follow the same pattern. Small or few samples underestimate the supports and lower both numbers even for a perfect model; the published defaults, with 50,000 samples and with 10,000, are calibrated for that. Everything happens in the feature space of an ImageNet network, which decides what counts as similar, with the caveats of FID. And the cost is quadratic: two sets of 50,000 samples need distances.
What changed#
| FID | PRD | k-NN precision and recall | Density and coverage | |
|---|---|---|---|---|
| Output | one distance | a curve, summarised by and | two numbers | two numbers |
| Model of the data | one Gaussian in feature space | histogram over 20 clusters | union of k-NN balls | k-NN balls around real samples only |
| Separates fidelity from coverage | no | yes | yes | yes |
| Sensitive to outliers | through the moments | little | yes, both sides | much less |
| Perfect model in high dimension | 0 up to the bias | — | well below 1 | near 1 |
What you should remember#
- Equal FID can hide opposite failures: and both give 0.98.
- Precision , recall , estimated from samples in a feature space.
- PRD: histograms over k-means clusters, a curve summarised by and .
- k-NN: unions of balls to the -th neighbour; one outlier can inflate recall or precision.
- Density and coverage use real balls only; density is 1 in expectation for a perfect model, coverage about .
- Report the pair, or a curve over the truncation or temperature knob, never their average.
Code#
No course notebook covers these metrics. The functions take embeddings X (real) and Y (generated) of shape [n, d]; the script scores the three toy models and a perfect model in growing dimension. It runs in a few seconds.
import numpy as np
from scipy.spatial.distance import cdist
def kth_radius(A, k): # distance to the k-th nearest neighbour in A
return np.sort(cdist(A, A), axis=1)[:, k] # column 0 is the point itself
def in_balls(B, A, r): # [len(B), len(A)]: is b in the ball around a?
return cdist(B, A) <= r[None]
def precision_recall(X, Y, k=3):
return in_balls(Y, X, kth_radius(X, k)).any(1).mean(), in_balls(X, Y, kth_radius(Y, k)).any(1).mean()
def density_coverage(X, Y, k=5):
hits = in_balls(Y, X, kth_radius(X, k))
return hits.sum() / (k * len(Y)), hits.any(0).mean()
rng = np.random.default_rng(0)
n = 2000
X = rng.standard_normal((n, 2)) # real data N(0, I)
for s in (0.3, 1.0, 1.7): # collapsed, matched, spread out
Y = s * rng.standard_normal((n, 2))
p, r = precision_recall(X, Y)
d, c = density_coverage(X, Y)
print(f's = {s}: precision {p:.2f} recall {r:.2f} density {d:.2f} coverage {c:.2f}')
for dim in (2, 16, 64): # a perfect model in higher dimensions
X, Y = rng.standard_normal((n, dim)), rng.standard_normal((n, dim))
p, r = precision_recall(X, Y)
d, c = density_coverage(X, Y)
print(f'd = {dim:2d}, identical: precision {p:.2f} recall {r:.2f} density {d:.2f} coverage {c:.2f}')
count = in_balls(Y, X, kth_radius(X, 3)).sum(1) # d = 64: how many real balls hold each generated sample
near = (Y ** 2).sum(1) < dim # closer to the centre than average
print(f'd = 64: mean count {count.mean():.2f}, in some ball {(count[near] > 0).mean():.2f} if |y|^2 < d, '
f'{(count[~near] > 0).mean():.2f} otherwise, largest count {count.max()}')
s = 0.3: precision 0.97 recall 0.47 density 1.00 coverage 0.35
s = 1.0: precision 0.98 recall 0.98 density 0.98 coverage 0.97
s = 1.7: precision 0.86 recall 0.98 density 0.82 coverage 0.91
d = 2, identical: precision 0.98 recall 0.98 density 1.03 coverage 0.98
d = 16, identical: precision 0.79 recall 0.78 density 1.02 coverage 0.97
d = 64, identical: precision 0.61 recall 0.60 density 1.07 coverage 0.97
d = 64: mean count 3.19, in some ball 0.90 if |y|^2 < d, 0.30 otherwise, largest count 74
The first three lines repeat the table of the two Gaussians with another random generator; they differ from it by sampling noise of up to 0.03. The next three are the table of the previous section, and the last line is the uneven count behind its 64-dimensional row: an average near , but concentrated on samples near the centre. The full distance matrix is fine for a few thousand samples; for 50,000 it is computed in blocks.
Next#
Precision, recall, FID and IS all replace a person looking at images by a network looking at features, and inherit what that network cannot see. The next note returns to the person: how to ask people about generated images so that their answers are reliable, and how many answers a conclusion needs.
References#
- M. S. M. Sajjadi, O. Bachem, M. Lucic, O. Bousquet, S. Gelly. Assessing generative models via precision and recall. NeurIPS, 2018. Definition 1 and Theorems 1–2: the decomposition, the support limits and the curve; Section 4: clustering into 20 clusters; Section 4.3 and Figure 7: and for GANs and VAEs.
- T. Kynkäänniemi, T. Karras, S. Laine, J. Lehtinen, T. Aila. Improved precision and recall metric for assessing generative models. NeurIPS, 2019. Section 2: the k-NN estimate, with 50,000 VGG-16 features; Appendix C: truncation strategies.
- M. F. Naeem, S. J. Oh, Y. Uh, Y. Choi, J. Yoo. Reliable fidelity and diversity metrics for generative models. ICML, 2020. Density and coverage; Section 3.3, Lemmas 1 and 2: their expected values; the choice with 10,000 samples.
- R. Isachenko. Deep Generative Models, MIPT and Yandex School of Data Analysis, 2025. Lecture 6: precision and recall with k-NN balls.
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 20.4.3: precision and recall metrics.