> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# From KL divergence to the Wasserstein distance

> Why KL misjudges distance between densities, and what W2 measures.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/optimal-transport/kl-to-wasserstein/index.ipynb)

You already compare distributions with the KL divergence. Maximum likelihood minimizes it, and the ELBO of a variational autoencoder contains it. This section shows a case where KL gives a poor answer to the question of how far apart two densities are. It then derives the Wasserstein distance from transport cost. Everything here uses two Gaussians on the real line, where each quantity has a closed form. [Transport maps and couplings](https://aegean.ai/aiml-common/lectures/optimal-transport/maps-and-couplings/index.md) carries the same ideas to a mixture target, where no closed form exists.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> import matplotlib.pyplot as plt
> from cycler import cycler
> from matplotlib_inline.backend_inline import set_matplotlib_formats
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]
> plt.rcParams.update({
>     "figure.facecolor": "none", "axes.facecolor": "none",
>     "savefig.facecolor": "none", "savefig.transparent": True,
>     "text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY,
>     "xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY,
>     "grid.color": FIG_GRAY, "grid.alpha": 0.25,
>     "legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0,
>     "axes.prop_cycle": cycler(color=FIG_COLORS),
>     "svg.hashsalt": "aiml", "svg.fonttype": "path",
> })
> from scipy import stats
> ```

## Maximum likelihood and the KL divergence

Maximum likelihood fits a model $q_\theta$ to data drawn from a density $p$ by maximizing the expected log-likelihood $\mathbb{E}_{x \sim p}[\log q_\theta(x)]$. The negative of this quantity is the cross-entropy $H(p, q_\theta)$, and [Entropy](https://aegean.ai/aiml-common/lectures/entropy/index.md) and [Maximum likelihood estimation of a marginal model](https://aegean.ai/aiml-common/lectures/optimization/maximum-likelihood/marginal_maximum_likelihood.md) show that it splits into two terms:

$$
H(p, q_\theta) = H(p) + \mathrm{KL}(p \,\|\, q_\theta).
$$

Since the entropy $H(p)$ does not depend on $\theta$, maximizing the likelihood minimizes $\mathrm{KL}(p \,\|\, q_\theta)$.

## The KL divergence between two Gaussians

For two Gaussians $p = \mathcal{N}(\mu_p, \sigma_p^2)$ and $q = \mathcal{N}(\mu_q, \sigma_q^2)$ the KL divergence has a closed form,

$$
\mathrm{KL}(p \,\|\, q) = \log \frac{\sigma_q}{\sigma_p} + \frac{\sigma_p^2 + (\mu_p - \mu_q)^2}{2 \sigma_q^2} - \frac{1}{2}.
$$

It is not symmetric. For $\mathcal{N}(0, 1)$ and $\mathcal{N}(0, 4)$ the two orders give 0.32 and 0.81, as the check below prints. When the two widths are equal, $\sigma_p = \sigma_q = \sigma$, the logarithm vanishes, the variance term cancels the constant, and

$$
\mathrm{KL}(p \,\|\, q) = \frac{(\mu_p - \mu_q)^2}{2 \sigma^2}.
$$

The code below defines the closed forms used in this section and checks the KL values.

> [accordion] Code
>
> ```python theme={null}
> DMU = 2.0  # gap between the two means in the sweeps
> SIGMAS = np.array([2.0, 1.0, 0.5, 0.1])  # common standard deviations in the sweep
> RHOS = np.array([0.0, 0.8, -0.8, 1.0])  # correlations of the four couplings
> RNG = np.random.default_rng(0)
> N_MC = 200_000  # samples per Monte Carlo check
>
>
> def kl_gauss(mu_p, s_p, mu_q, s_q):
>     """KL divergence KL(p || q) between two 1D Gaussians.
>
>     Args:
>         mu_p, s_p: mean and standard deviation of p.
>         mu_q, s_q: mean and standard deviation of q.
>
>     Returns:
>         float: log(s_q / s_p) + (s_p^2 + (mu_p - mu_q)^2) / (2 s_q^2) - 1/2.
>     """
>     return float(np.log(s_q / s_p) + (s_p**2 + (mu_p - mu_q) ** 2) / (2 * s_q**2) - 0.5)
>
>
> def coupling_cost(mu0, s0, mu1, s1, rho):
>     """Expected squared displacement E[(X - Y)^2] of a Gaussian coupling.
>
>     Args:
>         mu0, s0: mean and standard deviation of the source p_0 (law of X).
>         mu1, s1: mean and standard deviation of the target p_1 (law of Y).
>         rho: correlation between X and Y, in [-1, 1].
>
>     Returns:
>         float: (mu0 - mu1)^2 + s0^2 + s1^2 - 2 rho s0 s1.
>     """
>     return float((mu0 - mu1) ** 2 + s0**2 + s1**2 - 2 * rho * s0 * s1)
>
>
> def w2_gauss(mu0, s0, mu1, s1):
>     """Wasserstein-2 distance between two 1D Gaussians.
>
>     Args:
>         mu0, s0: mean and standard deviation of p_0.
>         mu1, s1: mean and standard deviation of p_1.
>
>     Returns:
>         float: sqrt((mu0 - mu1)^2 + (s0 - s1)^2), the cost of the rho = 1 coupling.
>     """
>     return float(np.sqrt((mu0 - mu1) ** 2 + (s0 - s1) ** 2))
>
>
> def gauss_map(x, mu0, s0, mu1, s1):
>     """Optimal transport map T from N(mu0, s0^2) to N(mu1, s1^2).
>
>     Args:
>         x: points drawn from p_0.
>         mu0, s0: mean and standard deviation of p_0.
>         mu1, s1: mean and standard deviation of p_1.
>
>     Returns:
>         np.ndarray: T(x) = mu1 + (s1 / s0) (x - mu0), the increasing affine map.
>     """
>     return mu1 + (s1 / s0) * (np.asarray(x) - mu0)
>
>
> def sample_coupling(mu0, s0, mu1, s1, rho, n, rng):
>     """Draw n pairs (X, Y) from the Gaussian coupling with correlation rho.
>
>     Args:
>         mu0, s0: mean and standard deviation of X ~ p_0.
>         mu1, s1: mean and standard deviation of Y ~ p_1.
>         rho: correlation between X and Y.
>         n: number of pairs.
>         rng: numpy random generator.
>
>     Returns:
>         tuple: arrays x and y of length n. With z1, z2 independent standard normals,
>         x = mu0 + s0 z1 and y = mu1 + s1 (rho z1 + sqrt(1 - rho^2) z2).
>     """
>     z1, z2 = rng.standard_normal(n), rng.standard_normal(n)
>     x = mu0 + s0 * z1
>     y = mu1 + s1 * (rho * z1 + np.sqrt(1 - rho**2) * z2)
>     return x, y
> ```
>
> ```python theme={null}
> kl_sweep = np.array([kl_gauss(0.0, s, DMU, s) for s in SIGMAS])
> assert np.allclose(kl_sweep, [0.5, 2.0, 8.0, 200.0])
> kl_pq, kl_qp = kl_gauss(0.0, 1.0, 0.0, 2.0), kl_gauss(0.0, 2.0, 0.0, 1.0)
> assert np.isclose(kl_pq, np.log(2) + 1 / 8 - 1 / 2) and not np.isclose(kl_pq, kl_qp)
> for s, k in zip(SIGMAS, kl_sweep):
>     print(f"sigma = {s:4.1f}   KL = {k:7.2f}")
> print(f"KL(N(0,1) || N(0,4)) = {kl_pq:.4f},  KL(N(0,4) || N(0,1)) = {kl_qp:.4f}")
> ```

```output theme={null}
sigma =  2.0   KL =    0.50
sigma =  1.0   KL =    2.00
sigma =  0.5   KL =    8.00
sigma =  0.1   KL =  200.00
KL(N(0,1) || N(0,4)) = 0.3181,  KL(N(0,4) || N(0,1)) = 0.8069
```

## Where KL falls short

Hold the gap between the means at $\Delta\mu = \mu_q - \mu_p = 2$ and shrink the common width $\sigma$. The two densities stay the same distance apart, and only their width changes. The KL divergence grows as $1/\sigma^2$ all the same: it is 0.5 at $\sigma = 2$, 2 at $\sigma = 1$, 8 at $\sigma = 0.5$ and 200 at $\sigma = 0.1$.

KL compares the two densities point by point through the ratio $p(x)/q(x)$. Narrow Gaussians overlap less, so the ratio becomes extreme where $p$ has its mass. In the limit of two point masses at 0 and 2 the KL divergence is infinite. It is also infinite for point masses at 0 and 0.001. KL depends only on the two density values at each point, so the distance the mass would have to move to turn one density into the other does not enter it.

![Four panels in a two by two grid, each with two Gaussian densities centered at 0 and 2 with a common standard deviation of 2, 1, 0.5 and 0.1 read row by row. The bumps narrow and separate while their centers stay 2 apart. Panel titles give the KL divergence as 0.5, 2, 8 and 200, and W2 as 2 in every panel.](https://mintcdn.com/aegeanaiinc/_jlBgoM0WEG9jqbU/aiml-common/lectures/optimal-transport/kl-to-wasserstein/images/cell_4_output_1.svg?fit=max\&auto=format\&n=_jlBgoM0WEG9jqbU\&q=85\&s=8b89e81da20ed46cb7e87846091d132a)

## Couplings of two Gaussians

To measure how far mass moves, you have to say where each piece of mass goes. From here on the source is $p_0$ and the target is $p_1$, the names the rest of the chapter uses. Take $p_0 = \mathcal{N}(0, 1)$ and $p_1 = \mathcal{N}(2, 1)$.

A coupling $\pi$ of $p_0$ and $p_1$ is a joint distribution of a pair $(X, Y)$ with $X \sim p_0$ and $Y \sim p_1$. It pairs source points with target points. Its cost is the expected squared distance the mass travels, $\mathbb{E}_\pi[(X - Y)^2]$. Many couplings share the same two marginals. For any of them, with $\rho$ the correlation between $X$ and $Y$, expanding the square gives

$$
\begin{aligned}
\mathbb{E}[(X - Y)^2] &= (\mu_0 - \mu_1)^2 + \sigma_0^2 + \sigma_1^2 - 2 \rho \, \sigma_0 \sigma_1 \\
&= 6 - 2\rho \quad \text{for these two Gaussians.}
\end{aligned}
$$

The independent coupling, $\rho = 0$, costs 6. A positive correlation sends low source points to low target points and costs less, 4.4 at $\rho = 0.8$. A negative correlation crosses the pairs and costs more, 7.6 at $\rho = -0.8$. The figure shows samples from four bivariate Gaussian couplings, and the check after it compares each formula with a sample average.

![Four scatter plots in a two by two grid of sample pairs with source x on the horizontal axis and target y on the vertical axis. With correlation 0 the cloud is round, cost 6. With 0.8 it tilts upward, cost 4.4. With minus 0.8 it tilts downward, cost 7.6. With correlation 1 every point lies on the line y = x + 2, cost 4.](https://mintcdn.com/aegeanaiinc/_jlBgoM0WEG9jqbU/aiml-common/lectures/optimal-transport/kl-to-wasserstein/images/cell_5_output_1.svg?fit=max\&auto=format\&n=_jlBgoM0WEG9jqbU\&q=85\&s=a7ae0d102c16ec8c255eb2642cc76d0a)

> [accordion] Code
>
> ```python theme={null}
> costs = np.array([coupling_cost(0.0, 1.0, DMU, 1.0, r) for r in RHOS])
> assert np.allclose(costs, [6.0, 4.4, 7.6, 4.0])
> mc = np.array([np.mean((x - y) ** 2) for x, y in
>                (sample_coupling(0.0, 1.0, DMU, 1.0, r, N_MC, RNG) for r in RHOS)])
> assert np.max(np.abs(mc - costs)) < 0.05
> for r, c, m in zip(RHOS, costs, mc):
>     print(f"rho = {r:+.1f}   E[(X-Y)^2] formula = {c:.2f}   sampled = {m:.3f}")
> ```

```output theme={null}
rho = +0.0   E[(X-Y)^2] formula = 6.00   sampled = 6.011
rho = +0.8   E[(X-Y)^2] formula = 4.40   sampled = 4.394
rho = -0.8   E[(X-Y)^2] formula = 7.60   sampled = 7.603
rho = +1.0   E[(X-Y)^2] formula = 4.00   sampled = 4.000
```

## The Wasserstein distance between Gaussians

The cost decreases as $\rho$ grows, and by the Cauchy-Schwarz inequality a correlation never exceeds 1. So over all couplings the cost is smallest at $\rho = 1$, where $Y$ is an increasing affine function of $X$. There the cost is $(\mu_0 - \mu_1)^2 + (\sigma_0 - \sigma_1)^2$. This smallest cost defines the squared Wasserstein distance,

$$
W_2^2(p_0, p_1) = \min_{\pi} \; \mathbb{E}_\pi\bigl[(X - Y)^2\bigr].
$$

For two Gaussians on the line the minimum is the cost of the $\rho = 1$ coupling, so

$$
W_2^2(p_0, p_1) = (\mu_0 - \mu_1)^2 + (\sigma_0 - \sigma_1)^2 .
$$

$W_2$ is the Euclidean distance between the points $(\mu_0, \sigma_0)$ and $(\mu_1, \sigma_1)$ in the plane of means and standard deviations (Remark 2.31 in (Peyré & Cuturi, 2018)). [Transport maps and couplings](https://aegean.ai/aiml-common/lectures/optimal-transport/maps-and-couplings/index.md) shows that the increasing pairing is optimal in 1D for any two densities.

The optimal coupling has no density. All of its mass lies on a line in the $(x, y)$ plane, as the last panel of the figure shows. A coupling only has to have the right two marginals, so nothing stops it from concentrating on a line.

## The transport map

At $\rho = 1$ each source point goes to exactly one target point. The coupling is the graph of the map

$$
T(x) = \mu_1 + \frac{\sigma_1}{\sigma_0} (x - \mu_0),
$$

which shifts and rescales the source. If $X \sim p_0$, then $T(X)$ has mean $\mu_1$ and standard deviation $\sigma_1$, so $T$ carries $p_0$ onto $p_1$. The map is increasing, and it sends the point at quantile level $u$ of $p_0$ to the point at the same level of $p_1$. It is the quantile map $T = F_1^{-1} \circ F_0$, which solves Monge's problem in 1D. [Transport maps and couplings](https://aegean.ai/aiml-common/lectures/optimal-transport/maps-and-couplings/index.md) computes that map numerically for the mixture target, where no formula exists. Moving each point at constant speed along the straight line from $x$ to $T(x)$ gives the path of densities studied in [Dynamic optimal transport](https://aegean.ai/aiml-common/lectures/optimal-transport/dynamic-transport/index.md).

The check below confirms the $W_2$ values and the map. For $\mathcal{N}(0, 1)$ and $\mathcal{N}(2, 3^2)$ the formula gives $W_2^2 = 4 + 4 = 8$, and the squared distance between the two quantile functions, averaged over levels $u$, gives the same number.

> [accordion] Code
>
> ```python theme={null}
> w2_sweep = np.array([w2_gauss(0.0, s, DMU, s) for s in SIGMAS])
> assert np.allclose(w2_sweep, 2.0)
> assert np.isclose(w2_gauss(0.0, 1.0, 2.0, 3.0) ** 2, 8.0)
> u = (np.arange(100_000) + 0.5) / 100_000
> q_int = np.mean((stats.norm.ppf(u, 0, 1) - stats.norm.ppf(u, 2, 3)) ** 2)
> assert abs(q_int - 8.0) < 1e-3
> y_T = gauss_map(RNG.normal(0.0, 1.0, N_MC), 0.0, 1.0, 2.0, 3.0)
> assert abs(y_T.mean() - 2.0) < 0.03 and abs(y_T.std() - 3.0) < 0.03
> print("W2 for the sweep:", ", ".join(f"{w:.2f}" for w in w2_sweep))
> print(f"N(0,1) to N(2,9): (dmu)^2 + (dsigma)^2 = 8,  quantile integral = {q_int:.5f}")
> print(f"T(x) on N(0,1) samples: mean = {y_T.mean():.3f}, std = {y_T.std():.3f}")
> ```

```output theme={null}
W2 for the sweep: 2.00, 2.00, 2.00, 2.00
N(0,1) to N(2,9): (dmu)^2 + (dsigma)^2 = 8,  quantile integral = 7.99995
T(x) on N(0,1) samples: mean = 2.007, std = 3.000
```

## KL and Wasserstein compared

Repeat the sweep from the KL section with both measures. $W_2$ stays at 2 for every width, because the mass moves the same distance. KL grows from 0.5 to 200.

![Log-log plot of KL divergence and W2 against the common standard deviation from 0.1 to 2, for two Gaussians with means 2 apart. KL falls along a straight line from 200 to 0.5. W2 is a flat line at 2.](https://mintcdn.com/aegeanaiinc/_jlBgoM0WEG9jqbU/aiml-common/lectures/optimal-transport/kl-to-wasserstein/images/cell_8_output_1.svg?fit=max\&auto=format\&n=_jlBgoM0WEG9jqbU\&q=85\&s=1eff46211dc6b393fcf72b6738edfe88)

| | KL divergence | Wasserstein distance $W_2$ |
| - | - | - |
| Compares | density ratios, point by point | where mass goes, and how far |
| Two Gaussians, common $\sigma$, means $\Delta\mu$ apart | $(\Delta\mu)^2 / (2\sigma^2)$, grows as $\sigma \to 0$ | $\lvert \Delta\mu \rvert$ for every $\sigma$ |
| Symmetric | no | yes |
| Disjoint supports | infinite | finite, if both have finite variance |
| Used by | maximum likelihood, the ELBO | optimal transport |

Maximum likelihood fits a model through KL, which compares values of densities. The Wasserstein distance depends on how far apart points are on the line, so it carries the geometry of the space. Next, [Transport maps and couplings](https://aegean.ai/aiml-common/lectures/optimal-transport/maps-and-couplings/index.md) solves the problem for the mixture target. [Dynamic optimal transport](https://aegean.ai/aiml-common/lectures/optimal-transport/dynamic-transport/index.md) then moves the mass along a path in time.

## References

* Peyré, G., Cuturi, M. (2018). *Computational Optimal Transport*. arXiv \[stat.ML]. [DOI](https://doi.org/10.48550/arXiv.1803.00567)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/optimal-transport/kl-to-wasserstein).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.