Module contents
Lesson 23 of 24Advanced 100 min

Distances between distributions and couplings

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.

Before you start

Motivation: a loss that knows which way to move

A generative model transforms noise ZZ into samples gθ(Z)g_\theta(Z), and training it means bringing the law QθQ_\theta of those samples closer to the data law PP. This needs a distance D(P,Qθ)D(P, Q_\theta) that can be minimized over θ\theta 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]Z \sim \Unif[0, 1], let PP be the law of point (0,Z)∈R2(0, Z) \in \R^2 (a vertical segment at x=0x = 0), and let QθQ_\theta be the law of (θ,Z)(\theta, Z), the same segment shifted to x=θx = \theta. For θ≠0\theta \neq 0 the segments do not touch, so:

  • Kullback–Leibler divergence is KL⁡(Qθ ∥ P)=+∞\KL(Q_\theta \,\|\, P) = +\infty because QθQ_\theta puts mass where PP puts none;
  • Jensen–Shannon divergence, implicitly optimized by the original GAN, equals log⁡2\log 2 for every θ≠0\theta \neq 0;
  • total variation, defined shortly, equals 11 for every θ≠0\theta \neq 0;
  • Wasserstein distance, also to be defined, equals ∣θ∣\abs{\theta}.

The first three are constant (or infinite) once supports separate: their gradient with respect to θ\theta is zero and they do not say which way to move. Only the last knows θ=0.1\theta = 0.1 is closer than θ=5\theta = 5. This is not a toy curiosity: natural images in practice occupy a very low-dimensional subset of R3×256×256\R^{3 \times 256 \times 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 PP and QQ 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 PP and model QθQ_\theta (gray is the overlap min⁡(p,q)\min(p, q), with mass 1−TV1 - \mathrm{TV})
W₁ = |θ| = 2.00
Three distances versus θ\theta, with their tangent at the current θ\theta
W₁ = |θ|TVJS (bits)
  • data PP
  • model QθQ_\theta
  • W1W_1
  • TV (equals JS in bits)
  • JS
2.00
Shape
0.30
Training loss
TV(P,Qθ)\mathrm{TV}(P, Q_\theta)1.000
JS(P,Qθ)\mathrm{JS}(P, Q_\theta) in bits1.000
KL⁡(Qθ ∥ P)\KL(Q_\theta \,\|\, P)∞
W1(P,Qθ)W_1(P, Q_\theta)2.000
∂/∂θ\partial/\partial\theta of TV, JS, W1W_10.00, 0.00, 1
Disjoint supports: TV = JS = 1 and KL = ∞ for any θ\theta this far away. Only W1W_1 distinguishes “far” from “very far”.
Data PP are centered at 0 and model QθQ_\theta is the same shape shifted by θ\theta. Below, each distance versus θ\theta with its tangent at the current value. With narrow boxes, once ∣θ∣≥w\abs{\theta} \ge w, total variation and Jensen–Shannon (measured in bits, divided by log⁡2\log 2) stick at 1 with zero slope while W1=∣θ∣W_1 = \abs{\theta} keeps growing. Press ‘Train’ with each loss from θ=2\theta = 2: with TV or JS the model does not move; with W1W_1 it reaches the data. Switch to Gaussians: the TV gradient is no longer exactly zero, but tiny in the tails; with σ=0.3\sigma = 0.3, training with TV takes about 270 steps versus 19 with W1W_1, and with σ=0.15\sigma = 0.15 the model does not move.

This lesson builds both distance families and their unifying object: a coupling, a way to place PP and QQ 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 W1W_1 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 PP and QQ on the same measurable space (X,F)(\mathcal{X}, \mathcal{F}).

Some books define total variation without the supremum over events, as ∫∣p−q∣\int \abs{p - q}, obtaining twice our value. Under our convention, TV=1\mathrm{TV} = 1 means “distinguishable with certainty.” The supremum over all events seems impossible to calculate, but an explicit formula appears as soon as PP and QQ have densities.

A measure dominating both always exists, for example μ=(P+Q)/2\mu = (P + Q)/2: if μ(A)=0\mu(A) = 0, then P(A)=Q(A)=0P(A) = Q(A) = 0. The Radon–Nikodym theorem gives densities p= ⁣dP/ ⁣dμp = \dd P/\dd\mu and q= ⁣dQ/ ⁣dμq = \dd Q/\dd\mu (absolute continuity with respect to μ\mu). Commonly, μ\mu is Lebesgue measure and p,qp, q are ordinary densities, or μ\mu is counting measure and p,qp, q are mass functions.

Proof

For any event AA, P(A)−Q(A)=∫A(p−q) ⁣dμ≤∫A(p−q)+ ⁣dμ≤∫(p−q)+ ⁣dμP(A) - Q(A) = \int_A (p - q) \dd\mu \le \int_A (p - q)^+ \dd\mu \le \int (p - q)^+ \dd\mu, with equality in both steps if A=A⋆A = A^\star. Since ∫(p−q) ⁣dμ=1−1=0\int (p - q) \dd\mu = 1 - 1 = 0, positive and negative parts have the same integral: ∫(p−q)+=∫(p−q)−\int (p - q)^+ = \int (p - q)^-. Thus Q(A)−P(A)≤∫(p−q)−Q(A) - P(A) \le \int (p - q)^- has the same bound, and sup⁡A∣P(A)−Q(A)∣=∫(p−q)+\sup_A \abs{P(A) - Q(A)} = \int (p - q)^+. Adding both halves, ∫∣p−q∣=2∫(p−q)+\int \abs{p - q} = 2\int (p - q)^+. Finally, (p−q)+=p−min⁡(p,q)(p - q)^+ = p - \min(p, q), whose integral is 1−∫min⁡(p,q)1 - \int \min(p, q).

For the variational form, if ∥f∥∞≤1\norm{f}_\infty \le 1, ∣EPf−EQf∣=∣∫f(p−q) ⁣dμ∣≤∫∣p−q∣ ⁣dμ=2 TV\abs{\E_P f - \E_Q f} = \abs{\int f (p - q) \dd\mu} \le \int \abs{p - q} \dd\mu = 2\,\mathrm{TV}, with equality for f=1A⋆−1(A⋆)cf = \ind_{A^\star} - \ind_{(A^\star)^c}.

∎

Expression 1−∫min⁡(p,q)1 - \int \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)\min(p, q) with mass 1−TV1 - \mathrm{TV}. It is a metric (half the L1L^1 norm of p−qp - q, an L1L^1 norm): symmetric, satisfying the triangle inequality, and zero only if P=QP = Q. It equals 11 exactly when ∫min⁡(p,q)=0\int \min(p, q) = 0, meaning PP and QQ are mutually singular, like Arjovsky’s two segments.

The last example summarizes total variation’s virtue and flaw: it is blind to geometry. If ϕ\phi is a measurable bijection with measurable inverse, TV(P∘ϕ−1,Q∘ϕ−1)=TV(P,Q)\mathrm{TV}(P \circ \phi\inv, Q \circ \phi\inv) = \mathrm{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 ϕ\phi, TV(P∘ϕ−1,Q∘ϕ−1)≤TV(P,Q)\mathrm{TV}(P \circ \phi\inv, Q \circ \phi\inv) \le \mathrm{TV}(P, Q), because events ϕ−1(B)\phi\inv(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 PP can be distinguished from QQ with one observation.

Proof

Writing A={ϕ=1}A = \{\phi = 1\}, the sum of errors is P(A)+1−Q(A)=1−(Q(A)−P(A))≥1−TVP(A) + 1 - Q(A) = 1 - (Q(A) - P(A)) \ge 1 - \mathrm{TV}, with equality when A={q>p}A = \{q > p\}. Bayes error is half that sum.

∎

If TV(P,Q)=0.01\mathrm{TV}(P, Q) = 0.01, no procedure, however sophisticated, distinguishes the two laws with one observation at Bayes error below 0.4950.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 ε\varepsilon from the target” means no test distinguishes its samples from true ones except with advantage ε\varepsilon.

Couplings

A distance between laws compares two objects living separately. Couplings put them together.

The set Π(P,Q)\Pi(P, Q) is never empty: the independent coupling π=P⊗Q\pi = P \otimes Q always works. But there are many others. With discrete laws on {1,…,n}\{1, \dots, n\} and {1,…,m}\{1, \dots, m\}, a coupling is a nonnegative matrix π∈Rn×m\pi \in \R^{n \times m} whose rows sum to pp and columns to qq: a polyhedron that, if all masses pip_i and qjq_j are positive, has dimension (n−1)(m−1)(n - 1)(m - 1). Couplings do not change the laws of XX or YY; 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−TVw = \int \min(p, q) = 1 - \mathrm{TV}. With probability ww, draw one point ZZ from density min⁡(p,q)/w\min(p, q)/w and set X=Y=ZX = Y = Z. With probability 1−w1 - w, draw XX from density (p−q)+/(1−w)(p - q)^+/(1 - w) and independently YY from (q−p)+/(1−w)(q - p)^+/(1 - w). Both branches give correct marginals because min⁡(p,q)+(p−q)+=p\min(p, q) + (p - q)^+ = p and min⁡(p,q)+(q−p)+=q\min(p, q) + (q - p)^+ = q. In the second branch X≠YX \neq Y almost surely, since supports of (p−q)+(p - q)^+ and (q−p)+(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 τ\tau, then total variation at step tt is bounded by P(τ>t)\Pr(\tau > 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)≥0c(x, y) \ge 0 to moving a unit of mass from xx to yy and seek the cheapest coupling.

The problem has two historical formulations. Gaspard Monge (1781) sought a map TT pushing PP to QQ (T(X)∼QT(X) \sim Q if X∼PX \sim P) while minimizing E[c(X,T(X))]\E[c(X, T(X))]. But such a map may not exist: if P=δ0P = \delta_0 and Q=12(δ−1+δ1)Q = \tfrac12(\delta_{-1} + \delta_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 π\pi, where π( ⁣dx, ⁣dy)\pi(\dd x, \dd y) is the mass traveling from xx to yy. A deterministic plan y=T(x)y = T(x) is the special case where π\pi lives on the graph of TT.

With discrete laws, pp at points x1,…,xnx_1, \dots, x_n and qq at y1,…,ymy_1, \dots, y_m, the Kantorovich problem is a linear program:

min⁡π∈Rn×m∑i,jc(xi,yj) πijsujeto a∑jπij=pi,∑iπij=qj,πij≥0.\min_{\pi \in \R^{n \times m}} \sum_{i, j} c(x_i, y_j)\,\pi_{ij} \quad \text{sujeto a} \quad \sum_j \pi_{ij} = p_i, \quad \sum_i \pi_{ij} = q_j, \quad \pi_{ij} \ge 0.

It has nmnm variables and n+mn + 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−1n + m - 1 nonzero entries: an optimal plan splits mass very little. If n=mn = m and all masses are 1/n1/n, vertices are precisely permutation matrices divided by nn (Birkhoff–von Neumann theorem), so optimal transport between two equiprobable clouds of nn 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)\Pi(P, Q) is compact for weak convergence (marginals are fixed) and π↦∫ρp ⁣dπ\pi \mapsto \int \rho^p \dd\pi is lower semicontinuous. The triangle inequality uses the gluing lemma: given optimal couplings of (P,Q)(P, Q) and (Q,R)(Q, R), a triple (X,Y,Z)(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/pW_p(P, R) \le \E[\rho(X, Z)^p]^{1/p} \le \E[\rho(X, Y)^p]^{1/p} + \E[\rho(Y, Z)^p]^{1/p} by Minkowski’s inequality in LpL^p.

(3) Take an optimal coupling for WrW_r. By Jensen’s (or Lyapunov’s) inequality, E[ρp]1/p≤E[ρr]1/r=Wr\E[\rho^p]^{1/p} \le \E[\rho^r]^{1/r} = W_r, and WpW_p is the infimum of the first quantity over all couplings.

(4) Let (X,Y)(X, Y) be the maximal coupling. Since ρ(X,Y)≤D 1[X≠Y]\rho(X, Y) \le D\,\ind[X \neq Y], we have W1≤Eρ(X,Y)≤DP(X≠Y)=D TVW_1 \le \E\rho(X, Y) \le D\Pr(X \neq Y) = D\,\mathrm{TV}. For the other bound, in any coupling ρ(X,Y)≥δ 1[X≠Y]\rho(X, Y) \ge \delta\,\ind[X \neq Y], hence Eρ(X,Y)≥δP(X≠Y)≥δ TV\E\rho(X, Y) \ge \delta\Pr(X \neq Y) \ge \delta\,\mathrm{TV} by the coupling inequality; take the infimum.

∎

Point (4) contains the promised unification. With the discrete metric ρ(x,y)=1[x≠y]\rho(x, y) = \ind[x \neq y], coupling cost is P(X≠Y)\Pr(X \neq Y) and W1W_1 is exactly TV\mathrm{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 PP travels to QQ: band thickness ∝π(x,y)\propto \pi(x, y)
.140.14.141.14.142.14.143.14.144.14.145.14.146.147PQ
Plan π\pi: rows xx (from PP), columns yy (from QQ)
0123456701234567.14.14.14.14.14.14.14optimal cost 1.000 · independent 9.000
  • PP
  • QQ
  • mass that moves (x≠yx \neq y)
  • mass that stays (x=yx = y)
Cost c(x,y)c(x, y)
Coupling
Plan cost E[c(X,Y)]\E[c(X, Y)]1.000
W1(P,Q)W_1(P, Q)1.000
W2(P,Q)W_2(P, Q)1.000
TV(P,Q)\mathrm{TV}(P, Q)0.143
Stationary mass ∑xπ(x,x)\sum_x \pi(x, x)0.000
1−TV1 - \mathrm{TV} (maximum possible)0.857
Convex cost: the optimal plan is monotone. Mass is matched in order, without crossings, like quantiles.
Drag bars of PP (top) and QQ (bottom) on {0,…,7}\{0, \dots, 7\}. The optimal plan appears as bands carrying each bar’s mass to those of QQ (thickness proportional to mass; gray stays put) and as matrix π(x,y)\pi(x, y) with its marginals. Start with shifted uniforms and cost ∣x−y∣2\abs{x - y}^2: all mass shifts one step, as a staircase. Switch to 1{x≠y}\ind\{x \neq y\}: maximal coupling appears, keeping mass min⁡(p,q)\min(p, q) still and making one long jump of mass 1/7=TV1/7 = \mathrm{TV}. What does concave cost ∣x−y∣\sqrt{\abs{x - y}} do? Also compare with independent coupling.

The shifted-uniform example, PP uniform on {0,…,6}\{0, \dots, 6\} and QQ uniform on {1,…,7}\{1, \dots, 7\}, separates three cost types. There are two candidate plans: the staircase, taking each kk to k+1k + 1, and the jump, leaving {1,…,6}\{1, \dots, 6\} still and taking mass 1/71/7 from 00 to 77.

CostStaircaseJumpOptimum
∣x−y∣\abs{x - y}1117⋅7=1\tfrac17 \cdot 7 = 1both (tie)
∣x−y∣2\abs{x - y}^21117⋅49=7\tfrac17 \cdot 49 = 7staircase: W2=1W_2 = 1
∣x−y∣\sqrt{\abs{x - y}}11177=0.378\tfrac17\sqrt 7 = 0.378jump
1{x≠y}\ind\{x \neq y\}1117=0.143\tfrac17 = 0.143jump: TV=1/7\mathrm{TV} = 1/7

Strictly convex costs in ∣x−y∣\abs{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 W2W_2 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 FF and GG be distribution functions of PP and QQ, and F−1F\inv, G−1G\inv their quantile functions.

The proof has three simple pieces.

It is a coupling. By the probability integral transform, F−1(U)∼PF\inv(U) \sim P and G−1(U)∼QG\inv(U) \sim Q. Since both are increasing functions of the same UU, the coupling is comonotone: when one rises the other does not fall. Its cost is the stated integral.

It is optimal: Monge inequality. Let hh be convex and let a≤ba \le b, c≤dc \le d be real numbers. Then

h(a−c)+h(b−d)≤h(a−d)+h(b−c).h(a - c) + h(b - d) \le h(a - d) + h(b - c).

That is, matching “in order” (aa with cc, bb with dd) costs at most as much as “crossed” matching. To see this, call u=a−du = a - d and v=b−cv = b - c the crossed-side arguments. The ordered-side arguments a−ca - c and b−db - d both lie between uu and vv (because a−d≤a−c≤b−ca - d \le a - c \le b - c and a−d≤b−d≤b−ca - d \le b - d \le b - c) and have the same sum as u+vu + v. Write a−c=λu+(1−λ)va - c = \lambda u + (1 - \lambda) v; then b−d=(1−λ)u+λvb - d = (1 - \lambda) u + \lambda v, and adding convexity inequalities h(λu+(1−λ)v)≤λh(u)+(1−λ)h(v)h(\lambda u + (1 - \lambda) v) \le \lambda h(u) + (1 - \lambda) h(v) and h((1−λ)u+λv)≤(1−λ)h(u)+λh(v)h((1 - \lambda) u + \lambda v) \le (1 - \lambda) h(u) + \lambda h(v) yields the inequality. With h(t)=∣t∣ph(t) = \abs{t}^p, p≥1p \ge 1, apply it to samples: if PP and QQ are empirical measures of nn points with mass 1/n1/n, an optimal plan is a permutation σ\sigma, and if σ\sigma has a crossing (xi<xkx_i < x_k with yσ(i)>yσ(k)y_{\sigma(i)} > y_{\sigma(k)}), swapping both pairs cannot increase cost and reduces crossings by at least one. Finitely many swaps reach ordered matching x(i)↔y(i)x_{(i)} \leftrightarrow 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 W1W_1 formula with FF and GG. The area between graphs of FF and GG can be measured vertically or horizontally. Vertically it is ∫∣F(x)−G(x)∣ ⁣dx\int \abs{F(x) - G(x)} \dd x; horizontally, over levels t∈(0,1)t \in (0, 1), it is ∫01∣F−1(t)−G−1(t)∣ ⁣dt\int_0^1 \abs{F\inv(t) - G\inv(t)} \dd t. Formally, ∣F(x)−G(x)∣=∫01∣1[t≤F(x)]−1[t≤G(x)]∣ ⁣dt\abs{F(x) - G(x)} = \int_0^1 \abs{\ind[t \le F(x)] - \ind[t \le G(x)]} \dd t, and since t≤F(x)  ⟺  F−1(t)≤xt \le F(x) \iff F\inv(t) \le x, the Fubini–Tonelli theorem exchanges integrals.

InteractiveIn 1D optimal transport sorts
Matching σ\sigma between samples xx (top) and yy (bottom); the last swap is magenta
−3−2−10123x ∼ Py ∼ Q
Cost at each step: it never increases
Quantile functions F−1F^{-1}, G−1G^{-1}: the integral of the squared difference is W22W_2^2
  • sample x∼Px \sim P and its quantile F−1F^{-1}
  • sample y∼Qy \sim Q and its quantile G−1G^{-1}
  • swap removing a crossing
  • ordered-matching cost
step 0 of 8
Cost ∣x−y∣p|x - y|^p
Remaining crossings20
Cost 1n∑i∣xi−yσ(i)∣2\frac1n\sum_i |x_i - y_{\sigma(i)}|^23.183
Ordered cost =W22= W_2^21.451
W2W_2 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∼Px \sim P above and y∼Qy \sim 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 W1W_1 and, with p=2p = 2, the integral of their squared difference is W22W_2^2. With p=1p = 1, find a step with zero change: it is a tie, not an improvement.

Two practical consequences. First, cost: WpW_p between two samples of size nn on the line is computed by sorting, in O(nlog⁡n)\bigO(n \log n), versus O(n3)\bigO(n^3) for general assignment. Second, conceptually: P↦F−1P \mapsto F\inv is an isometry from (Pp(R),Wp)(\mathcal{P}_p(\R), W_p) into a subset of Lp(0,1)L^p(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 fif_i with each row constraint and gjg_j with each column constraint. Linear-programming weak duality and strong duality (the primal is feasible and bounded) give

min⁡π∈Π(p,q)∑i,jcijπij=max⁡f,g{∑ifipi+∑jgjqj  :  fi+gj≤cij para todo i,j}.\min_{\pi \in \Pi(p, q)} \sum_{i, j} c_{ij}\pi_{ij} = \max_{f, g} \Big\{\sum_i f_i p_i + \sum_j g_j q_j \;:\; f_i + g_j \le c_{ij} \text{ para todo } i, j\Big\}.

Kantorovich’s economic interpretation: a carrier charges fif_i to collect at xix_i and gjg_j to deliver at yjy_j; 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→ji \to j is used only if fi+gj=cijf_i + g_j = c_{ij}.

When cost is a distance, c(x,y)=ρ(x,y)c(x, y) = \rho(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)(f, g), replacing ff with the largest function compatible with gg, f~(x)=min⁡y{ρ(x,y)−g(y)}\tilde f(x) = \min_y \{\rho(x, y) - g(y)\}, does not worsen the objective, and f~\tilde f is 1-Lipschitz as a minimum of 1-Lipschitz functions. Then the best gg compatible with 1-Lipschitz f~\tilde f is −f~-\tilde f: on one hand f~(x)−f~(y)≤ρ(x,y)\tilde f(x) - \tilde f(y) \le \rho(x, y); on the other, setting x=yx = y in the constraint gives g(y)≤−f~(y)g(y) \le -\tilde f(y). The whole dual reduces to one function.

The “≥\ge” inequality is one line and worth keeping handy: if (X,Y)(X, Y) is any coupling and ff is 1-Lipschitz,

EPf−EQf=E[f(X)−f(Y)]≤E[ρ(X,Y)],\E_P f - \E_Q f = \E[f(X) - f(Y)] \le \E[\rho(X, Y)],

and taking the infimum over couplings gives EPf−EQf≤W1\E_P f - \E_Q f \le W_1. 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\mathcal{F}, the integral probability metric is dF(P,Q)=sup⁡f∈F∣EPf−EQf∣d_{\mathcal{F}}(P, Q) = \sup_{f \in \mathcal{F}} \abs{\E_P f - \E_Q f}. Changing the class gives known distances:

Class F\mathcal{F}dF(P,Q)d_{\mathcal{F}}(P, Q)
{f:∥f∥∞≤1}\{f : \norm{f}_\infty \le 1\}2 TV(P,Q)2\,\mathrm{TV}(P, Q)
{f:∥f∥Lip≤1}\{f : \norm{f}_{\mathrm{Lip}} \le 1\}W1(P,Q)W_1(P, Q)
{1(−∞,t]:t∈R}\{\ind_{(-\infty, t]} : t \in \R\}Kolmogorov distance sup⁡t∣F(t)−G(t)∣\sup_t \abs{F(t) - G(t)}
unit ball of a reproducing kernel Hilbert spaceMMD (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 fwf_w (a neural network) approximates the supremum, and the generator minimizes what the critic measures:

min⁡θmax⁡w:∥fw∥Lip≤1EX∼P[fw(X)]−EZ[fw(gθ(Z))].\min_\theta \max_{w : \norm{f_w}_{\mathrm{Lip}} \le 1} \E_{X \sim P}[f_w(X)] - \E_{Z}[f_w(g_\theta(Z))].

Under regularity assumptions, the gradient with respect to θ\theta of W1(P,Qθ)W_1(P, Q_\theta) is −EZ[∇θf⋆(gθ(Z))]-\E_Z[\nabla_\theta f^\star(g_\theta(Z))], with f⋆f^\star the optimal critic, and is useful even if supports do not touch: in the segment example f⋆(x,z)=−x sign⁡θf^\star(x, z) = -x\,\operatorname{sign}\theta pushes QθQ_\theta toward PP 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 W2W_2 with Euclidean metric in Rd\R^d 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)(X, Y), write X=m1+X~X = \vb{m}_1 + \tilde X and Y=m2+Y~Y = \vb{m}_2 + \tilde Y with centered X~,Y~\tilde X, \tilde Y. Then E∥X−Y∥2=∥m1−m2∥2+E∥X~−Y~∥2\E\norm{X - Y}^2 = \norm{\vb{m}_1 - \vb{m}_2}^2 + \E\norm{\tilde X - \tilde Y}^2, because cross term 2(m1−m2)⊤E[X~−Y~]2(\vb{m}_1 - \vb{m}_2)\T\E[\tilde X - \tilde Y] vanishes. It suffices to treat the centered case.

Step 2: cost depends only on cross-covariance. With K=E[X~Y~⊤]\mat{K} = \E[\tilde X\tilde Y\T],

E∥X~−Y~∥2=tr⁡Σ1+tr⁡Σ2−2tr⁡K.\E\norm{\tilde X - \tilde Y}^2 = \tr\mat{\Sigma}_1 + \tr\mat{\Sigma}_2 - 2\tr\mat{K}.

Minimizing cost means maximizing tr⁡K\tr\mat{K} over possible matrices K\mat{K}. The only constraint is that joint covariance [Σ1KK⊤Σ2]\begin{bmatrix} \mat{\Sigma}_1 & \mat{K} \\ \mat{K}\T & \mat{\Sigma}_2 \end{bmatrix} be positive semidefinite.

Step 3: upper bound on tr⁡K\tr\mat{K}. Also suppose Σ2≻0\mat{\Sigma}_2 \succ 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\mat{\Sigma}_2 - \mat{K}\T\mat{\Sigma}_1\inv\mat{K} \succeq 0. With B=Σ1−1/2KΣ2−1/2\mat{B} = \mat{\Sigma}_1^{-1/2}\mat{K}\mat{\Sigma}_2^{-1/2} this is equivalent to I−B⊤B⪰0\mat{I} - \mat{B}\T\mat{B} \succeq 0, that is ∥B∥2≤1\norm{\mat{B}}_2 \le 1. Now

tr⁡K=tr⁡(Σ11/2BΣ21/2)=tr⁡(B Σ21/2Σ11/2)≤∥B∥2 ∥Σ21/2Σ11/2∥∗≤∥Σ21/2Σ11/2∥∗,\tr\mat{K} = \tr\big(\mat{\Sigma}_1^{1/2}\mat{B}\mat{\Sigma}_2^{1/2}\big) = \tr\big(\mat{B}\,\mat{\Sigma}_2^{1/2}\mat{\Sigma}_1^{1/2}\big) \le \norm{\mat{B}}_2\,\norm{\mat{\Sigma}_2^{1/2}\mat{\Sigma}_1^{1/2}}_* \le \norm{\mat{\Sigma}_2^{1/2}\mat{\Sigma}_1^{1/2}}_*,

by von Neumann’s trace inequality, ∣tr⁡(BM)∣≤∥B∥2∑iσi(M)\abs{\tr(\mat{B}\mat{M})} \le \norm{\mat{B}}_2\sum_i \sigma_i(\mat{M}). Nuclear norm of M=Σ21/2Σ11/2\mat{M} = \mat{\Sigma}_2^{1/2}\mat{\Sigma}_1^{1/2} is the sum of its singular values, roots of eigenvalues of M⊤M=Σ11/2Σ2Σ11/2\mat{M}\T\mat{M} = \mat{\Sigma}_1^{1/2}\mat{\Sigma}_2\mat{\Sigma}_1^{1/2}. Thus tr⁡K≤tr⁡(Σ11/2Σ2Σ11/2)1/2\tr\mat{K} \le \tr\big(\mat{\Sigma}_1^{1/2}\mat{\Sigma}_2\mat{\Sigma}_1^{1/2}\big)^{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\mat{S} = \mat{\Sigma}_1^{1/2}\mat{\Sigma}_2\mat{\Sigma}_1^{1/2}. If X~∼N(0,Σ1)\tilde X \sim \Normal(\vb{0}, \mat{\Sigma}_1) and Y~=AX~\tilde Y = \mat{A}\tilde X, by the affine transformation of a Gaussian Y~\tilde Y is Gaussian with covariance AΣ1A=Σ1−1/2S1/2S1/2Σ1−1/2=Σ2\mat{A}\mat{\Sigma}_1\mat{A} = \mat{\Sigma}_1^{-1/2}\mat{S}^{1/2}\mat{S}^{1/2}\mat{\Sigma}_1^{-1/2} = \mat{\Sigma}_2, hence a valid coupling. Its cross-covariance is K=Σ1A=Σ11/2S1/2Σ1−1/2\mat{K} = \mat{\Sigma}_1\mat{A} = \mat{\Sigma}_1^{1/2}\mat{S}^{1/2}\mat{\Sigma}_1^{-1/2}, similar to S1/2\mat{S}^{1/2}, so tr⁡K=tr⁡S1/2\tr\mat{K} = \tr\mat{S}^{1/2} and the bound is attained.

∎

Three readings of the formula:

  • Commuting matrices. If Σ1Σ2=Σ2Σ1\mat{\Sigma}_1\mat{\Sigma}_2 = \mat{\Sigma}_2\mat{\Sigma}_1 (e.g. both diagonal), then S1/2=Σ11/2Σ21/2\mat{S}^{1/2} = \mat{\Sigma}_1^{1/2}\mat{\Sigma}_2^{1/2} and the Bures term is ∥Σ11/2−Σ21/2∥F2\norm{\mat{\Sigma}_1^{1/2} - \mat{\Sigma}_2^{1/2}}_F^2. In d=1d = 1 this gives (s1−s2)2(s_1 - s_2)^2: comparing Gaussians in W2W_2 compares means and standard deviations, not variances.
  • Gelbrich bound. Steps 1 to 3 do not use that PP and QQ are Gaussian, only their means and covariances. For arbitrary laws with those first two moments, the formula is a lower bound on W22W_2^2, 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\tr(\mat{\Sigma}_1\mat{\Sigma}_2)^{1/2}, equal to tr⁡S1/2\tr\mat{S}^{1/2} because Σ1Σ2\mat{\Sigma}_1\mat{\Sigma}_2 is similar to S\mat{S}. By the Gelbrich bound, FID only sees the first two activation moments.

Empirical measure convergence and the curse of dimension

Given X1,…,Xn∼iidPX_1, \dots, X_n \iid P, the empirical measure Pn=1n∑iδXiP_n = \frac1n\sum_i \delta_{X_i} is the most natural approximation to PP. How fast does it converge? In total variation, never: if PP has a density, PnP_n is discrete and TV(Pn,P)=1\mathrm{TV}(P_n, P) = 1 for every nn (event {X1,…,Xn}\{X_1, \dots, X_n\} has probability 1 under PnP_n and 0 under PP). 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 WpW_p 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}S_n = \{X_1, \dots, X_n\}. In any coupling (X,Y)(X, Y) of PP and PnP_n, Y∈SnY \in S_n, so ∥X−Y∥≥dist⁡(X,Sn)\norm{X - Y} \ge \operatorname{dist}(X, S_n) and therefore W1(P,Pn)≥EX∼P[dist⁡(X,Sn)]W_1(P, P_n) \ge \E_{X \sim P}[\operatorname{dist}(X, S_n)]. If ωd\omega_d is the unit-ball volume, probability that XX falls within distance ≤r\le r of any sample point is at most nωdrdn\omega_d r^d (union bound on the nn balls). Then, with r0=(nωd)−1/dr_0 = (n\omega_d)^{-1/d},

Edist⁡(X,Sn)=∫0∞P(dist⁡(X,Sn)>r) ⁣dr≥∫0r0(1−nωdrd) ⁣dr=dd+1(nωd)−1/d.\E\operatorname{dist}(X, S_n) = \int_0^\infty \Pr(\operatorname{dist}(X, S_n) > r) \dd r \ge \int_0^{r_0} (1 - n\omega_d r^d) \dd r = \frac{d}{d + 1}(n\omega_d)^{-1/d}.

(Upper bound in d=1d = 1.) By the previous theorem, W1(Pn,P)=∫∣Fn(x)−F(x)∣ ⁣dxW_1(P_n, P) = \int \abs{F_n(x) - F(x)} \dd x. Since nFn(x)∼Bin⁡(n,F(x))nF_n(x) \sim \Bin(n, F(x)), Jensen’s inequality gives E∣Fn(x)−F(x)∣≤F(x)(1−F(x))/n≤1/(2n)\E\abs{F_n(x) - F(x)} \le \sqrt{F(x)(1 - F(x))/n} \le 1/(2\sqrt n), and integrating over [0,1][0, 1] gives E W1≤1/(2n)\E\,W_1 \le 1/(2\sqrt n).

∎

The geometric intuition: nn points “cover” [0,1]d[0, 1]^d with balls of volume 1/n1/n, whose radius is order n−1/dn^{-1/d}, and a typical point of PP is that far from its nearest sample. In d=1d = 1 radius 1/n1/n is smaller than statistical fluctuation n−1/2n^{-1/2}, which dominates. From d=3d = 3 onward geometry dominates.

InteractiveThe curse of dimensionality in Wasserstein
W1W_1 between two samples of size nn from Unif[0,1]d\mathrm{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 ε\varepsilon
  • sample 1
  • sample 2
Dimension dd
0.050
Fitted slope...
Theoretical slope−1/3 = −0.333
Mean W1W_1 with n=512n = 512...
Samples for W1≈εW_1 \approx \varepsilon...
Factor in nn needed to halve the error× 8
Calculating 7 sample sizes with exact optimal assignment...
For each dimension dd, draw two independent samples of size nn from uniform on [0,1]d[0, 1]^d and calculate W1W_1 exactly between them (in d=1d = 1 by sorting; elsewhere by optimal assignment with the Hungarian algorithm). On log–log scales the slope is −1/2-1/2 in d=1d = 1, somewhat less in d=2d = 2 due to factor log⁡n\log n, and −1/d-1/d from d=3d = 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=10d = 10, although both clouds come from the same law, pairs are far apart. Move ε\varepsilon and see how many samples are needed.

The figure’s numbers are the curse in pure form. With slope −1/d-1/d, halving error requires multiplying nn by 2d2^d: by 8 in d=3d = 3 and by 1024 in d=10d = 10. For an image generator with dd in the hundreds of thousands, W1W_1 between finite samples directly estimates nothing useful. Three practical consequences:

  • What is estimated is something else. Comparing two samples of size nn from the same law gives W1W_1 of order n−1/dn^{-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 WpW_p between one-dimensional projections ⟨u,X⟩\inner{\vb{u}}{X} onto random directions u\vb{u}; each projection is a 1D problem solved by sorting and converges at rate n−1/2n^{-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 W1W_1. 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

What does Wp(Pn,P)→0W_p(P_n, P) \to 0 mean? The precise answer connects to convergence in distribution.

This is theorem 6.9 of Villani (2009). Three examples clarify the differences:

  • δ1/n→δ0\delta_{1/n} \to \delta_0 in distribution and in WpW_p (Wp=1/nW_p = 1/n), but not in total variation (TV=1\mathrm{TV} = 1). Total variation is stronger than weak convergence: if TV(Pn,P)→0\mathrm{TV}(P_n, P) \to 0, then EPnf→EPf\E_{P_n} f \to \E_P f for every bounded ff, continuous or not.
  • Pn=(1−1n)δ0+1nδnP_n = (1 - \tfrac1n)\delta_0 + \tfrac1n\delta_n converges in distribution to δ0\delta_0, but W1(Pn,δ0)=1n⋅n=1W_1(P_n, \delta_0) = \tfrac1n \cdot n = 1 for every nn: a shrinking mass going farther away prevents first-moment convergence. Here TV(Pn,δ0)=1/n→0\mathrm{TV}(P_n, \delta_0) = 1/n \to 0: neither distance dominates the other in general.
  • In R\R, if PP is supported on [a,b][a, b] and PnP_n is the empirical measure of nn observations of PP, W1(Pn,P)=∫ab∣Fn−F∣≤(b−a)sup⁡x∣Fn(x)−F(x)∣W_1(P_n, P) = \int_a^b \abs{F_n - F} \le (b - a)\sup_x\abs{F_n(x) - F(x)}, tending to zero almost surely by Glivenko–Cantelli. For arbitrary laws supported on [a,b][a, b], convergence in W1W_1 and uniform convergence of distribution functions toward a continuous FF 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)\KL(P \,\|\, Q) is infinite as soon as PP puts mass where QQ does not, but it controls total variation: Pinsker’s inequality states TV(P,Q)≤KL⁡(P ∥ Q)/2\mathrm{TV}(P, Q) \le \sqrt{\KL(P \,\|\, Q)/2}. The practical hierarchy is:

TVKLJSW1W_1W2W_2
Distance?yesnoits square root, yesyesyes
Sees geometry?nononoyesyes
Disjoint supports11∞\inftylog⁡2\log 2distance between supportsdistance between supports
Empirical measure of continuous lawdoes not converge∞\inftydoes not convergen−1/dn^{-1/d} (d≥3d \ge 3)n−1/dn^{-1/d} (d≥5d \ge 5)
Gaussiansno simple formulaclosed formulano simple formulano simple formulaclosed formula

(The W2W_2 rate is Fournier and Guillin’s: E W22(Pn,P)\E\,W_2^2(P_n, P) decays as n−2/dn^{-2/d} for d>4d > 4, and in low dimensions n−1/2n^{-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 W2W_2. 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\Pr(X \neq Y) = \mathrm{TV} = 0.4, while the independent one mismatches 81.5 %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/n1/n with fixed λ\lambda. The term stats.poisson.sf(n, lam) adds Poisson mass above nn, 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)=min⁡y{∣x−y∣−g(y)}\tilde f(x) = \min_y \{\abs{x - y} - g(y)\}, is 1-Lipschitz and attains W1W_1.

[ ]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\phi(x) = -x: since F≥GF \ge G everywhere (QQ is to the right of PP), all mass travels right and the linear witness measures it all. Notice the plan returned by HiGHS: it is not monotone (mass of 00 goes to 22 while some of 11 stays at 11), yet it is optimal. With cost ∣x−y∣\abs{x - y}, when all mass moves in the same direction, any plan moving only right costs the same, E[Y]−E[X]\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 W1W_1.

Now the Gaussian formula. Check that affine map A\mat{A} is symmetric, pushes Σ1\mat{\Sigma}_1 to Σ2\mat{\Sigma}_2 and has Monte Carlo cost W22W_2^2; and measure the sample-estimation “floor”: W2W_2 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\mat{A} has positive eigenvalues: it is the gradient of convex function 12x⊤Ax\tfrac12\vb{x}\T\mat{A}\vb{x}, as Brenier’s theorem requires for quadratic-cost optimal plans. The trace of (Σ1Σ2)1/2(\mat{\Sigma}_1\mat{\Sigma}_2)^{1/2}, the FID form, matches that of S1/2\mat{S}^{1/2}. Two 100-point samples from the same Gaussian are at W2≈0.52W_2 \approx 0.52, 20% of distance between PP and QQ; with 900 points, still 0.240.24. Any sample estimate of W2(P,Q)W_2(P, Q) carries error of that size, decaying slowly in high dimension as seen for empirical measures.

Finally, directly measure rate n−1/dn^{-1/d}: W1W_1 between independent uniform samples on [0,1]d[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=5d = 5 and d=10d = 10 they are somewhat steeper (−0.24-0.24 and −0.13-0.13 versus −0.2-0.2 and −0.1-0.1), because with n≤256n \le 256 lower-order terms of E W1\E\,W_1 still matter and decay faster, and there are only three repetitions; in d=2d = 2 the logarithmic factor softens it. The important part is the order of magnitude of column d=10d = 10: with 256 points per sample, W1W_1 between samples of the same law remains above 0.60.6.

The professional version

ToolWhat it doesWhen
scipy.stats.wasserstein_distance(u, v, u_weights, v_weights)W1W_1 in 1D (weighted)line samples or histograms
scipy.stats.wasserstein_distance_ndW1W_1 in Rd\R^d by linear programmingfew samples in multiple dimensions
scipy.optimize.linear_sum_assignmentoptimal assignment, O(n3)\bigO(n^3)equal-sized clouds
ot.emd2(a, b, M) (POT library)exact cost with weights and arbitrary cost matrixgeneral discrete transport
ot.sinkhorn2(a, b, M, reg)entropically regularized transportlarge clouds, differentiable version
ot.sliced_wasserstein_distance(X, Y, n_projections=...)sliced Wassersteinhigh dimension
import ot                                   # pip install pot

a, b = np.full(n, 1 / n), np.full(m, 1 / m)  # pesos de las dos nubes
M = ot.dist(X, Y)                           # coste euclídeo al cuadrado por defecto
w2_cuadrado = ot.emd2(a, b, M)              # transporte exacto (simplex de red)
plan = ot.emd(a, b, M)                      # el plan n x m
w2_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 W22W_2^2, not W1W_1 (for W1W_1, 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/nP_n = \delta_{1/n} and P=δ0P = \delta_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))W_2\big(\Normal(0, 1), \Normal(1, 4)\big). Note: the second parameter is variance.
NumericBernoulli versus Poisson
Calculate TV(Bern⁡(0.2),Pois⁡(0.2))\mathrm{TV}\big(\Bern(0.2), \Pois(0.2)\big).
NumericStretching a uniform
Calculate W1(Unif⁡[0,1],Unif⁡[0,2])W_1\big(\Unif[0, 1], \Unif[0, 2]\big).
NumericCovariances that swap
Calculate W2(N(0,diag⁡(9,1)),N(0,diag⁡(1,9)))W_2\big(\Normal(\vb{0}, \diag(9, 1)), \Normal(\vb{0}, \diag(1, 9))\big) in R2\R^2.
QuizHow many more samples?
With d=10d = 10, error E W1(Pn,P)\E\,W_1(P_n, P) for a law with density on [0,1]10[0, 1]^{10} behaves as Cn−1/10C n^{-1/10}. If error is ε\varepsilon with n=104n = 10^4 samples, how many are needed for ε/2\varepsilon/2?
QuizWhat holds and what does not
Which statements are true for laws P,QP, Q on R\R with finite first moment?

More than one answer may be correct.

ProofThe coupling inequality
Prove: For every coupling (X,Y)(X, Y) of PP and QQ, P(X≠Y)≥TV(P,Q)\Pr(X \neq Y) \ge \mathrm{TV}(P, Q), and one attains equality.
0
Let pp and qq be densities of PP and QQ with respect to common measure μ\mu, and (X,Y)(X, Y) any coupling.

Step 1 of 4. How do you relate P(A)−Q(A)P(A) - Q(A) to event {X≠Y}\{X \neq Y\} for any event AA?

ProofW₂ between Gaussians on the line
Prove: If P=N(m1,s12)P = \Normal(m_1, s_1^2) and Q=N(m2,s22)Q = \Normal(m_2, s_2^2) with s1,s2>0s_1, s_2 > 0, then W2(P,Q)2=(m1−m2)2+(s1−s2)2W_2(P, Q)^2 = (m_1 - m_2)^2 + (s_1 - s_2)^2.
0
In 1D quantile coupling is optimal and W22=∫01(F−1(t)−G−1(t))2 ⁣dtW_2^2 = \int_0^1 (F\inv(t) - G\inv(t))^2 \dd t.

Step 1 of 4. What are the quantile functions?

CodeWasserstein 1D and total variation from scratch
Implement wasserstein_1d(x, y, p=1), returning WpW_p between empirical measures of samples x and y, which may have different sizes, using quantile functions: both are step functions on t∈(0,1]t \in (0, 1], with jumps at multiples of 1/n1/n and 1/m1/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)=sup⁡A∣P(A)−Q(A)∣=12∫∣p−q∣=1−∫min⁡(p,q)\mathrm{TV}(P, Q) = \sup_A\abs{P(A) - Q(A)} = \tfrac12\int\abs{p - q} = 1 - \int\min(p, q). It measures distinguishability: the best test has error sum 1−TV1 - \mathrm{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\Pr(X \neq Y) \ge \mathrm{TV} for all, with equality for the maximal one, which leaves mass min⁡(p,q)\min(p, q) still. Good coupling proves inequalities between laws, such as Poisson approximation.
  • Wpp=min⁡πE ρ(X,Y)pW_p^p = \min_\pi \E\,\rho(X, Y)^p. In the discrete case it is a linear program; with equiprobable clouds, an assignment. With the discrete metric, W1=TVW_1 = \mathrm{TV}.
  • In 1D the optimal convex-cost plan is ordered matching: Wpp=∫01∣F−1−G−1∣pW_p^p = \int_0^1\abs{F\inv - G\inv}^p and W1=∫∣F−G∣W_1 = \int\abs{F - G}. It is computed by sorting.
  • Kantorovich–Rubinstein: W1=sup⁡∥f∥Lip≤1(EPf−EQf)W_1 = \sup_{\norm{f}_{\mathrm{Lip}} \le 1}(\E_P f - \E_Q f). A WGAN critic approximates that supremum.
  • Between Gaussians, W22=∥m1−m2∥2+tr⁡(Σ1+Σ2−2(Σ11/2Σ2Σ11/2)1/2)W_2^2 = \norm{\vb{m}_1 - \vb{m}_2}^2 + \tr(\mat{\Sigma}_1 + \mat{\Sigma}_2 - 2(\mat{\Sigma}_1^{1/2}\mat{\Sigma}_2\mat{\Sigma}_1^{1/2})^{1/2}), with an optimal affine plan. This is FID.
  • The empirical measure converges in W1W_1 as n−1/dn^{-1/d} for d≥3d \ge 3: halving error costs 2d2^d times more samples.
  • WpW_p metrizes convergence in distribution plus order-pp moments; total variation is stronger and KL controls TV by Pinsker.