Wasserstein distance

Also known as: earth mover's distance · EMD

On this page 7

The Wasserstein distance is a metric between two probability distributions equal to the minimum total cost of transporting mass from one distribution to the other, where cost is measured as distance moved multiplied by the amount of mass moved. In optimization for artificial intelligence, it is also known as the earth mover’s distance (EMD), and it appears wherever a model must compare, align or generate distributions rather than single points.

Unlike divergences that compare probabilities point by point, the Wasserstein distance respects the geometry of the underlying space. Two distributions that do not overlap at all still receive a finite, meaningful distance that shrinks smoothly as they move closer, which is why it became central to Wasserstein GANs, domain adaptation and distribution-aware evaluation.

How the Wasserstein distance is defined

The Wasserstein distance is defined as the solution of an optimal transport problem. Given distributions P and Q on a metric space and a ground cost d(x, y), a transport plan is a joint distribution whose marginals are P and Q. The Wasserstein-p distance is the p-th root of the minimum expected cost d(x, y) raised to the power p over all such plans.

For discrete distributions, the problem becomes a linear program: a matrix of flows between n source points and m target points, with row and column sums fixed to the two histograms. The optimal flow matrix is sparse, with at most n + m – 1 nonzero entries, which reflects the vertex structure that the simplex algorithm exploits.

The table below summarizes the main ingredients of the definition and their role in the computation.

ComponentMeaningTypical choice
Ground costPrice of moving one unit of mass between two pointsEuclidean or squared Euclidean distance
Transport planJoint distribution coupling P and QMatrix of flows for discrete data
Order pExponent applied to the costp = 1 or p = 2
Marginal constraintsPlan must reproduce both distributionsRow and column sums fixed
Optimal valueMinimum total transport costReported as W1 or W2
Components of the Wasserstein definition

Wasserstein-1, Wasserstein-2 and their special forms

The most common orders are W1 and W2, and each has properties that make it useful in different settings. W1 admits the Kantorovich-Rubinstein duality, which rewrites the distance as the largest difference in expectations achievable by a 1-Lipschitz function. This dual form is what Wasserstein GANs approximate with a constrained critic network.

W2 has a rich geometric structure: it turns the space of distributions into a curved space where displacement interpolation traces the shortest path between distributions. For two Gaussian distributions, W2 has a closed-form expression based on the means and covariance matrices, which underlies the Frechet Inception Distance used to evaluate image generators.

The following table compares the main variants and where each one is typically chosen.

VariantKey propertyTypical use in AI
Wasserstein-1Dual form over Lipschitz functionsGAN critics, robust comparison of histograms
Wasserstein-2Closed form for Gaussians, geodesic structureGenerative model evaluation, flow models
One-dimensional caseEquals area between cumulative distributionsFast comparison of scalar outputs
Sliced WassersteinAverage of many 1D projectionsLarge-scale training losses
Entropic (Sinkhorn) distanceRegularized, smooth and fastDifferentiable losses on GPUs
Common variants of the Wasserstein distance

Computing the Wasserstein distance in practice

Exact computation is costly: solving the transport linear program for n points scales roughly as O(n^3 log n) with network simplex or interior-point methods. This is acceptable for a few thousand points but becomes impractical for large batches in deep learning, which motivated faster approximations.

Sinkhorn iterations add an entropy penalty to the transport problem, which turns it into a matrix-scaling task solvable by alternating normalizations in about O(n^2) per iteration. The regularization strength trades accuracy for speed: a small value approaches the exact distance but converges slowly and can underflow, while a large value blurs the plan. Log-domain stabilization is the standard fix for numerical problems.

  • Exact solvers suit small, high-stakes comparisons such as auditing two datasets.
  • Sinkhorn solvers suit differentiable losses inside training loops.
  • Sliced estimators suit very high-dimensional data where only projections are affordable.
  • Neural dual estimators suit adversarial training, at the cost of approximation bias.

How it compares with other distribution measures

The Wasserstein distance differs from information-theoretic divergences because it accounts for how far mass moves, not only where probabilities differ. Kullback-Leibler divergence becomes infinite when supports do not overlap, and Jensen-Shannon divergence saturates at a constant, so neither provides useful gradients when a generator starts far from the data.

The comparison below shows why practitioners choose a transport-based measure in some tasks and a divergence in others.

MeasureDisjoint supportsUses geometryCost to compute
Wasserstein distanceFinite and informativeYesHigh unless approximated
KL divergenceInfiniteNoLow with densities
Jensen-Shannon divergenceConstant at log 2NoLow with densities
Total variationMaximal value of 1NoLow for histograms
Maximum mean discrepancyFiniteThrough the kernelModerate, quadratic in samples
Wasserstein distance versus other measures

Limitations and common mistakes

The Wasserstein distance suffers from the curse of dimensionality in its sample estimates: the error of the empirical estimate decreases only at a rate near n^(-1/d) in d dimensions. Comparing two small samples of high-dimensional embeddings can therefore produce distances dominated by sampling noise rather than by real differences.

The result also depends heavily on the choice of ground cost. Raw pixel distance makes two images with a one-pixel shift look far apart, so practitioners usually compute the distance in a learned feature space. The table lists frequent problems and their remedies.

SymptomLikely causeRemedy
Unstable GAN criticLipschitz constraint enforced by crude weight clippingUse a gradient penalty or spectral normalization
Sinkhorn returns NaN valuesRegularization too small for the cost scaleNormalize costs and iterate in the log domain
Distances not comparable across runsDifferent ground costs or feature extractorsFix the cost and feature space in advance
Noisy estimatesToo few samples in high dimensionsIncrease samples or use sliced estimators
Frequent problems and fixes

Explained without jargon

Imagine two piles of sand with different shapes. You want to reshape the first pile into the second. Each shovelful costs effort based on how far you carry it. The Wasserstein distance is the least total effort needed to do the job.

This makes it a natural way to compare groups of data. If two groups are similar, little sand moves a short way. If they are very different, much sand travels far. Even piles that do not touch get a sensible score, which is why AI systems use it to learn and to judge their own output.

A typical use case

A machine learning team trains a model on product photos from one warehouse and must deploy it in a second warehouse with different lighting and cameras. To measure the shift, the engineers extract 512-dimensional feature vectors from 5,000 images at each site and compute an entropic Wasserstein distance between the two sets with Sinkhorn iterations on a GPU.

The distance is several times larger than the value measured between two random halves of the original data, which confirms a substantial domain shift. The team then adds an optimal transport alignment term to the training loss, which pulls the feature distributions of both sites together. After retraining, the distance falls by more than half and classification accuracy at the second warehouse recovers to within a few points of the original site.