AI Wiki中文/EN

Evaluating generators: quality, coverage and blind spots

生成模型评测

Compute distribution precision and recall, then find distinct distributions with identical moments.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Which failure does a good score hide?

A generator can produce excellent examples of only one class. Another can cover every class but add nonsense. A third can copy a small training collection. A single score may rank them without explaining which problem matters for the intended use.

Evaluation should specify the target distribution, generated distribution, sample budget and representation. FID’s original description compares Gaussian moments of Inception features. Precision and recall for distributions separates missing target mass from extra generated mass. These are different questions, not interchangeable names for image quality. Begin with generative models and covariance.

Finite PRD separates missing and unrelated mass; matching two moments can still leave distributions disjoint.
Finite PRD separates missing and unrelated mass; matching two moments can still leave distributions disjoint.

Moments, shared mass and likelihood

For feature distributions approximated by Gaussians with means μP, μQ and positive-semidefinite covariances CP, CQ, the squared Gaussian Wasserstein distance is:

DG=∥μP−μQ∥22+tr⁡ ⁣(CP+CQ−2(CP1/2CQCP1/2)1/2).D_G=\|\mu_P-\mu_Q\|_2^2+\operatorname{tr}\!\left(C_P+C_Q-2(C_P^{1/2}C_QC_P^{1/2})^{1/2}\right).

The symmetric sandwich permits a real eigendecomposition. In the Gaussian case this is a distribution distance; for arbitrary features it compares only their first two moments. It becomes the named FID protocol only with the specified Inception representation and preprocessing, not with any convenient two-dimensional features. The reference code instead uses a matrix square root of the covariance product and handles numerical problems explicitly.

For finite distributions P and Q on the same state space, the PRD definition asks whether some normalized common component μ can be embedded in both:

P=βμ+(1−β)νP,Q=αμ+(1−α)νQ,α,β∈(0,1].P=\beta\mu+(1-\beta)\nu_P,\qquad Q=\alpha\mu+(1-\alpha)\nu_Q,\qquad \alpha,\beta\in(0,1].

Here α is precision and β recall. The remainder distributions explain extra generated mass or target mass not represented by that component. A curve describes one fixed generator; moving along it does not change a classifier threshold or the generator itself. Its boundary can be computed using positive slopes λ:

α(λ)=∑xmin⁡(λP(x),Q(x)),β(λ)=α(λ)/λ.\alpha(\lambda)=\sum_x\min(\lambda P(x),Q(x)),\qquad \beta(\lambda)=\alpha(\lambda)/\lambda.

This follows because the common component can use at most min(P/β,Q/α) mass at each state. At λ=1 the overlap connects to total variation:

α(1)=β(1)=∑xmin⁡(P(x),Q(x))=1−12∑x∣P(x)−Q(x)∣.\alpha(1)=\beta(1)=\sum_x\min(P(x),Q(x))=1-\tfrac12\sum_x|P(x)-Q(x)|.

Likelihood answers another question: how much probability a model assigns to target observations. On a finite support its average negative log-likelihood is:

NLL⁡(P,Q)=−∑x:P(x)>0P(x)log⁡Q(x)=H(P)+DKL(P∥Q).\operatorname{NLL}(P,Q)=-\sum_{x:P(x)>0}P(x)\log Q(x)=H(P)+D_{\mathrm{KL}}(P\|Q).

It is infinite if Q assigns zero to a state with positive target probability. Good likelihood does not by itself establish suitability for a particular downstream task or absence of memorization.

For a moment-distance counterexample, let P put half its mass at each of −1 and 1; let Q put mass 1/8, 3/4 and 1/8 at −2, 0 and 2. Then:

μP=μQ=0,CP=CQ=1,DG=0,TV⁡(P,Q)=1,EQ[X4]−EP[X4]=3.\mu_P=\mu_Q=0,\quad C_P=C_Q=1,\quad D_G=0,\quad \operatorname{TV}(P,Q)=1,\quad \mathbb E_Q[X^4]-\mathbb E_P[X^4]=3.

The supports are disjoint despite identical first two moments. This is an exact counterexample about moment summaries, not an observed failure rate of a particular Inception model.

Compute the scores on distributions we know

Save as generative_evaluation.py; use Python 3.12 and NumPy 1.26.4. The program implements PRD over four states, weighted moments and a symmetric PSD square root. Tiny negative eigenvalues within its stated numerical tolerance are clipped; genuinely negative covariance eigenvalues raise an error. No image encoder or clustering is used.

With S states and L slopes, PRD costs O(LS), including an L×S intermediate. For n feature vectors of dimension d, moments cost O(nd²) and dense square roots O(d³). Population weights are used here; real sample estimates require a separately specified covariance convention and sample size.

"""Original finite-distribution evaluation and Gaussian-moment counterexamples."""
import json
import numpy as np


def probability(p):
    p = np.asarray(p, dtype=float)
    if p.ndim != 1 or not 1 <= len(p) <= 10000 or not np.isfinite(p).all() or np.any(p < 0) or not np.isclose(p.sum(), 1, atol=1e-12, rtol=0):
        raise ValueError('Expected normalized finite probability vector')
    return p


def prd(p, q, slopes):
    p, q = probability(p), probability(q); slopes = np.asarray(slopes, dtype=float)
    if p.shape != q.shape or slopes.ndim != 1 or not 1 <= len(slopes) <= 1000 or not np.isfinite(slopes).all() or np.any(slopes <= 0):
        raise ValueError('Matching supports and positive finite slopes required')
    mass = np.minimum(slopes[:, None]*p, q).sum(axis=1)
    return mass, mass/slopes


def moments(x, p):
    x = np.asarray(x, dtype=float); p = probability(p)
    if x.ndim != 2 or len(x) != len(p) or not 1 <= x.shape[1] <= 32 or not np.isfinite(x).all():
        raise ValueError('Invalid feature matrix')
    mu = p @ x; delta = x-mu
    return mu, (delta.T*p) @ delta


def psd_root(c):
    c = np.asarray(c, dtype=float)
    if c.ndim != 2 or c.shape[0] != c.shape[1] or not 1 <= len(c) <= 32 or not np.isfinite(c).all() or not np.allclose(c, c.T, atol=1e-12, rtol=0):
        raise ValueError('Expected symmetric finite covariance')
    val, vec = np.linalg.eigh(c)
    if val.min() < -1e-10: raise ValueError('Covariance must be positive semidefinite')
    return (vec*np.sqrt(np.maximum(val, 0))) @ vec.T


def gaussian_distance(mu, c, nu, d):
    mu, nu = np.asarray(mu, dtype=float), np.asarray(nu, dtype=float)
    c, d = np.asarray(c, dtype=float), np.asarray(d, dtype=float)
    if mu.ndim != 1 or mu.shape != nu.shape or c.shape != (mu.size, mu.size) or d.shape != c.shape or not np.isfinite(mu).all() or not np.isfinite(nu).all():
        raise ValueError('Incompatible Gaussian dimensions')
    root = psd_root(c); psd_root(d)
    sandwich = root @ d @ root; sandwich = (sandwich+sandwich.T)/2
    value = float((mu-nu) @ (mu-nu) + np.trace(c+d-2*psd_root(sandwich)))
    if value < -1e-8: raise ArithmeticError('Unexpected negative distance')
    return max(value, 0.)


def demo():
    p = np.array([.5, .5, 0, 0]); slopes = np.array([.25, .5, 1., 2., 4.]); models = {}
    for name, q in [('correct', p), ('drop', [1, 0, 0, 0]), ('noise', [.25, .25, .25, .25]), ('reweight', [.9, .1, 0, 0])]:
        q = probability(q); a, b = prd(p, q, slopes)
        models[name] = dict(precision=a.tolist(), recall=b.tolist(), total_variation=float(abs(p-q).sum()/2),
                            max_precision=float(q[p > 0].sum()), max_recall=float(p[q > 0].sum()))
    x = np.array([[-1.], [1.], [-2.], [0.], [2.]])
    p1 = np.array([.5, .5, 0, 0, 0]); p2 = np.array([0, 0, .125, .75, .125])
    m1, c1 = moments(x, p1); m2, c2 = moments(x, p2)
    fourth_moment_gap = float(abs(p1 @ x[:, 0]**4-p2 @ x[:, 0]**4))
    return dict(slopes=slopes.tolist(), models=models, moment_collision=dict(mean=m1.tolist(), variance=c1.tolist(),
                gaussian_distance=gaussian_distance(m1, c1, m2, c2), total_variation=float(abs(p1-p2).sum()/2),
                fourth_moment_gap=fourth_moment_gap),
                scalar_distance=gaussian_distance([0], [[1]], [2], [[4]]),
                scope='Exact synthetic supports and supplied features; no Inception network, image FID or human-quality score.')


if __name__ == '__main__': print(json.dumps(demo(), indent=2))

For P=[.5,.5,0,0], dropping one mode gives Q=[1,0,0,0]: maximum precision is 1 but maximum recall .5. Adding unrelated mass with Q=[.25,.25,.25,.25] reverses those maxima. Reweighting the same two supported states to [.9,.1,0,0] keeps both maxima at 1, yet the λ=1 point is only (.6,.6). The entire curve carries information that the maxima alone discard. The separate scalar Gaussian example has distance 5: squared mean difference 4 plus squared standard-deviation difference 1.

The measurement pipeline is part of the result

PRD on continuous images requires an empirical representation and approximation. The paper discusses features and discretization; our exact finite calculation skips those sources of estimation error. It cannot establish how a chosen feature network treats a rare object or a culturally specific visual detail.

Keep train/test separation, preprocessing, encoder version, sample count, conditional prompts and selection budget fixed. Report multiple seeds or uncertainty when sampling is involved. A best-of-many selected gallery and an unfiltered sample distribution are different evaluation objects. Distribution fidelity, prompt following, utility and memorization deserve separate checks; a favourable aggregate does not settle all four.

Choose the missing measurement

  1. Calculate. For P=[.5,.5] and Q=[.9,.1], what is the λ=1 PRD point? Answer: Both coordinates equal min(.5,.9)+min(.5,.1)=.6; total variation is .4.
  2. Diagnose. Why does the moment counterexample have zero distance? Answer: Both means are zero and both variances are one, which are all this distance uses. Their fourth moments and supports differ.
  3. Interpret. Do maximum precision and maximum recall both equal to one imply P=Q? Answer: No. The maxima can occur at different curve points. The pair (1,1) being attainable is the stronger condition; mere shared support is insufficient.
  4. Transfer. Can a distance computed on raw toy coordinates be reported as FID? Answer: No. It is a Gaussian moment distance on those coordinates. The representation and preprocessing define the named image metric.

Use disagreements between metrics as evidence

FID provides a useful feature-moment comparison; PRD makes some asymmetric failures visible. Neither paper makes every evaluation problem disappear. Continue with synthetic data to see why similar downstream utility can coexist with a changed data distribution.

Make a prediction, then check

Does zero Gaussian-moment distance imply equal arbitrary distributions?

Choose one answer

Learning objectives

  • Compute finite distribution precision and recall.
  • Explain a zero moment-distance counterexample.
  • Specify the feature space and evaluation protocol.

Prerequisites & connections

Explore related knowledge →

References

  1. GANs Trained by a Two Time-Scale Update Rule Converge to a Nash Equilibrium (v1)
    Martin Heusel; Hubert Ramsauer; Thomas Unterthiner; Bernhard Nessler; Günter Klambauer; Sepp Hochreiter · 2017
  2. Assessing Generative Models via Precision and Recall (NeurIPS2018)
    Mehdi S. M. Sajjadi; Olivier Bachem; Mario Lucic; Olivier Bousquet; Sylvain Gelly · 2018
  3. bioinf-jku/TTUR: fid.py @ec65610
    bioinf-jku/TTUR contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked TTUR v1 Performance Measure/equation8, PRD sections3.2-3.4/opening4 and fixed FID matrix-square-root code. Six paired equations and four explained exercises; exact finite PRD, common-component witnesses, TV duality, PSD Gaussian distance and disjoint-support moment collision. Supplied synthetic features, not image FID or metric benchmark reproduction.

  • Single AI author checked TTUR v1 Performance Measure/equation8, PRD sections3.2-3.4/opening4 and fixed FID matrix-square-root code. Six paired equations and four explained exercises; exact finite PRD, common-component witnesses, TV duality, PSD Gaussian distance and disjoint-support moment collision. Supplied synthetic features, not image FID or metric benchmark reproduction.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial label polish and English mobile-title clipping correction preserved. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.