Search

Search papers and lessons

Wasserstein Distance

Level 4 · 14 min read

The Wasserstein distance is the least total work needed to reshape one probability distribution into another, where the work is mass moved multiplied by the distance it travels.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Calculus
  • Information theory
  • Sign in to see your progress

TL;DR

Picture one probability distribution as a pile of sand and another as the shape you want to build from it. The Wasserstein distance is the least total effort needed to move the sand, where each grain costs its mass times the distance it travels. It is a true distance between distributions: it is zero only when they match, it is symmetric, and it obeys the triangle inequality.

Where you'll see it: in training Wasserstein GANs, in comparing histograms of measurements, and in matching the feature distributions of two data sources in machine learning.

Intuition

Moving a pile of sand

A density or a histogram describes how a quantity is spread out. Two such shapes can differ in two ways: they can put their mass in different places, or they can put the same mass in nearly the same places. The Wasserstein question is: what is the cheapest way to turn one shape into the other?

Imagine each shape is a pile of sand. Moving one grain one metre costs one unit of effort. The Wasserstein distance is the total effort of the cheapest way to reshape pile A into pile B. If B is A pushed a little to the right, the effort is small. If B is A pushed far to the right, the effort is large. The measure respects closeness in the space the mass lives in, and it does so without any extra rule.

Why not compare heights?

A common way to compare two densities is to look at their heights point by point, as KL divergence does. That works when the two shapes overlap. When they do not overlap at all, the height comparison breaks down: wherever one shape has mass the other has none, the comparison says "infinitely different", even if the two piles are one centimetre apart. The Wasserstein distance measures the horizontal gap instead, so it stays finite and shrinks as the piles approach each other.

−4−2024600.10.20.30.40.5xdensity
  • P = N(0, 1)
  • Q = N(2, 1)
Q is P slid two units to the right. Moving each grain of P two units to the right costs two units of work per unit of mass, so the Wasserstein distance between them is 2.

The math

Couplings

A coupling of two distributions PP and QQ is a joint distribution γ\gamma on pairs (x,y)(x, y) whose two margins (the distributions of the first and second coordinate alone) are PP and QQ. If (X,Y)(X, Y) is drawn from γ\gamma, then XX has law PP and YY has law QQ. Read γ\gamma as a transport plan: it says how much of the mass at xx is sent to the target yy. Write Π(P,Q)\Pi(P, Q) for the set of all couplings. Every coupling sends out exactly what PP holds and fills exactly what QQ needs.

Definition

Definition: Wasserstein distance

Let (X,d)(X, d) be a metric space, and let PP and QQ be probability distributions on XX. For p≥1p \ge 1, the Wasserstein distance of order pp is

Wp(P,Q)=(inf⁡γ∈Π(P,Q)E(X,Y)∼γ[d(X,Y)p])1/p.W_p(P, Q) = \left( \inf_{\gamma \in \Pi(P, Q)} \mathbb{E}_{(X, Y) \sim \gamma}\left[ d(X, Y)^p \right] \right)^{1/p}.

The expectation is the average cost of one plan, where the cost of moving from XX to YY is the distance d(X,Y)d(X, Y) raised to the power pp. The infimum (the greatest lower bound, here simply the cost of the cheapest plan) picks the cheapest plan among all couplings, and the outer power 1/p1/p brings the answer back to units of distance. The case p=1p = 1 is the earth mover's distance, W1W_1. The case p=2p = 2 is the one most often used in theory, because it has the cleanest formulas.

Discrete distributions are a linear program

Suppose PP puts mass pip_i on points xix_i, and QQ puts mass qjq_j on points yjy_j. A coupling is then a table πij≥0\pi_{ij} \ge 0 with row sums ∑jπij=pi\sum_j \pi_{ij} = p_i (every source sends out what it holds) and column sums ∑iπij=qj\sum_i \pi_{ij} = q_j (every target receives what it needs). With cost cij=d(xi,yj)c_{ij} = d(x_i, y_j),

W1(P,Q)=min⁡π∑i,jcij πij,W_1(P, Q) = \min_{\pi} \sum_{i,j} c_{ij}\, \pi_{ij},

where the minimum runs over the tables that satisfy the row and column constraints. The objective and the constraints are all linear, so this is a linear program, and its best solution sits at a corner of the feasible set. That is why Wasserstein distances between histograms can be computed exactly.

The one-dimensional formula

On the real line with d(x,y)=∣x−y∣d(x, y) = \lvert x - y \rvert, the best plan is the sorted matching: the lowest source goes to the lowest target, and so on. The distance then has a formula in terms of the cumulative distribution functions FP(x)=P(X≤x)F_P(x) = P(X \le x) and FQ(x)=Q(Y≤x)F_Q(x) = Q(Y \le x):

W1(P,Q)=∫−∞∞∣FP(x)−FQ(x)∣ dx.W_1(P, Q) = \int_{-\infty}^{\infty} \left\lvert F_P(x) - F_Q(x) \right\rvert \, dx.

At each point xx, the quantity ∣FP(x)−FQ(x)∣\lvert F_P(x) - F_Q(x) \rvert is the net amount of mass that must cross xx to turn PP into QQ. Integrating over all xx adds up those crossings, and each crossing is paid for by the distance it spans. This is the most useful formula in practice, because you can check it by hand.

For general pp, the same idea works through the quantile function F−1F^{-1}, the inverse of the CDF:

Wp(P,Q)p=∫01∣FP−1(u)−FQ−1(u)∣p du.W_p(P, Q)^p = \int_0^1 \left\lvert F_P^{-1}(u) - F_Q^{-1}(u) \right\rvert^p \, du.

The metric axioms

Wasserstein distance satisfies the axioms of a metric on the set of distributions. It is zero only when P=QP = Q. It is symmetric, because swapping the roles of PP and QQ transposes every plan. The triangle inequality comes from gluing: given a plan from PP to QQ and a plan from QQ to RR, you can glue them along their shared middle distribution QQ to get a plan from PP to RR, and the cost of that plan is the sum of the two costs.

The dual form for p=1p = 1

For p=1p = 1 there is a second formula that uses no plans at all. A function f:X→Rf : X \to \mathbb{R} is 1-Lipschitz if ∣f(x)−f(y)∣≤d(x,y)\lvert f(x) - f(y) \rvert \le d(x, y) for all xx and yy, so it never changes faster than the distance does (see Lipschitz Continuity). The Kantorovich–Rubinstein duality says

W1(P,Q)=sup⁡f is 1-Lipschitz(EX∼P[f(X)]−EY∼Q[f(Y)]).W_1(P, Q) = \sup_{f \text{ is 1-Lipschitz}} \left( \mathbb{E}_{X \sim P}[f(X)] - \mathbb{E}_{Y \sim Q}[f(Y)] \right).

Each allowed test function ff gives a lower bound on the distance: its average under PP minus its average under QQ. The supremum (the least upper bound, here the best value over all allowed ff) is exactly W1W_1. This form is the one used to train GANs, because it turns the distance into an optimisation over a single function.

Worked examples

Example
Tiny: two grains of mass on a line

PP puts mass 12\tfrac12 at 00 and 12\tfrac12 at 22. QQ puts mass 12\tfrac12 at 11 and 12\tfrac12 at 33. Use d(x,y)=∣x−y∣d(x, y) = \lvert x - y \rvert.

  1. Sorted matching: send the mass at 00 to 11 (distance 1) and the mass at 22 to 33 (distance 1). The cost is 12⋅1+12⋅1=1\tfrac12 \cdot 1 + \tfrac12 \cdot 1 = 1.
  2. The other pairing sends 00 to 33 and 22 to 11. Its cost is 12⋅3+12⋅1=2\tfrac12 \cdot 3 + \tfrac12 \cdot 1 = 2, which is worse.
  3. Check with the CDF formula. FPF_P is 00 before 00, 12\tfrac12 on [0,2)[0, 2), and 11 from 22 on. FQF_Q is 00 before 11, 12\tfrac12 on [1,3)[1, 3), and 11 from 33 on. The difference ∣FP−FQ∣\lvert F_P - F_Q \rvert is 12\tfrac12 on [0,1)[0, 1), 00 on [1,2)[1, 2), 12\tfrac12 on [2,3)[2, 3), and 00 elsewhere. Its integral is 12⋅1+12⋅1=1\tfrac12 \cdot 1 + \tfrac12 \cdot 1 = 1.

Interpretation: the plan and the formula agree on 1. Since the formula gives the exact distance, no plan can do better, so W1(P,Q)=1W_1(P, Q) = 1.

Example
Standard: a histogram with three bins

Measurements are sorted into three bins at positions 1, 2 and 3 (low, medium, high), with d(i,j)=∣i−j∣d(i, j) = \lvert i - j \rvert. Histogram PP is (0.6, 0.4, 0)(0.6,\ 0.4,\ 0) and histogram QQ is (0, 0.3, 0.7)(0,\ 0.3,\ 0.7).

  1. Use the CDF formula with the bins as points. After bin 1, FP=0.6F_P = 0.6 and FQ=0F_Q = 0. After bin 2, FP=1.0F_P = 1.0 and FQ=0.3F_Q = 0.3.
  2. Between positions 1 and 2, the mass that must cross is ∣0.6−0∣=0.6\lvert 0.6 - 0 \rvert = 0.6. The gap is 1, so this stretch contributes 0.60.6.
  3. Between positions 2 and 3, the mass that must cross is ∣1.0−0.3∣=0.7\lvert 1.0 - 0.3 \rvert = 0.7, contributing 0.70.7.
  4. Total: W1(P,Q)=0.6+0.7=1.3W_1(P, Q) = 0.6 + 0.7 = 1.3.
  5. Check with an explicit plan. Move 0.30.3 from bin 1 to bin 2 (cost 0.3×10.3 \times 1), move 0.30.3 from bin 1 to bin 3 (cost 0.3×20.3 \times 2), and move 0.40.4 from bin 2 to bin 3 (cost 0.4×10.4 \times 1). Bin 1 sends 0.60.6, which it holds. Bin 2 sends 0.40.4, which it holds. Bin 2 receives 0.30.3, which is what it needs. Bin 3 receives 0.3+0.4=0.70.3 + 0.4 = 0.7, which is what it needs. The total cost is 0.3+0.6+0.4=1.30.3 + 0.6 + 0.4 = 1.3.
flowchart LR
  S1["source bin 1 (0.6)"] -->|"0.3 at cost 1"| T2["target bin 2 (0.3)"]
  S1 -->|"0.3 at cost 2"| T3["target bin 3 (0.7)"]
  S2["source bin 2 (0.4)"] -->|"0.4 at cost 1"| T3

Interpretation: 0.60.6 units of mass cross the boundary between bins 1 and 2, and 0.70.7 cross the boundary between bins 2 and 3. The cheapest plan pays for each crossing once, and the explicit plan costs exactly what the formula predicted.

Example
Standard: two Gaussians

Let P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(2,4)Q = \mathcal{N}(2, 4). The means are 00 and 22, and the standard deviations are 11 and 22. For two univariate Gaussians there is a closed form for p=2p = 2:

W2(P,Q)2=(μ1−μ2)2+(σ1−σ2)2.W_2(P, Q)^2 = (\mu_1 - \mu_2)^2 + (\sigma_1 - \sigma_2)^2.
  1. Mean difference: (0−2)2=4(0 - 2)^2 = 4.
  2. Standard deviation difference: (1−2)2=1(1 - 2)^2 = 1.
  3. Add: W22=4+1=5W_2^2 = 4 + 1 = 5.
  4. Take the square root: W2=5≈2.236W_2 = \sqrt{5} \approx 2.236.

Interpretation: part of the distance comes from shifting the centre by 2 and part from changing the spread by 1. The two pieces combine like the legs of a right triangle, so the answer is not the simple sum 2+1=32 + 1 = 3.

Example
Realistic: a generator that starts far from the data

Suppose the real data all sit at one point, 00. A generative model outputs a single value θ≥0\theta \ge 0, so its distribution is QθQ_\theta, a point mass at θ\theta. Compare the two losses. Write P=δ0P = \delta_0 for the data.

  1. KL divergence. If θ>0\theta \gt 0, the outcome 00 has probability 1 under PP and probability 0 under QθQ_\theta. The divergence is therefore infinite. Every positive θ\theta gets the same infinite loss, so a KL-trained model cannot tell θ=0.1\theta = 0.1 from θ=10\theta = 10, and it gets no signal about which way to move.
  2. Wasserstein distance. The only coupling of two point masses moves all the mass from 00 to θ\theta, so W1(P,Qθ)=θW_1(P, Q_\theta) = \theta.
  3. Dual check. Take f(x)=−xf(x) = -x. It is 1-Lipschitz, because ∣f(x)−f(y)∣=∣x−y∣\lvert f(x) - f(y) \rvert = \lvert x - y \rvert. The dual objective is f(0)−f(θ)=θf(0) - f(\theta) = \theta, which equals the W1W_1 value from step 2, so this ff attains the supremum.
  4. So the loss is θ\theta: 0.10.1 at θ=0.1\theta = 0.1 and 1010 at θ=10\theta = 10. A gradient step lowers it by moving θ\theta toward 00.

Interpretation: the Wasserstein loss says how far off the model is and which way to move. The KL loss says "infinitely wrong" everywhere except at an exact match. Arjovsky, Chintala and Bottou made this kind of argument when they proposed Wasserstein training for GANs.

Tradeoffs and failure modes

SituationProblemBetter choice
Distributions with disjoint supports, such as two point massesKL divergence is infinite, so it gives no gradientWasserstein distance, which stays finite and shrinks as the supports approach
Large numbers of pointsExact transport becomes slow, since it is a large linear programEntropic regularisation with Sinkhorn iterations (Sinkhorn distances)
Samples in high dimensionsDistances between empirical samples converge slowly and are biased upwardUse it with care, reduce the dimension, or use sliced versions that average one-dimensional distances
A poor choice of ground metric ddThe value depends entirely on dd, so bin spacing or a colour scale can change the answerChoose dd so that it matches what "moving" means for the problem

Two practical points follow from the definition. First, the distance inherits the geometry of the space. Moving mass between two nearby colours costs little, while moving it between unrelated categories costs whatever you declared the distance to be. Second, the choice of pp matters. For p=2p = 2 long moves are penalised more heavily than for p=1p = 1. In one dimension both have the cheap formulas above; in higher dimensions there is usually no closed form, and you rely on linear programs or approximations.

History

Gaspard Monge posed the transport problem in 1781, asking how to move earth from cuttings into embankments at the lowest total cost. Leonid Kantorovich recast it as a linear problem in the early 1940s, which is why the distance is sometimes called the Monge–Kantorovich distance. The Russian mathematician Leonid Vaserstein used the same distance in a 1969 paper on Markov processes. The name "Wasserstein" is the spelling that became common in the West. In the late 1990s, computer vision researchers, led by Rubner, Tomasi and Guibas, popularised the distance as the "earth mover's distance" for comparing colour histograms. Cédric Villani's 2009 monograph Optimal Transport: Old and New made the theory central to modern analysis. In 2017, Arjovsky, Chintala and Bottou used the Kantorovich–Rubinstein dual to train GANs, which brought the distance into deep learning. It caught on because it is a true metric, it is finite when other comparisons are not, and it has both a clean theory and a concrete algorithm.

Recap

The Wasserstein distance is the least total cost of turning one distribution into another, where the cost of a move is mass times distance. It is defined as an infimum over couplings, each of which is a joint distribution with the right margins, and the cost is an expectation. For discrete histograms it is a linear program. On the line it is the area between the two CDFs. For p=1p = 1 it also equals a supremum over 1-Lipschitz test functions. Unlike KL divergence, it stays finite when supports do not overlap, and it is a true metric on distributions. It leads to the Wasserstein GAN, and to the general theory of optimal transport, which treats transport between any two measures.

Check yourself

QuestionRecall: what two conditions must a coupling of P and Q satisfy?Show answer

Its first margin must be PP and its second margin must be QQ. In the discrete case, every source's row sum equals the mass PP puts there, and every target's column sum equals the mass QQ asks for.

QuestionComputation: let P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(0,9)Q = \mathcal{N}(0, 9), so QQ has mean 0 and standard deviation 3. Find W2(P,Q)W_2(P, Q).Show answer

The means are equal, so the mean term is 0. The standard deviations are 1 and 3, so the spread term is (1−3)2=4(1 - 3)^2 = 4. Then W22=0+4=4W_2^2 = 0 + 4 = 4, and W2=2W_2 = 2.

QuestionWhy: take two distributions with disjoint supports. Why is KL divergence unhelpful here, while the Wasserstein distance is still useful?Show answer

KL divergence is infinite wherever one distribution has mass and the other has none. That happens for any disjoint pair, however close the supports are, so the divergence carries no information about how far apart they are. The Wasserstein distance measures how far the mass has to travel. That is finite, and it shrinks as the supports move closer, so it gives a useful signal.

QuestionApplied: a GAN's generator starts out producing samples whose distribution has almost no overlap with the real data. Which loss gives training a usable signal, and what must the critic satisfy?Show answer

The Wasserstein loss, computed through the dual form for p=1p = 1, still changes smoothly as the generator moves toward the data. The critic (the network that plays the role of the test function ff) must be 1-Lipschitz. The original Wasserstein GAN enforced this by clipping weights, and later work used a gradient penalty.

Sources