Compare distributions using total variation and Wasserstein distances, construct couplings, study Kantorovich–Rubinstein duality and Gaussian formulas, and understand high-dimensional sampling costs.
After this lesson you can
Calculate total variation distance and construct a maximal coupling attaining it.
Define Wasserstein distance via couplings and calculate it in 1D using quantiles.
State Kantorovich–Rubinstein duality and interpret it as a WGAN critic.
Derive W₂ distance between Gaussians.
Explain the curse of dimensionality when estimating Wasserstein from samples.
A generative model transforms noise Z into samples gθ(Z), and training it means bringing the law Qθ of those samples closer to the data law P. This needs a distance D(P,Qθ) that can be minimized over θ using gradients. The choice looks technical but determines whether training works.
The canonical example is from Arjovsky, Chintala and Bottou (2017). Let Z∼Unif[0,1], let P be the law of point (0,Z)∈R2 (a vertical segment at x=0), and let Qθ be the law of (θ,Z), the same segment shifted to x=θ. For θ=0 the segments do not touch, so:
Kullback–Leibler divergence is KL(Qθ∥P)=+∞ because Qθ puts mass where P puts none;
Jensen–Shannon divergence, implicitly optimized by the original GAN, equals log2 for every θ=0;
total variation, defined shortly, equals 1 for every θ=0;
Wasserstein distance, also to be defined, equals ∣θ∣.
The first three are constant (or infinite) once supports separate: their gradient with respect to θ is zero and they do not say which way to move. Only the last knows θ=0.1 is closer than θ=5. This is not a toy curiosity: natural images in practice occupy a very low-dimensional subset of R3×256×256, and two such subsets, one for data and one for the model, almost never overlap at training start.
The basic difference is what each distance measures. Total variation asks “is there an event to which P and Q assign very different probabilities?” and does not examine where mass is. Wasserstein asks “how much does transforming one distribution into the other by moving mass cost?”, and thus depends on space geometry. Before formalizing anything, experiment with both.
InteractiveTotal variation versus Wasserstein
Data P and model Qθ (gray is the overlap min(p,q), with mass 1−TV)
Three distances versus θ, with their tangent at the current θ
data P
model Qθ
W1
TV (equals JS in bits)
JS
Shape
Training loss
TV(P,Qθ)1.000
JS(P,Qθ) in bits1.000
KL(Qθ∥P)∞
W1(P,Qθ)2.000
∂/∂θ of TV, JS, W10.00, 0.00, 1
Disjoint supports: TV = JS = 1 and KL = ∞ for any θ this far away. Only W1 distinguishes “far” from “very far”.
Data P are centered at 0 and model Qθ is the same shape shifted by θ. Below, each distance versus θ with its tangent at the current value. With narrow boxes, once ∣θ∣≥w, total variation and Jensen–Shannon (measured in bits, divided by log2) stick at 1 with zero slope while W1=∣θ∣ keeps growing. Press ‘Train’ with each loss from θ=2: with TV or JS the model does not move; with W1 it reaches the data. Switch to Gaussians: the TV gradient is no longer exactly zero, but tiny in the tails; with σ=0.3, training with TV takes about 270 steps versus 19 with W1, and with σ=0.15 the model does not move.
This lesson builds both distance families and their unifying object: a coupling, a way to place P and Q on the same probability space. With couplings, total variation is the minimum probability that two variables with those laws differ, and Wasserstein is the minimum expected cost of moving one to the other. Then we see three results with direct machine-learning consequences: in one dimension optimal transport reduces to sorting; Kantorovich–Rubinstein duality turns W1 into maximizing over Lipschitz functions, exactly the WGAN critic; and Gaussians have a closed formula used by FID. We end with bad news: estimating Wasserstein from high-dimensional samples is exponentially expensive.
Total variation
We work with two probability measures P and Q on the same measurable space (X,F).
Some books define total variation without the supremum over events, as ∫∣p−q∣, obtaining twice our value. Under our convention, TV=1 means “distinguishable with certainty.” The supremum over all events seems impossible to calculate, but an explicit formula appears as soon as P and Q have densities.
A measure dominating both always exists, for example μ=(P+Q)/2: if μ(A)=0, then P(A)=Q(A)=0. The Radon–Nikodym theorem gives densities p=dP/dμ and q=dQ/dμ (absolute continuity with respect to μ). Commonly, μ is Lebesgue measure and p,q are ordinary densities, or μ is counting measure and p,q are mass functions.
Proof
For any event A, P(A)−Q(A)=∫A(p−q)dμ≤∫A(p−q)+dμ≤∫(p−q)+dμ, with equality in both steps if A=A⋆. Since ∫(p−q)dμ=1−1=0, positive and negative parts have the same integral: ∫(p−q)+=∫(p−q)−. Thus Q(A)−P(A)≤∫(p−q)− has the same bound, and supA∣P(A)−Q(A)∣=∫(p−q)+. Adding both halves, ∫∣p−q∣=2∫(p−q)+. Finally, (p−q)+=p−min(p,q), whose integral is 1−∫min(p,q).
For the variational form, if ∥f∥∞≤1, ∣EPf−EQf∣=∫f(p−q)dμ≤∫∣p−q∣dμ=2TV, with equality for f=1A⋆−1(A⋆)c.
∎
Expression 1−∫min(p,q) is the most visual: total variation is mass the two densities do not share. In the motivating figure, the gray region was min(p,q) with mass 1−TV. It is a metric (half the L1 norm of p−q, an L1 norm): symmetric, satisfying the triangle inequality, and zero only if P=Q. It equals 1 exactly when ∫min(p,q)=0, meaning P and Q are mutually singular, like Arjovsky’s two segments.
The last example summarizes total variation’s virtue and flaw: it is blind to geometry. If ϕ is a measurable bijection with measurable inverse, TV(P∘ϕ−1,Q∘ϕ−1)=TV(P,Q): rearrange space however you like and the distance is unchanged, so it cannot know which points are “close.” More generally, for any measurable function ϕ, TV(P∘ϕ−1,Q∘ϕ−1)≤TV(P,Q), because events ϕ−1(B) are only some of the possible events: processing data never increases total variation.
Total variation and optimal tests
Total variation has an operational interpretation making it essential in statistics: it measures how well P can be distinguished from Q with one observation.
Proof
Writing A={ϕ=1}, the sum of errors is P(A)+1−Q(A)=1−(Q(A)−P(A))≥1−TV, with equality when A={q>p}. Bayes error is half that sum.
∎
If TV(P,Q)=0.01, no procedure, however sophisticated, distinguishes the two laws with one observation at Bayes error below 0.495: almost the same as flipping a coin. This is why sampler guarantees (Markov chains, diffusion models) are often stated in total variation: “the output law is at TV distance ε from the target” means no test distinguishes its samples from true ones except with advantage ε.
Couplings
A distance between laws compares two objects living separately. Couplings put them together.
The set Π(P,Q) is never empty: the independent couplingπ=P⊗Q always works. But there are many others. With discrete laws on {1,…,n} and {1,…,m}, a coupling is a nonnegative matrix π∈Rn×m whose rows sum to p and columns to q: a polyhedron that, if all masses pi and qj are positive, has dimension (n−1)(m−1). Couplings do not change the laws of X or Y; they only decide how they relate. That freedom is the tool: many inequalities between laws are proved by building a clever coupling and reasoning about concrete random variables.
The first result connects couplings with total variation.
The proof is short and you will do it step by step in the first guided exercise. The maximal coupling construction is useful now because it appears in the next interactive. Let w=∫min(p,q)=1−TV. With probability w, draw one point Z from density min(p,q)/w and set X=Y=Z. With probability 1−w, draw X from density (p−q)+/(1−w) and independently Y from (q−p)+/(1−w). Both branches give correct marginals because min(p,q)+(p−q)+=p and min(p,q)+(q−p)+=q. In the second branch X=Y almost surely, since supports of (p−q)+ and (q−p)+ are disjoint. In words: leave common mass in place and move only excess.
This pattern, “construct two variables on the same space that coincide with high probability,” is central to studying Markov-chain convergence: if two chain copies, one from an arbitrary state and another from the stationary distribution, meet at time τ, then total variation at step t is bounded by P(τ>t). You will use it to bound mixing times.
Optimal transport and Wasserstein distances
Total variation counts whether mass must move, not how far. To let distance see geometry, assign cost c(x,y)≥0 to moving a unit of mass from x to y and seek the cheapest coupling.
The problem has two historical formulations. Gaspard Monge (1781) sought a map T pushing P to Q (T(X)∼Q if X∼P) while minimizing E[c(X,T(X))]. But such a map may not exist: if P=δ0 and Q=21(δ−1+δ1), no function sends one point to two places. Leonid Kantorovich (1942) relaxed the problem by permitting mass to split: instead of a map, a coupling π, where π(dx,dy) is the mass traveling from x to y. A deterministic plan y=T(x) is the special case where π lives on the graph of T.
With discrete laws, p at points x1,…,xn and q at y1,…,ym, the Kantorovich problem is a linear program:
It has nm variables and n+m equality constraints (one redundant), and its feasible set is the coupling polyhedron. Linear programming theory ensures the minimum occurs at a vertex, and vertices of this polyhedron have at most n+m−1 nonzero entries: an optimal plan splits mass very little. If n=m and all masses are 1/n, vertices are precisely permutation matrices divided by n (Birkhoff–von Neumann theorem), so optimal transport between two equiprobable clouds of n points is an assignment problem: match points one to one.
Proof
(1) and (2) are theorems from Villani (2009), chapters 4 and 6. Existence follows because Π(P,Q) is compact for weak convergence (marginals are fixed) and π↦∫ρpdπ is lower semicontinuous. The triangle inequality uses the gluing lemma: given optimal couplings of (P,Q) and (Q,R), a triple (X,Y,Z) exists with those pairwise laws, and then Wp(P,R)≤E[ρ(X,Z)p]1/p≤E[ρ(X,Y)p]1/p+E[ρ(Y,Z)p]1/p by Minkowski’s inequality in Lp.
(3) Take an optimal coupling for Wr. By Jensen’s (or Lyapunov’s) inequality, E[ρp]1/p≤E[ρr]1/r=Wr, and Wp is the infimum of the first quantity over all couplings.
(4) Let (X,Y) be the maximal coupling. Since ρ(X,Y)≤D1[X=Y], we have W1≤Eρ(X,Y)≤DP(X=Y)=DTV. For the other bound, in any coupling ρ(X,Y)≥δ1[X=Y], hence Eρ(X,Y)≥δP(X=Y)≥δTV by the coupling inequality; take the infimum.
∎
Point (4) contains the promised unification. With the discrete metricρ(x,y)=1[x=y], coupling cost is P(X=Y) and W1 is exactly TV. Total variation is optimal transport with a cost that does not distinguish short and long jumps. The next interactive shows concrete plans.
InteractiveTransport plans
Mass from P travels to Q: band thickness ∝π(x,y)
Plan π: rows x (from P), columns y (from Q)
P
Q
mass that moves (x=y)
mass that stays (x=y)
Cost c(x,y)
Coupling
Plan cost E[c(X,Y)]1.000
W1(P,Q)1.000
W2(P,Q)1.000
TV(P,Q)0.143
Stationary mass ∑xπ(x,x)0.000
1−TV (maximum possible)0.857
Convex cost: the optimal plan is monotone. Mass is matched in order, without crossings, like quantiles.
Drag bars of P (top) and Q (bottom) on {0,…,7}. The optimal plan appears as bands carrying each bar’s mass to those of Q (thickness proportional to mass; gray stays put) and as matrix π(x,y) with its marginals. Start with shifted uniforms and cost ∣x−y∣2: all mass shifts one step, as a staircase. Switch to 1{x=y}: maximal coupling appears, keeping mass min(p,q) still and making one long jump of mass 1/7=TV. What does concave cost ∣x−y∣ do? Also compare with independent coupling.
The shifted-uniform example, P uniform on {0,…,6} and Q uniform on {1,…,7}, separates three cost types. There are two candidate plans: the staircase, taking each k to k+1, and the jump, leaving {1,…,6} still and taking mass 1/7 from 0 to 7.
Cost
Staircase
Jump
Optimum
∣x−y∣
1
71⋅7=1
both (tie)
∣x−y∣2
1
71⋅49=7
staircase: W2=1
∣x−y∣
1
717=0.378
jump
1{x=y}
1
71=0.143
jump: TV=1/7
Strictly convex costs in ∣x−y∣ prefer many short moves; concave costs prefer a few long moves and leaving shared mass still; linear is on the boundary and permits many optimal plans. This is why W2 is the natural choice for “smooth” transport, and why the next section’s result holds.
The one-dimensional case: sorting suffices
On the real line, optimal transport with convex cost has an explicit solution: match in order. Let F and G be distribution functions of P and Q, and F−1, G−1 their quantile functions.
The proof has three simple pieces.
It is a coupling. By the probability integral transform, F−1(U)∼P and G−1(U)∼Q. Since both are increasing functions of the same U, the coupling is comonotone: when one rises the other does not fall. Its cost is the stated integral.
It is optimal: Monge inequality. Let h be convex and let a≤b, c≤d be real numbers. Then
h(a−c)+h(b−d)≤h(a−d)+h(b−c).
That is, matching “in order” (a with c, b with d) costs at most as much as “crossed” matching. To see this, call u=a−d and v=b−c the crossed-side arguments. The ordered-side arguments a−c and b−d both lie between u and v (because a−d≤a−c≤b−c and a−d≤b−d≤b−c) and have the same sum as u+v. Write a−c=λu+(1−λ)v; then b−d=(1−λ)u+λv, and adding convexity inequalities h(λu+(1−λ)v)≤λh(u)+(1−λ)h(v) and h((1−λ)u+λv)≤(1−λ)h(u)+λh(v) yields the inequality. With h(t)=∣t∣p, p≥1, apply it to samples: if P and Q are empirical measures of n points with mass 1/n, an optimal plan is a permutation σ, and if σ has a crossing (xi<xk with yσ(i)>yσ(k)), swapping both pairs cannot increase cost and reduces crossings by at least one. Finitely many swaps reach ordered matching x(i)↔y(i), which is therefore optimal. General laws are approximated by empirical measures and passed to the limit using optimal-plan stability (Villani, 2009, chapter 5).
The W1 formula with F and G. The area between graphs of F and G can be measured vertically or horizontally. Vertically it is ∫∣F(x)−G(x)∣dx; horizontally, over levels t∈(0,1), it is ∫01F−1(t)−G−1(t)dt. Formally, ∣F(x)−G(x)∣=∫01∣1[t≤F(x)]−1[t≤G(x)]∣dt, and since t≤F(x)⟺F−1(t)≤x, the Fubini–Tonelli theorem exchanges integrals.
InteractiveIn 1D optimal transport sorts
Matching σ between samples x (top) and y (bottom); the last swap is magenta
Cost at each step: it never increases
Quantile functions F−1, G−1: the integral of the squared difference is W22
sample x∼P and its quantile F−1
sample y∼Q and its quantile G−1
swap removing a crossing
ordered-matching cost
step 0 of 8
Cost ∣x−y∣p
Remaining crossings20
Cost n1∑i∣xi−yσ(i)∣23.183
Ordered cost =W221.451
W2 between the samples1.205
Random matching with 20 crossings. Press play: each step swaps two crossing pairs and removes at least one crossing.
Two samples of 8 points, x∼P above and y∼Q below, start linked by a random matching. Each step swaps two crossing pairs (magenta; dashed ones are before), choosing the swap that reduces cost most, and removes at least one crossing. The left plot shows cost never rises and ends at the dashed line, ordered matching cost. Right: empirical quantile functions; the shaded area between them is W1 and, with p=2, the integral of their squared difference is W22. With p=1, find a step with zero change: it is a tie, not an improvement.
Two practical consequences. First, cost: Wp between two samples of size n on the line is computed by sorting, in O(nlogn), versus O(n3) for general assignment. Second, conceptually: P↦F−1 is an isometry from (Pp(R),Wp) into a subset of Lp(0,1), the increasing functions. This permits, for example, averaging distributions by averaging quantile functions (the 1D Wasserstein barycenter), preserving distribution shape rather than mixing as averaging densities would.
Kantorovich–Rubinstein duality
The Kantorovich problem is a linear program, and every linear program has a dual. In the discrete case associate multiplier fi with each row constraint and gj with each column constraint. Linear-programming weak duality and strong duality (the primal is feasible and bounded) give
π∈Π(p,q)mini,j∑cijπij=f,gmax{i∑fipi+j∑gjqj:fi+gj≤cij para todo i,j}.
Kantorovich’s economic interpretation: a carrier charges fi to collect at xi and gj to deliver at yj; the constraint says the charge never exceeds doing it yourself, and the carrier maximizes revenue. At optimum the total price equals your minimum cost, and complementary slackness says route i→j is used only if fi+gj=cij.
When cost is a distance, c(x,y)=ρ(x,y), the dual simplifies. Formulate the problem on the union of both supports (with zero mass where needed), so each point is both a possible origin and destination. Given feasible pair (f,g), replacing f with the largest function compatible with g, f~(x)=miny{ρ(x,y)−g(y)}, does not worsen the objective, and f~ is 1-Lipschitz as a minimum of 1-Lipschitz functions. Then the best g compatible with 1-Lipschitz f~ is −f~: on one hand f~(x)−f~(y)≤ρ(x,y); on the other, setting x=y in the constraint gives g(y)≤−f~(y). The whole dual reduces to one function.
The “≥” inequality is one line and worth keeping handy: if (X,Y) is any coupling and f is 1-Lipschitz,
EPf−EQf=E[f(X)−f(Y)]≤E[ρ(X,Y)],
and taking the infimum over couplings gives EPf−EQf≤W1. Equality is strong duality: for finite-support laws it is the preceding linear-program argument, and the general case follows by approximation (Villani, 2009, theorem 5.10). This is Kantorovich–Rubinstein duality.
Integral probability metrics and WGAN
The dual form belongs to a general family. For a function class F, the integral probability metric is dF(P,Q)=supf∈F∣EPf−EQf∣. Changing the class gives known distances:
Class F
dF(P,Q)
{f:∥f∥∞≤1}
2TV(P,Q)
{f:∥f∥Lip≤1}
W1(P,Q)
{1(−∞,t]:t∈R}
Kolmogorov distance supt∣F(t)−G(t)∣
unit ball of a reproducing kernel Hilbert space
MMD (maximum mean discrepancy)
The smaller the class, the weaker the distance and the easier it is to estimate from samples. Kolmogorov distance is controlled by the Glivenko–Cantelli theorem.
The Wasserstein GAN takes the dual form literally. A critic fw (a neural network) approximates the supremum, and the generator minimizes what the critic measures:
Under regularity assumptions, the gradient with respect to θ of W1(P,Qθ) is −EZ[∇θf⋆(gθ(Z))], with f⋆ the optimal critic, and is useful even if supports do not touch: in the segment example f⋆(x,z)=−xsignθ pushes Qθ toward P with constant force. The difficult part is imposing a Lipschitz constraint on a network: the original paper clipped weights to an interval, and Gulrajani et al. (2017) replaced this with a critic-gradient-norm penalty. See details in WGAN.
Wasserstein between Gaussians
For distance W2 with Euclidean metric in Rd there is a closed formula between Gaussians, reusing everything seen about the multivariate Gaussian.
This is the formula for Wasserstein distance between Gaussians. The second summand is the Bures term (the square of Bures distance between covariance matrices), and roots are symmetric square roots of positive semidefinite matrices.
Proof
Step 1: separate means. For any coupling (X,Y), write X=m1+X~ and Y=m2+Y~ with centered X~,Y~. Then E∥X−Y∥2=∥m1−m2∥2+EX~−Y~2, because cross term 2(m1−m2)⊤E[X~−Y~] vanishes. It suffices to treat the centered case.
Step 2: cost depends only on cross-covariance. With K=E[X~Y~⊤],
EX~−Y~2=trΣ1+trΣ2−2trK.
Minimizing cost means maximizing trK over possible matrices K. The only constraint is that joint covariance [Σ1K⊤KΣ2] be positive semidefinite.
Step 3: upper bound on trK. Also suppose Σ2≻0 (the general case follows by continuity). By the Schur complement, joint matrix is positive semidefinite if and only if Σ2−K⊤Σ1−1K⪰0. With B=Σ1−1/2KΣ2−1/2 this is equivalent to I−B⊤B⪰0, that is ∥B∥2≤1. Now
by von Neumann’s trace inequality, ∣tr(BM)∣≤∥B∥2∑iσi(M). Nuclear norm of M=Σ21/2Σ11/2 is the sum of its singular values, roots of eigenvalues of M⊤M=Σ11/2Σ2Σ11/2. Thus trK≤tr(Σ11/2Σ2Σ11/2)1/2, and any coupling’s cost is at least that in the formula.
Step 4: the affine map attains the bound. Write S=Σ11/2Σ2Σ11/2. If X~∼N(0,Σ1) and Y~=AX~, by the affine transformation of a GaussianY~ is Gaussian with covariance AΣ1A=Σ1−1/2S1/2S1/2Σ1−1/2=Σ2, hence a valid coupling. Its cross-covariance is K=Σ1A=Σ11/2S1/2Σ1−1/2, similar to S1/2, so trK=trS1/2 and the bound is attained.
∎
Three readings of the formula:
Commuting matrices. If Σ1Σ2=Σ2Σ1 (e.g. both diagonal), then S1/2=Σ11/2Σ21/2 and the Bures term is Σ11/2−Σ21/2F2. In d=1 this gives (s1−s2)2: comparing Gaussians in W2 compares means and standard deviations, not variances.
Gelbrich bound. Steps 1 to 3 do not use that P and Q are Gaussian, only their means and covariances. For arbitrary laws with those first two moments, the formula is a lower bound on W22, exact for Gaussians.
FID. Fréchet Inception Distance of Heusel et al. (2017), the standard image-generator metric, is this formula applied to Gaussians fitted to Inception network activations on real and generated images. It is often written using tr(Σ1Σ2)1/2, equal to trS1/2 because Σ1Σ2 is similar to S. By the Gelbrich bound, FID only sees the first two activation moments.
Empirical measure convergence and the curse of dimension
Given X1,…,Xn∼iidP, the empirical measurePn=n1∑iδXi is the most natural approximation to P. How fast does it converge? In total variation, never: if P has a density, Pn is discrete and TV(Pn,P)=1 for every n (event {X1,…,Xn} has probability 1 under Pn and 0 under P). It does converge in Wasserstein, but its rate depends brutally on dimension.
This result about the empirical measure convergence rate is a special case of Fournier and Guillin (2015), who give rates for all Wp and laws with finite moments rather than bounded support. The lower bound has a four-line proof explaining the curse.
Proof
(Lower bound for uniform.) Fix sample Sn={X1,…,Xn}. In any coupling (X,Y) of P and Pn, Y∈Sn, so ∥X−Y∥≥dist(X,Sn) and therefore W1(P,Pn)≥EX∼P[dist(X,Sn)]. If ωd is the unit-ball volume, probability that X falls within distance ≤r of any sample point is at most nωdrd (union bound on the n balls). Then, with r0=(nωd)−1/d,
(Upper bound in d=1.) By the previous theorem, W1(Pn,P)=∫∣Fn(x)−F(x)∣dx. Since nFn(x)∼Bin(n,F(x)), Jensen’s inequality gives E∣Fn(x)−F(x)∣≤F(x)(1−F(x))/n≤1/(2n), and integrating over [0,1] gives EW1≤1/(2n).
∎
The geometric intuition: n points “cover” [0,1]d with balls of volume 1/n, whose radius is order n−1/d, and a typical point of P is that far from its nearest sample. In d=1 radius 1/n is smaller than statistical fluctuation n−1/2, which dominates. From d=3 onward geometry dominates.
InteractiveThe curse of dimensionality in Wasserstein
W1 between two samples of size n from Unif[0,1]d (log-log)
Two samples of size 64 (coordinates 1 and 2) and their optimal matching
theoretical slope through the last point
target accuracy ε
sample 1
sample 2
Dimension d
Fitted slope...
Theoretical slope−1/3 = −0.333
Mean W1 with n=512...
Samples for W1≈ε...
Factor in n needed to halve the error× 8
Calculating 7 sample sizes with exact optimal assignment...
For each dimension d, draw two independent samples of size n from uniform on [0,1]d and calculate W1 exactly between them (in d=1 by sorting; elsewhere by optimal assignment with the Hungarian algorithm). On log–log scales the slope is −1/2 in d=1, somewhat less in d=2 due to factor logn, and −1/d from d=3. The selected dimension is highlighted with a dashed theoretical line through its last point, others faded. Right: two samples of 64 points joined by optimal matching: in d=10, although both clouds come from the same law, pairs are far apart. Move ε and see how many samples are needed.
The figure’s numbers are the curse in pure form. With slope −1/d, halving error requires multiplying n by 2d: by 8 in d=3 and by 1024 in d=10. For an image generator with d in the hundreds of thousands, W1 between finite samples directly estimates nothing useful. Three practical consequences:
What is estimated is something else. Comparing two samples of size n from the same law gives W1 of order n−1/d, not zero. A small empirical value means something only relative to that floor.
Variants escaping the curse change the distance.Sliced Wasserstein averages Wp between one-dimensional projections ⟨u,X⟩ onto random directions u; each projection is a 1D problem solved by sorting and converges at rate n−1/2. Entropic regularization (Sinkhorn algorithm) also improves sample complexity, at the cost of bias depending on the regularization parameter (Peyré and Cuturi, 2019).
WGAN does not estimate W1. A limited-capacity critic computes a supremum over a much smaller class than all 1-Lipschitz functions: a weaker integral probability metric, and precisely for that reason estimable.
Wasserstein, convergence in distribution and other divergences
This is theorem 6.9 of Villani (2009). Three examples clarify the differences:
δ1/n→δ0 in distribution and in Wp (Wp=1/n), but not in total variation (TV=1). Total variation is stronger than weak convergence: if TV(Pn,P)→0, then EPnf→EPf for every bounded f, continuous or not.
Pn=(1−n1)δ0+n1δn converges in distribution to δ0, but W1(Pn,δ0)=n1⋅n=1 for every n: a shrinking mass going farther away prevents first-moment convergence. Here TV(Pn,δ0)=1/n→0: neither distance dominates the other in general.
In R, if P is supported on [a,b] and Pn is the empirical measure of n observations of P, W1(Pn,P)=∫ab∣Fn−F∣≤(b−a)supx∣Fn(x)−F(x)∣, tending to zero almost surely by Glivenko–Cantelli. For arbitrary laws supported on [a,b], convergence in W1 and uniform convergence of distribution functions toward a continuous F go hand in hand.
It remains to place Kullback–Leibler divergence, studied in information theory. It is not a distance (not symmetric) and KL(P∥Q) is infinite as soon as P puts mass where Q does not, but it controls total variation: Pinsker’s inequality states TV(P,Q)≤KL(P∥Q)/2. The practical hierarchy is:
TV
KL
JS
W1
W2
Distance?
yes
no
its square root, yes
yes
yes
Sees geometry?
no
no
no
yes
yes
Disjoint supports
1
∞
log2
distance between supports
distance between supports
Empirical measure of continuous law
does not converge
∞
does not converge
n−1/d (d≥3)
n−1/d (d≥5)
Gaussians
no simple formula
closed formula
no simple formula
no simple formula
closed formula
(The W2 rate is Fournier and Guillin’s: EW22(Pn,P) decays as n−2/d for d>4, and in low dimensions n−1/2 dominates.)
These distances recur throughout the course. In generative models, flow matching couples noise and data with optimal transport couplings, and diffusion-model guarantees are stated in TV and W2. In deployment, monitoring distribution shift between training and production data compares two laws using one of these distances, and everything about geometry, scale and sample size determines which distance makes sense.
Implementation from scratch
Start with total variation and maximal coupling between two histograms. The coupling is constructed exactly as in the proof: common mass on the diagonal and excess coupled independently off it.
[ ]Total variation and maximal couplingBrowser
import numpy as np
from scipy import stats
rng = np.random.default_rng(0)
def tv_hist(p, q):
"""Variación total entre dos funciones de masa sobre el mismo soporte."""
p, q = np.asarray(p, float), np.asarray(q, float)
return 0.5 * np.abs(p - q).sum()
def maximal_coupling(p, q):
"""Plan con marginales p y q que deja quieta la masa min(p, q)."""
p, q = np.asarray(p, float), np.asarray(q, float)
m = np.minimum(p, q)
tv = 1 - m.sum()
pi = np.diag(m)
if tv > 1e-15:
# los excesos (p - m) y (q - m) tienen soportes disjuntos: fuera de la diagonal
pi = pi + np.outer(p - m, q - m) / tv
return pi
p = np.array([0.10, 0.20, 0.40, 0.20, 0.10, 0.00])
q = np.array([0.00, 0.10, 0.20, 0.30, 0.25, 0.15])
pi = maximal_coupling(p, q)
print("marginales correctas:", np.allclose(pi.sum(axis=1), p), np.allclose(pi.sum(axis=0), q))
print(f"TV = {tv_hist(p, q):.3f} P(X != Y) = {1 - np.trace(pi):.3f} P(A*) - Q(A*) = {(p - q)[p > q].sum():.3f}")
# muestreamos pares (X, Y) del acoplamiento y contamos
idx = rng.choice(pi.size, size=200_000, p=pi.ravel())
X, Y = np.unravel_index(idx, pi.shape)
print(f"frecuencia de X != Y en 200 000 pares: {np.mean(X != Y):.4f}")
print(f"acoplamiento independiente: P(X != Y) = {1 - np.sum(p * q):.3f}")
# la cota de Le Cam: TV(Bin(n, p), Pois(np)) <= n p (1 - e^{-p})
for n, lam in [(10, 2.0), (100, 2.0), (1000, 2.0), (100, 3.0)]:
pp = lam / n
k = np.arange(n + 1)
tv = 0.5 * (np.abs(stats.binom.pmf(k, n, pp) - stats.poisson.pmf(k, lam)).sum() + stats.poisson.sf(n, lam))
print(f"n = {n:5d}, lambda = {lam}: TV = {tv:.5f} cota = {n * pp * (1 - np.exp(-pp)):.5f}")
The maximal coupling attains P(X=Y)=TV=0.4, while the independent one mismatches 81.5% of the time with the same marginals. Le Cam’s bound is loose (between 7 and 12 times the true value in these cases) but has the right order: both columns fall as 1/n with fixed λ. The term stats.poisson.sf(n, lam) adds Poisson mass above n, where the binomial has none.
Now the Kantorovich problem as a linear program, with its dual. Use scipy.optimize.linprog with HiGHS and check Kantorovich–Rubinstein duality: the optimal potential, after transformation f~(x)=miny{∣x−y∣−g(y)}, is 1-Lipschitz and attains W1.
[ ]Kantorovich problem as a linear programBrowser
import numpy as np
from scipy.optimize import linprog
x = np.arange(6.0) # soporte común {0, ..., 5}
C = np.abs(x[:, None] - x[None, :]) # coste |x - y|
n = len(x)
# primal: min <C, pi> con filas que suman p y columnas que suman q
A_eq = np.vstack([np.kron(np.eye(n), np.ones((1, n))), # sumas por filas
np.kron(np.ones((1, n)), np.eye(n))]) # sumas por columnas
primal = linprog(C.ravel(), A_eq=A_eq, b_eq=np.concatenate([p, q]), bounds=(0, None), method="highs")
plan = primal.x.reshape(n, n)
# dual: max p.f + q.g con f_i + g_j <= C_ij (variables libres)
dual = linprog(-np.concatenate([p, q]), A_ub=A_eq.T, b_ub=C.ravel(), bounds=(None, None), method="highs")
f, g = dual.x[:n], dual.x[n:]
w1_cdf = np.abs(np.cumsum(p - q))[:-1].sum() # integral de |F - G| con separación 1
print(f"primal = {primal.fun:.4f} dual = {-dual.fun:.4f} integral de |F - G| = {w1_cdf:.4f}")
# transformación c: el mejor f compatible con g es 1-lipschitziano
phi = (C - g[None, :]).min(axis=1)
print("potencial phi (desplazado a phi(0) = 0):", np.round(phi - phi[0], 3))
print("¿1-lipschitziano?", bool(np.all(np.abs(np.diff(phi)) <= 1 + 1e-9)))
print(f"E_P phi - E_Q phi = {p @ phi - q @ phi:.4f}")
i, j = np.nonzero(plan > 1e-12)
print("holgura complementaria phi(x) - phi(y) = |x - y| en las rutas usadas:", np.allclose(phi[i] - phi[j], C[i, j]))
print("plan óptimo devuelto por HiGHS:\n", np.round(plan, 3))
The optimal critic is ϕ(x)=−x: since F≥G everywhere (Q is to the right of P), all mass travels right and the linear witness measures it all. Notice the plan returned by HiGHS: it is not monotone (mass of 0 goes to 2 while some of 1 stays at 1), yet it is optimal. With cost ∣x−y∣, when all mass moves in the same direction, any plan moving only right costs the same, E[Y]−E[X]. This is the shifted-uniform table’s tie.
In one dimension, sorting suffices. Check it against general optimal assignment and SciPy:
[ ]Wasserstein in 1D: sorting versus assignmentBrowser
import numpy as np
from scipy import stats
from scipy.optimize import linear_sum_assignment
rng = np.random.default_rng(1)
def w_sorted(x, y, p=1):
"""W_p entre dos muestras del mismo tamaño: empareja en orden."""
return float(np.mean(np.abs(np.sort(x) - np.sort(y)) ** p) ** (1 / p))
xs = rng.normal(0.0, 1.0, size=400)
ys = rng.exponential(1.0, size=400)
for pexp in (1, 2):
Cm = np.abs(xs[:, None] - ys[None, :]) ** pexp
r, c = linear_sum_assignment(Cm) # O(n^3), sin usar el orden
print(f"p = {pexp}: asignación óptima {Cm[r, c].mean() ** (1 / pexp):.6f} ordenando {w_sorted(xs, ys, pexp):.6f}")
print(f"scipy.stats.wasserstein_distance (p = 1): {stats.wasserstein_distance(xs, ys):.6f}")
# W1 como área entre las funciones de distribución
z = np.sort(np.concatenate([xs, ys]))
F = np.searchsorted(np.sort(xs), z[:-1], side="right") / len(xs)
G = np.searchsorted(np.sort(ys), z[:-1], side="right") / len(ys)
print(f"integral de |F - G|: {np.sum(np.abs(F - G) * np.diff(z)):.6f}")
All four figures agree to six decimal places: general assignment, which knows nothing about order, finds the same cost as ordered matching, and the area between distribution functions gives the same W1.
Now the Gaussian formula. Check that affine map A is symmetric, pushes Σ1 to Σ2 and has Monte Carlo cost W22; and measure the sample-estimation “floor”: W2 between independent samples of the same law, whose true value is zero.
[ ]W₂ between Gaussians and its optimal planBrowser
import numpy as np
from scipy.linalg import sqrtm
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cdist
def sqrtm_psd(S):
"""Raíz cuadrada simétrica de una matriz semidefinida positiva."""
w, V = np.linalg.eigh(S)
return (V * np.sqrt(np.clip(w, 0, None))) @ V.T
def w2_gauss(m1, S1, m2, S2):
r = sqrtm_psd(S1)
bures2 = np.trace(S1 + S2 - 2 * sqrtm_psd(r @ S2 @ r))
return float(np.sqrt(np.sum((m1 - m2) ** 2) + max(bures2, 0.0)))
def gauss_map(m1, S1, m2, S2):
r = sqrtm_psd(S1)
ri = np.linalg.inv(r)
A = ri @ sqrtm_psd(r @ S2 @ r) @ ri
return A, (lambda X: m2 + (X - m1) @ A.T)
rng = np.random.default_rng(2)
a, b = rng.normal(0, 1, 200_000), rng.normal(1, 2, 200_000)
print(f"1D, N(0,1) frente a N(1,4): fórmula {w2_gauss(np.zeros(1), np.eye(1), np.ones(1), 4 * np.eye(1)):.4f}"
f" ordenando 200 000 muestras {w_sorted(a, b, 2):.4f}")
m1, S1 = np.array([0.0, 0.0]), np.array([[2.0, 0.9], [0.9, 1.0]])
m2, S2 = np.array([2.0, 1.0]), np.array([[0.5, -0.3], [-0.3, 1.5]])
W = w2_gauss(m1, S1, m2, S2)
A, T_map = gauss_map(m1, S1, m2, S2)
print(f"\n2D: W2 = {W:.4f}")
print("A simétrica:", np.allclose(A, A.T), " autovalores de A:", np.round(np.linalg.eigvalsh(A), 3))
print("A S1 A = S2:", np.allclose(A @ S1 @ A, S2))
X = rng.multivariate_normal(m1, S1, size=200_000)
print(f"Monte Carlo E|X - T(X)|^2 = {np.mean(np.sum((X - T_map(X)) ** 2, axis=1)):.4f} W2^2 = {W ** 2:.4f}")
print(f"tr (S1 S2)^(1/2) = {np.trace(sqrtm(S1 @ S2)).real:.6f} tr S^(1/2) = {np.trace(sqrtm_psd(sqrtm_psd(S1) @ S2 @ sqrtm_psd(S1))):.6f}")
# dos muestras de la MISMA gaussiana: la distancia verdadera es 0
for n in (100, 300, 900):
Xs, Ys = rng.multivariate_normal(m1, S1, size=n), rng.multivariate_normal(m1, S1, size=n)
Cm = cdist(Xs, Ys, "sqeuclidean")
r, c = linear_sum_assignment(Cm)
print(f" W2 entre dos muestras de P de tamaño {n:4d}: {np.sqrt(Cm[r, c].mean()):.4f}")
Map A has positive eigenvalues: it is the gradient of convex function 21x⊤Ax, as Brenier’s theorem requires for quadratic-cost optimal plans. The trace of (Σ1Σ2)1/2, the FID form, matches that of S1/2. Two 100-point samples from the same Gaussian are at W2≈0.52, 20% of distance between P and Q; with 900 points, still 0.24. Any sample estimate of W2(P,Q) carries error of that size, decaying slowly in high dimension as seen for empirical measures.
Finally, directly measure rate n−1/d: W1 between independent uniform samples on [0,1]d, with exact assignment and log–log slope.
[ ]Measuring the n^(-1/d) rateBrowser
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cdist
def w1_two_samples(n, d, rng):
Xs, Ys = rng.random((n, d)), rng.random((n, d))
Cm = cdist(Xs, Ys)
r, c = linear_sum_assignment(Cm)
return Cm[r, c].mean()
ns = np.array([32, 64, 128, 256])
rng = np.random.default_rng(3)
for d in (1, 2, 5, 10):
w = np.array([np.mean([w1_two_samples(n, d, rng) for _ in range(3)]) for n in ns])
s = np.polyfit(np.log(ns), np.log(w), 1)[0]
print(f"d = {d:2d}: W1 = {np.round(w, 4)} pendiente {s:+.3f} teórica {-0.5 if d <= 2 else -1 / d:+.3f}")
plt.loglog(ns, w, "o-", label=f"d = {d}")
plt.xlabel("n"); plt.ylabel("W1 entre dos muestras"); plt.legend(); plt.show()
At these sizes measured slopes are of theoretical order but not exact: in d=5 and d=10 they are somewhat steeper (−0.24 and −0.13 versus −0.2 and −0.1), because with n≤256 lower-order terms of EW1 still matter and decay faster, and there are only three repetitions; in d=2 the logarithmic factor softens it. The important part is the order of magnitude of column d=10: with 256 points per sample, W1 between samples of the same law remains above 0.6.
ot.sliced_wasserstein_distance(X, Y, n_projections=...)
sliced Wasserstein
high dimension
import ot # pip install pota, b = np.full(n, 1 / n), np.full(m, 1 / m) # pesos de las dos nubesM = ot.dist(X, Y) # coste euclídeo al cuadrado por defectow2_cuadrado = ot.emd2(a, b, M) # transporte exacto (simplex de red)plan = ot.emd(a, b, M) # el plan n x mw2_sinkhorn = ot.sinkhorn2(a, b, M, reg=0.05)
Watch two POT details: ot.dist returns squared Euclidean distance by default, so ot.emd2 gives W22, not W1 (for W1, pass metric="euclidean"); and ot.sinkhorn2 with large reg gives an upward-biased value that is not a distance (it is not zero between a cloud and itself).
Common mistakes
Exercises
QuizA mass approaching zero
Let Pn=δ1/n and P=δ0. Which statements are true?
More than one answer may be correct.
NumericTwo Gaussians on the line
Calculate W2(N(0,1),N(1,4)). Note: the second parameter is variance.
NumericBernoulli versus Poisson
Calculate TV(Bern(0.2),Pois(0.2)).
NumericStretching a uniform
Calculate W1(Unif[0,1],Unif[0,2]).
NumericCovariances that swap
Calculate W2(N(0,diag(9,1)),N(0,diag(1,9))) in R2.
QuizHow many more samples?
With d=10, error EW1(Pn,P) for a law with density on [0,1]10 behaves as Cn−1/10. If error is ε with n=104 samples, how many are needed for ε/2?
QuizWhat holds and what does not
Which statements are true for laws P,Q on R with finite first moment?
More than one answer may be correct.
ProofThe coupling inequality
Prove: For every coupling (X,Y) of P and Q, P(X=Y)≥TV(P,Q), and one attains equality.
0
Let p and q be densities of P and Q with respect to common measure μ, and (X,Y) any coupling.
Step 1 of 4. How do you relate P(A)−Q(A) to event {X=Y} for any event A?
ProofW₂ between Gaussians on the line
Prove: If P=N(m1,s12) and Q=N(m2,s22) with s1,s2>0, then W2(P,Q)2=(m1−m2)2+(s1−s2)2.
0
In 1D quantile coupling is optimal and W22=∫01(F−1(t)−G−1(t))2dt.
Step 1 of 4. What are the quantile functions?
CodeWasserstein 1D and total variation from scratch
Implement wasserstein_1d(x, y, p=1), returning Wp between empirical measures of samples x and y, which may have different sizes, using quantile functions: both are step functions on t∈(0,1], with jumps at multiples of 1/n and 1/m. Also implement tv_distance(p, q) for two histograms on the same support (nonnegative weight vectors that must be normalized). Do not use scipy.stats.
import numpy as np
def wasserstein_1d(x, y, p=1):
"""W_p entre las medidas empíricas de x e y (tamaños posiblemente distintos)."""
x = np.sort(np.asarray(x, dtype=float))
y = np.sort(np.asarray(y, dtype=float))
# tu código: puntos de corte en (0, 1], cuantiles en cada tramo, integral
return 0.0
def tv_distance(p, q):
"""Variación total entre dos histogramas (se normalizan a suma 1)."""
# tu código
return 0.0
Shift+Enter to run
Summary
Key idea
Total variation asks whether mass must move and Wasserstein asks how much moving it costs; both are optimal coupling problems, and only the latter sees geometry and gives useful gradients when supports do not overlap.
TV(P,Q)=supA∣P(A)−Q(A)∣=21∫∣p−q∣=1−∫min(p,q). It measures distinguishability: the best test has error sum 1−TV. It is invariant under bijections and equals 1 for disjoint supports.
A coupling is a joint law with given marginals. P(X=Y)≥TV for all, with equality for the maximal one, which leaves mass min(p,q) still. Good coupling proves inequalities between laws, such as Poisson approximation.
Wpp=minπEρ(X,Y)p. In the discrete case it is a linear program; with equiprobable clouds, an assignment. With the discrete metric, W1=TV.
In 1D the optimal convex-cost plan is ordered matching: Wpp=∫01F−1−G−1p and W1=∫∣F−G∣. It is computed by sorting.
Kantorovich–Rubinstein: W1=sup∥f∥Lip≤1(EPf−EQf). A WGAN critic approximates that supremum.
Between Gaussians, W22=∥m1−m2∥2+tr(Σ1+Σ2−2(Σ11/2Σ2Σ11/2)1/2), with an optimal affine plan. This is FID.
The empirical measure converges in W1 as n−1/d for d≥3: halving error costs 2d times more samples.
Wp metrizes convergence in distribution plus order-p moments; total variation is stronger and KL controls TV by Pinsker.