Course contents 12 / 34

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 P=N(0,I)P = \mathcal N(0, I) in two dimensions and models Qs=N(0,s2I)Q_s = \mathcal N(0, s^2 I). By the isotropic case of the FID note,

FID(P,Qs)=2(1−s)2.\mathrm{FID}(P, Q_s) = 2(1 - s)^2 .

The value depends only on ∣1−s∣\lvert 1 - s \rvert, so s=0.3s = 0.3 and s=1.7s = 1.7 score the same, 2⋅0.72=0.982 \cdot 0.7^2 = 0.98.

The two models fail in opposite ways. The first is collapsed. Its samples are plausible points of PP, but it rarely leaves the centre: the disc of radius 0.90 holds only the inner third of PP, yet 1−e−0.81/0.18=98.9%1 - e^{-0.81/0.18} = 98.9\% of the model’s samples. Both numbers come from integrating the density of N(0,s2I)\mathcal N(0, s^2 I) over the disc in polar coordinates:

∫0re−ρ2/(2s2)2πs2 2πρ dρ=1−e−r2/(2s2),\int_0^r \frac{e^{-\rho^2/(2s^2)}}{2\pi s^2}\, 2\pi\rho\, d\rho = 1 - e^{-r^2/(2s^2)} ,

which at r=0.9r = 0.9 is 1−e−0.405=0.3331 - e^{-0.405} = 0.333 for s=1s = 1 and 0.9890.989 for s=0.3s = 0.3. 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 PP the real distribution and QQ the model:

precision=Q(supp⁡P),recall=P(supp⁡Q).\begin{aligned} \text{precision} &= Q(\operatorname{supp} P) , \\ \text{recall} &= P(\operatorname{supp} Q) . \end{aligned}

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 ss. 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. QQ has precision α\alpha at recall β\beta if both distributions contain a common part μ\mu:

P=β μ+(1−β) νP,Q=α μ+(1−α) νQ.\begin{aligned} P &= \beta\, \mu + (1 - \beta)\, \nu_P , \\ Q &= \alpha\, \mu + (1 - \alpha)\, \nu_Q . \end{aligned}

A fraction β\beta of the data is covered by the shared part, and a fraction α\alpha of the model’s mass lies in it. For distributions on a finite set of outcomes ω\omega, the best attainable pairs form a curve traced by λ>0\lambda > 0, and every pair below it is attainable too (Sajjadi et al., 2018, Theorem 2):

α(λ)=∑ωmin⁡(λP(ω), Q(ω)),β(λ)=∑ωmin⁡(P(ω), Q(ω)λ).\begin{aligned} \alpha(\lambda) &= \sum_\omega \min\big(\lambda P(\omega),\, Q(\omega)\big) , \\ \beta(\lambda) &= \sum_\omega \min\Big(P(\omega),\, \frac{Q(\omega)}{\lambda}\Big) . \end{aligned}

Where the curve comes from. Fix the ratio λ=α/β\lambda = \alpha / \beta. The decomposition needs βμ≤P\beta \mu \le P and αμ≤Q\alpha \mu \le Q at every outcome, so that the rest parts νP\nu_P and νQ\nu_Q are non-negative. With α=λβ\alpha = \lambda \beta both conditions read α μ(ω)≤min⁡(λP(ω),Q(ω))\alpha\, \mu(\omega) \le \min(\lambda P(\omega), Q(\omega)). Summing over ω\omega, and using that μ\mu sums to 1, gives α≤α(λ)\alpha \le \alpha(\lambda); the choice μ∝min⁡(λP,Q)\mu \propto \min(\lambda P, Q) reaches it, and β=α/λ\beta = \alpha / \lambda is β(λ)\beta(\lambda).

The ends of the curve recover the support definition. As λ→∞\lambda \to \infty, min⁡(λP(ω),Q(ω))\min(\lambda P(\omega), Q(\omega)) tends to Q(ω)Q(\omega) wherever P(ω)>0P(\omega) > 0 and to 0 elsewhere, so the largest precision is Q(supp⁡P)Q(\operatorname{supp} P); as λ→0\lambda \to 0, the largest recall is P(supp⁡Q)P(\operatorname{supp} Q) (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 PP and QQ 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 P=(0.5,0.5)P = (0.5, 0.5) and a collapsed model Q=(1,0)Q = (1, 0), the curve is α(λ)=min⁡(0.5λ,1)\alpha(\lambda) = \min(0.5\lambda, 1) and β(λ)=min⁡(0.5,1/λ)\beta(\lambda) = \min(0.5, 1/\lambda). Up to λ=2\lambda = 2 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

Fb=(1+b2) αβb2α+βF_b = \frac{(1 + b^2)\, \alpha \beta}{b^2 \alpha + \beta}

for b=8b = 8, which leans toward recall, and b=1/8b = 1/8, 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 NNDk(φ)\mathrm{NND}_k(\varphi) for the distance from a feature vector φ\varphi to its kk-th nearest neighbour in its own set, and B(c,r)B(c, r) for the ball of radius rr around cc. Around every real sample put the ball reaching to its kk-th nearest real neighbour; their union is the estimate of where real data live. With

f(φ,Φ)={1,φ∈B(φ′,NNDk(φ′)) for some φ′∈Φ,0,otherwise,f(\varphi, \Phi) = \begin{cases} 1, & \varphi \in B\big(\varphi', \mathrm{NND}_k(\varphi')\big) \text{ for some } \varphi' \in \Phi , \\ 0, & \text{otherwise,} \end{cases}

and real features X={x1,…,xN}X = \{x_1, \dots, x_N\} and generated features Y={y1,…,yM}Y = \{y_1, \dots, y_M\},

precision=1M∑j=1Mf(yj,X),recall=1N∑i=1Nf(xi,Y).\begin{aligned} \text{precision} &= \frac1M \sum_{j=1}^M f(y_j, X) , \\ \text{recall} &= \frac1N \sum_{i=1}^N f(x_i, Y) . \end{aligned}

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 k=3k = 3, 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 X={0,1,2,3}X = \{0, 1, 2, 3\}, generated samples Y={0.2,0.8,1.1,7}Y = \{0.2, 0.8, 1.1, 7\}, k=1k = 1.

Each real sample has a neighbour at distance 1, so each real ball has radius 1 and their union is [−1,4][-1, 4]. Three generated samples lie inside it and 7 does not: precision is 3/43/4.

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 4/44/4. Remove the outlier and recall drops to 2/42/4: the model’s actual samples sit between 0.2 and 1.1 and say nothing about 2 or 3.

Figure

k-NN balls, and an outlier

k-NN precision and recall in one dimensionTwo number lines. Top: segments of radius 1 around the real samples 0, 1, 2, 3; generated samples 0.2, 0.8 and 1.1 lie inside, 7 outside: precision 3/4. Bottom: segments around the generated samples with radii 0.6, 0.3, 0.3 and 5.9; the segment of the outlier 7 covers the real samples 2 and 3: recall 4/4.balls around real samples → precisionprecision = 3/40123571013balls around generated samples → recallrecall = 4/40123571013outlier 7: radius 5.9k-NN precision and recall in one dimensionTwo number lines. Top: segments of radius 1 around the real samples 0, 1, 2, 3; generated samples 0.2, 0.8 and 1.1 lie inside, 7 outside: precision 3/4. Bottom: segments around the generated samples with radii 0.6, 0.3, 0.3 and 5.9; the segment of the outlier 7 covers the real samples 2 and 3: recall 4/4.balls around real samplesprecision = 3/40123571013balls around generated samplesrecall = 4/40123571013outlier 7: radius 5.9
The worked example with k = 1: real samples 0, 1, 2, 3 (grey), generated 0.2, 0.8, 1.1, 7 (blue). Top: balls around real samples; generated samples inside one (green) count toward precision, 3/4. Bottom: balls around generated samples; covered real samples count toward recall. The outlier 7 gets radius 5.9 and alone covers 2 and 3, so recall is 4/4.

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=1kM∑j=1M∑i=1N1[yj∈B(xi,NNDk(xi))],coverage=1N∑i=1N1[∃ j:yj∈B(xi,NNDk(xi))].\begin{aligned} \text{density} &= \frac{1}{kM} \sum_{j=1}^M \sum_{i=1}^N \mathbb 1\big[y_j \in B(x_i, \mathrm{NND}_k(x_i))\big] , \\ \text{coverage} &= \frac1N \sum_{i=1}^N \mathbb 1\big[\exists\, j : y_j \in B(x_i, \mathrm{NND}_k(x_i))\big] . \end{aligned}

Density replaces precision. It asks how many real balls contain each generated sample, divided by kk. 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 yy and the ball of a real xix_i. That ball contains yy when yy is among the kk nearest of xix_i‘s NN candidates, the N−1N - 1 other real samples and yy. All NN candidates are independent draws from one continuous distribution, so every ordering of their distances to xix_i is equally likely, and yy ranks among the first kk with probability k/Nk / N. Linearity of expectation over the MNM N pairs gives

E[density]=1kM⋅MN⋅kN=1.\mathbb E[\text{density}] = \frac{1}{kM} \cdot M N \cdot \frac kN = 1 .

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 xix_i misses every generated sample when the kk nearest of the other N−1+MN - 1 + M 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 kk draws without replacement from N−1N - 1 real and MM generated points are all real:

E[coverage]=1−∏t=1kN−tN+M−t≈1−2−k(M=N large).\begin{aligned} \mathbb E[\text{coverage}] &= 1 - \prod_{t=1}^{k} \frac{N - t}{N + M - t} \\ &\approx 1 - 2^{-k} \quad (M = N \text{ large}) . \end{aligned}

The paper’s choice of k=5k = 5 with 10,000 samples on each side gives 0.9690.969.

In the one-dimensional example with k=1k = 1, the samples 0.2, 0.8 and 1.1 each fall into 2 real balls and 7 into none, so density is 6/(1⋅4)=1.56 / (1 \cdot 4) = 1.5: the model piles its samples into the left part of the data. Coverage is 3/43/4, 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 3/43/4, where recall jumped between 4/44/4 and 2/42/4.

The two Gaussians again#

The figure draws 2,000 real points from N(0,I)\mathcal N(0, I) and 2,000 from each model, and scores them with k=3k = 3 for precision and recall and k=5k = 5 for density and coverage:

ModelFIDPrecisionRecallDensityCoverage
collapsed, s=0.3s = 0.30.980.980.480.970.37
matched, s=1s = 100.970.981.000.98
spread out, s=1.7s = 1.70.980.880.990.810.90
Figure

The same FID, opposite precision and recall

Three models against the same datacollapsed model, s = 0.3: FID 0.98, precision 0.98, recall 0.48; matched model, s = 1: FID 0.00, precision 0.97, recall 0.98; spread-out model, s = 1.7: FID 0.98, precision 0.88, recall 0.99.collapsed model, s = 0.3FID 0.98precision 0.98 · recall 0.48matched model, s = 1FID 0.00precision 0.97 · recall 0.98spread-out model, s = 1.7FID 0.98precision 0.88 · recall 0.99Three models against the same datacollapsed model, s = 0.3: FID 0.98, precision 0.98, recall 0.48; matched model, s = 1: FID 0.00, precision 0.97, recall 0.98; spread-out model, s = 1.7: FID 0.98, precision 0.88, recall 0.99.collapsed model, s = 0.3FID 0.98precision 0.98 · recall 0.48matched model, s = 1FID 0.00precision 0.97 · recall 0.98spread-out model, s = 1.7FID 0.98precision 0.88 · recall 0.99
Real data: 2000 points from N(0, I) (grey); models: 2000 points from N(0, s²I) with s = 0.3, 1 and 1.7 (coloured), the first 260 of each shown. FID = 2(1 − s)² is 0.98 for both s = 0.3 and 1.7. With k = 3, the collapsed model has precision 0.98 and recall 0.48; the spread-out one, precision 0.88 and recall 0.99.

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 N(0,τ2I)\mathcal N(0, \tau^2 I) with a temperature τ<1\tau < 1 instead of the prior: narrower codes give more typical images. That is the ss 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 dimensionPrecisionRecallDensityCoverage
20.980.981.030.98
160.790.781.020.97
640.610.601.070.97

In 64 dimensions a perfect model loses 40% of both. The mechanism starts with the distances. For independent x,y∼N(0,Id)x, y \sim \mathcal N(0, I_d), each coordinate difference is N(0,2)\mathcal N(0, 2), so its square has mean 2 and variance 4⋅2=84 \cdot 2 = 8 (a squared standard normal has variance 2, as in the shell). Summing dd independent coordinates, ∥x−y∥2\lVert x - y \rVert^2 has mean 2d2d and standard deviation 8d\sqrt{8d}, a relative spread 2/d\sqrt{2/d}: 1.00 in 2 dimensions, 0.35 in 16 and 0.18 in 64. All distances crowd around 2d\sqrt{2d}.

In such a crowd a shared offset decides membership. Write ∥y−xi∥2=∥y∥2+∥xi∥2−2 y⊤xi\lVert y - x_i \rVert^2 = \lVert y \rVert^2 + \lVert x_i \rVert^2 - 2\, y^\top x_i. The term ∥y∥2\lVert y \rVert^2, with spread 2d\sqrt{2d}, half that of a distance, shifts the distance from yy 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 kk, by the symmetry argument of density, but it is spread unevenly. In the 64-dimensional run, samples with ∥y∥2<d\lVert y \rVert^2 < d 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, kk 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 kk or few samples underestimate the supports and lower both numbers even for a perfect model; the published defaults, k=3k = 3 with 50,000 samples and k=5k = 5 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 2.5⋅1092.5 \cdot 10^9 distances.

What changed#

FIDPRDk-NN precision and recallDensity and coverage
Outputone distancea curve, summarised by F8F_8 and F1/8F_{1/8}two numberstwo numbers
Model of the dataone Gaussian in feature spacehistogram over 20 clustersunion of k-NN ballsk-NN balls around real samples only
Separates fidelity from coveragenoyesyesyes
Sensitive to outliersthrough the momentslittleyes, both sidesmuch less
Perfect model in high dimension0 up to the bias—well below 1near 1

What you should remember#

  • Equal FID can hide opposite failures: s=0.3s = 0.3 and s=1.7s = 1.7 both give 0.98.
  • Precision =Q(where P lives)= Q(\text{where } P \text{ lives}), recall =P(where Q lives)= P(\text{where } Q \text{ lives}), estimated from samples in a feature space.
  • PRD: histograms over k-means clusters, a curve summarised by F8F_8 and F1/8F_{1/8}.
  • k-NN: unions of balls to the kk-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 1−2−k1 - 2^{-k}.
  • 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 k=3k = 3, 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#