Course contents 03 / 33

03 / 33 · Foundations

Entropy, cross-entropy and KL divergence

From surprise to entropy, cross-entropy and the Kullback–Leibler divergence, why cross-entropy is the training loss of likelihood-based models, and the symmetric Jensen–Shannon divergence.

Prerequisites

Probability · Expectation

On this page 8

The previous note ended with a concrete task: fit the distribution we are training, QQ, to a target distribution PP. To do that we need a number that measures how far QQ is from PP. The standard first choice is the Kullback–Leibler divergence:

DKL(P ∥ Q)=∑x∈XP(x) log⁡P(x)Q(x).D_{\mathrm{KL}}(P \,\|\, Q) = \sum_{x \in \mathcal X} P(x)\,\log\frac{P(x)}{Q(x)} .

What does this formula mean? This note builds it from the ground up: surprise → entropy → cross-entropy → KL. Along the way it explains why cross-entropy is the loss of classifiers and language models. The intermediate quantities are the entropy and the cross-entropy:

H(P)=−∑x∈XP(x)log⁡P(x),H(P,Q)=−∑x∈XP(x)log⁡Q(x).\begin{gathered} H(P) = -\sum_{x\in\mathcal X} P(x)\log P(x), \\ H(P, Q) = -\sum_{x\in\mathcal X} P(x)\log Q(x). \end{gathered}

Notation. PP is the real (data, target) distribution and QQ the believed (model) distribution. H(P)H(P) is the entropy of X∼PX \sim P, sometimes also written H(X)H(X). For continuous distributions, lowercase pp and qq denote densities and sums become integrals; what changes for densities is noted at the end of the KL section. log⁡2\log_2 gives bits and ln⁡\ln gives nats; a plain log⁡\log means either, as long as one base is used throughout.

Surprise#

The construction below follows the intuitive route of Josh Starmer’s StatQuest explanation of entropy (Starmer, 2021); the formal treatment is in Cover and Thomas (2006), chapter 2.

Take two boards with ten marks each. Board A has 5 noughts and 5 crosses; board B has 9 noughts and 1 cross. Draw one mark at random. On which board is getting an X more surprising?

Figure

Where is drawing an X more surprising?

Two boards of noughts and crossesBoard A has five noughts and five crosses, so P(O) = P(X) = 1/2; drawing an X carries 1 bit of surprise and the entropy is 1 bit. Board B has nine noughts and one cross, so P(O) = 9/10 and P(X) = 1/10; drawing the X carries 3.32 bits of surprise and the entropy is 0.469 bits.vsBoard A#O = 5#X = 5P(O) = 5/10, P(X) = 5/10surprise of X: 1 bitentropy H = 1 bitBoard B#O = 9#X = 1P(O) = 9/10, P(X) = 1/10surprise of X: 3.32 bitsentropy H = 0.469 bitsthe rare X: high surpriseTwo boards of noughts and crossesBoard A has five noughts and five crosses, so P(O) = P(X) = 1/2; drawing an X carries 1 bit of surprise and the entropy is 1 bit. Board B has nine noughts and one cross, so P(O) = 9/10 and P(X) = 1/10; drawing the X carries 3.32 bits of surprise and the entropy is 0.469 bits.Board A#O = 5#X = 5P(O) = 5/10, P(X) = 5/10surprise of X: 1 bitentropy H = 1 bitBoard B#O = 9#X = 1P(O) = 9/10, P(X) = 1/10surprise of X: 3.32 bitsentropy H = 0.469 bitsthe rare X: high surprise
Both boards hold ten marks. On board B a cross is rare (1 in 10), so drawing it is more surprising, while the board as a whole is more predictable: its entropy, the average surprise defined in the next section, is lower than that of the balanced board A.

Think of surprise informally as the feeling that something should not have happened. The probabilities of drawing each mark are

A:P(O)=12,    P(X)=12,B:P(O)=910,    P(X)=110.\begin{gathered} \text{A:}\quad P(\text{O}) = \tfrac12,\;\; P(\text{X}) = \tfrac12, \\ \text{B:}\quad P(\text{O}) = \tfrac{9}{10},\;\; P(\text{X}) = \tfrac{1}{10}. \end{gathered}

The cross is clearly more surprising on board B, so surprise must grow as the probability falls.

First attempt: 1/p1/p. To compare 12\tfrac12 and 110\tfrac1{10}, flip them: 1/P(X)1/P(\text{X}) is 22 on board A and 1010 on board B. This ranks the boards correctly, and as a function of pp it is a decreasing curve.

Problem. Take a rigged coin that always lands heads: HHHHHHHHHH. Its two outcomes give

P(H)=1:1P(H)=11=1,P(T)=0:1P(T)=10.\begin{aligned} P(H) = 1 &: \quad \frac{1}{P(H)} = \frac11 = 1, \\[4pt] P(T) = 0 &: \quad \frac{1}{P(T)} = \frac10 . \end{aligned}

Getting heads should not surprise us at all, so the first value should be 00. The second is not even a number.

Fix: take the logarithm.

log⁡1P(H)=log⁡1=0,log⁡1P(T)=log⁡1−log⁡0is undefined.\begin{aligned} \log\frac{1}{P(H)} &= \log 1 = 0, \\ \log\frac{1}{P(T)} &= \log 1 - \log 0 \quad\text{is undefined}. \end{aligned}

The undefined case is harmless: an outcome with probability 00 never happens, so its surprise is never needed. This gives the definition of surprise, also called self-information:

s(x)=log⁡1P(x)=−log⁡P(x).s(x) = \log\frac{1}{P(x)} = -\log P(x).

It equals 00 when P(x)=1P(x) = 1 and grows without bound as P(x)→0P(x) \to 0.

Figure

Surprise must vanish for a certain outcome

Surprise as a function of probabilityTwo decreasing curves over probability from 0 to 1. The dashed curve 1 over P(x) ends at height 1 when P(x) equals 1. The solid curve minus log base 2 of P(x) ends at zero, marked as no surprise. Points mark probability 0.9 with surprise 0.152 bits and probability 0.1 with surprise 3.322 bits.01234500.10.50.91P(x)surprise1 / P(x)−log₂ P(x)P = 0.1: 3.322 bitsP = 0.9: 0.152 bitsno surprise when P(x) = 11/P = 1Surprise as a function of probabilityTwo decreasing curves over probability from 0 to 1. The dashed curve 1 over P(x) ends at height 1 when P(x) equals 1. The solid curve minus log base 2 of P(x) ends at zero, marked as no surprise. Points mark probability 0.9 with surprise 0.152 bits and probability 0.1 with surprise 3.322 bits.01234500.10.50.91P(x)surprise1 / P(x)−log₂ P(x)P = 0.1: 3.322 bits; P = 0.9: 0.152 bitsno surprisewhen P(x) = 11/P = 1
The first attempt, 1/P(x), ranks rare outcomes correctly but still equals 1 when P(x) = 1. Taking the logarithm moves that point to zero. Surprise −log₂ P(x) is in bits; 1/P(x) has no unit. The two marked points are the probabilities 0.1 and 0.9 used in the biased-coin example below.

A biased coin#

Let P(H)=0.9P(H) = 0.9 and P(T)=0.1P(T) = 0.1. Then

log⁡210.9≈0.152,log⁡210.1≈3.322.\log_2\frac{1}{0.9} \approx 0.152, \qquad \log_2\frac{1}{0.1} \approx 3.322 .

Tails is much rarer than heads, so its surprise is much larger.

HeadsTails
Probability P(x)P(x)0.90.90.10.1
Surprise log⁡21P(x)\log_2 \frac{1}{P(x)}0.1520.1523.3223.322

Surprise is additive#

Now flip the coin three times and observe H H T. The flips are independent, so the probability of the sequence is 0.9×0.9×0.10.9 \times 0.9 \times 0.1, and

s(HHT)=log⁡210.9⋅0.9⋅0.1=−log⁡20.9−log⁡20.9−log⁡20.1≈0.152+0.152+3.322=3.626 bits.\begin{aligned} s(\text{HHT}) &= \log_2\frac{1}{0.9\cdot 0.9\cdot 0.1} \\ &= -\log_2 0.9 - \log_2 0.9 - \log_2 0.1 \\ &\approx 0.152 + 0.152 + 3.322 \\ &= 3.626 \text{ bits}. \end{aligned}

The total surprise of a sequence is the sum of the surprises of the individual tosses. This is what the logarithm buys: it turns a product of probabilities into a sum. No other continuous function does this. Suppose s(pq)=s(p)+s(q)s(pq) = s(p) + s(q) for all p,q∈(0,1]p, q \in (0, 1] and put g(t)=s(e−t)g(t) = s(e^{-t}) for t≥0t \ge 0. Then g(t+u)=g(t)+g(u)g(t + u) = g(t) + g(u), and the only continuous solutions of this equation are linear, g(t)=ctg(t) = ct. Hence s(p)=clog⁡1ps(p) = c\log\frac1p. Requiring rare outcomes to be surprising makes c>0c > 0, and the choice of cc is the choice of base. This is why logarithms appear in every information measure; Shannon proved the matching uniqueness result for entropy itself (Shannon, 1948, Theorem 2).

Figure

Probabilities multiply, surprises add

Surprise of the sequence heads, heads, tailsThree boxes: heads with probability 0.9, heads with probability 0.9, tails with probability 0.1. The probability of the sequence is 0.9 times 0.9 times 0.1, which is 0.081. The surprises are 0.152, 0.152 and 3.322 bits, which add up to 3.626 bits, equal to log base 2 of 1 over 0.081. A stacked bar shows that the tails flip contributes almost all of the total.P(H, H, T) = 0.9 × 0.9 × 0.1 = 0.081HP(H) = 0.9log₂(1/0.9)0.152HP(H) = 0.9log₂(1/0.9)0.152TP(T) = 0.1log₂(1/0.1)3.322++tails: 3.322 bitstotal = 3.626 bits = log₂(1/0.081)Surprise of the sequence heads, heads, tailsThree boxes: heads with probability 0.9, heads with probability 0.9, tails with probability 0.1. The probability of the sequence is 0.9 times 0.9 times 0.1, which is 0.081. The surprises are 0.152, 0.152 and 3.322 bits, which add up to 3.626 bits, equal to log base 2 of 1 over 0.081. A stacked bar shows that the tails flip contributes almost all of the total.P(H, H, T) = 0.9 × 0.9 × 0.1 = 0.081HP(H) = 0.9log₂(1/0.9)0.152HP(H) = 0.9log₂(1/0.9)0.152TP(T) = 0.1log₂(1/0.1)3.322++tails: 3.322 bitstotal = 3.626 bits = log₂(1/0.081)
For independent flips the probability of the sequence H, H, T is a product. Its logarithm splits into a sum, so the total surprise is the sum of the per-flip surprises: almost all of it comes from the single rare tails.

Entropy: expected surprise#

Now estimate the total surprise after 100 flips. We expect about 9090 heads and 1010 tails:

(0.9⋅100)⏟number of H⋅0.152⏟surprise of H+  (0.1⋅100)⋅3.322  ≈  46.9 bits.\begin{aligned} &\underbrace{(0.9\cdot 100)}_{\text{number of H}}\cdot \underbrace{0.152}_{\text{surprise of H}} \\ &\quad +\; (0.1\cdot 100)\cdot 3.322 \;\approx\; 46.9 \text{ bits}. \end{aligned}

Dividing by 100 gives the surprise per flip:

0.9⋅0.152+0.1⋅3.322≈0.469 bits.0.9 \cdot 0.152 + 0.1 \cdot 3.322 \approx 0.469 \text{ bits}.

This is the surprise we expect on average every time we flip the coin. Each probability multiplies its own surprise, which is exactly an expected value: if S=s(X)S = s(X) is the surprise of a random outcome X∼PX \sim P, then E[S]=∑xP(x) s(x)\mathbb E[S] = \sum_x P(x)\,s(x). The expected surprise is the entropy:

H(P)=∑xP(x)log⁡1P(x)=−∑xP(x)log⁡P(x),\begin{aligned} H(P) &= \sum_x P(x)\log\frac{1}{P(x)} \\ &= -\sum_x P(x)\log P(x), \end{aligned}

the quantity introduced by Claude Shannon in 1948 (Shannon, 1948).

Outcomes with P(x)=0P(x) = 0 never occur, so their terms are left out of the sum. Equivalently, we use the convention 0⋅log⁡10=00 \cdot \log\frac10 = 0, which is the limit of plog⁡1pp\log\frac1p as p→0p \to 0 (Cover and Thomas, 2006, §2.1). The rigged coin that always lands heads therefore has entropy 1⋅log⁡1=01 \cdot \log 1 = 0: it holds no surprise at all.

Back to the boards#

HA=12log⁡22+12log⁡22=1 bit,HB=910log⁡2109+110log⁡210≈0.469 bits.\begin{aligned} H_A &= \tfrac12\log_2 2 + \tfrac12\log_2 2 = 1 \text{ bit}, \\ H_B &= \tfrac{9}{10}\log_2\frac{10}{9} + \tfrac{1}{10}\log_2 10 \approx 0.469 \text{ bits}. \end{aligned}

Board B has exactly the biased coin’s distribution, so it has the same entropy. The balanced board is less predictable: higher entropy means more uncertainty. For two outcomes no distribution has more than 1 bit of entropy, and only the uniform one reaches it; this follows from Gibbs’ inequality in the next section.

Cross-entropy: surprise under a wrong belief#

Take a coin that our model believes to be fair, Q=(0.5, 0.5),{Q = (0.5,\,0.5)}, while in reality it is rigged, P=(0.99, 0.01).{P = (0.99,\,0.01)}. We observe ten heads in a row:

Probability of 10 headsSurprise (nats)
Model QQ0.510≈0.0010.5^{10} \approx 0.001ln⁡0.5−10≈6.93\ln 0.5^{-10} \approx 6.93
Reality PP0.9910≈0.900.99^{10} \approx 0.90ln⁡0.99−10≈0.10\ln 0.99^{-10} \approx 0.10
Figure

Ten heads: surprising under the model, ordinary in reality

Believed fair coin versus real rigged coinTop: the model Q puts probability 0.5 on heads and 0.5 on tails; the probability of ten heads under Q is 0.5 to the power 10, about 0.001, and the surprise is minus the natural log of that, about 6.93 nats. Bottom: reality P puts 0.99 on heads and 0.01 on tails; the probability of ten heads under P is 0.99 to the power 10, about 0.904, and the surprise is about 0.10 nats. A red note says the surprise is caused by believing in the wrong model.observed:HHHHHHHHHHModel Q (believed)0.5H0.5TQ(10 heads) = 0.5¹⁰ ≈ 0.001surprise = −ln 0.5¹⁰ ≈ 6.93 natsReality P0.99H0.01TP(10 heads) = 0.99¹⁰ ≈ 0.904surprise = −ln 0.99¹⁰ ≈ 0.10 natssurprise caused by believingin the wrong modelBelieved fair coin versus real rigged coinTop: the model Q puts probability 0.5 on heads and 0.5 on tails; the probability of ten heads under Q is 0.5 to the power 10, about 0.001, and the surprise is minus the natural log of that, about 6.93 nats. Bottom: reality P puts 0.99 on heads and 0.01 on tails; the probability of ten heads under P is 0.99 to the power 10, about 0.904, and the surprise is about 0.10 nats. A red note says the surprise is caused by believing in the wrong model.observed:HHHHHHHHHHModel Q (believed)0.5H0.5TQ(10 heads) = 0.5¹⁰ ≈ 0.001surprise = −ln 0.5¹⁰ ≈6.93 natsReality P0.99H0.01TP(10 heads) = 0.99¹⁰ ≈ 0.904surprise = −ln 0.99¹⁰ ≈0.10 natssurprise causedby believing inthe wrong model
We believe the coin is fair, but it is rigged. Ten heads in a row have probability about 0.001 under the belief (6.93 nats of surprise) and about 0.90 in reality (0.10 nats). The difference is surprise produced by the wrong model, not by the data. Natural logarithms.

The outcome was ordinary. Our surprise is caused by believing in the wrong model.

Cross-entropy H(P,Q)H(P, Q) is the average surprise when the real distribution is PP while we believe in QQ:

H(P,Q)=∑x∈XP(x)⏟how often xis observed  log⁡1Q(x)⏟how surprised weare to see itH(P, Q) = \sum_{x\in\mathcal X} \underbrace{P(x)}_{\substack{\text{how often } x \\ \text{is observed}}}\; \underbrace{\log\frac{1}{Q(x)}}_{\substack{\text{how surprised we} \\ \text{are to see it}}}
Figure

Reading the cross-entropy formula

Real distribution P, believed distribution Q and the cross-entropy formulaTwo bar charts over the same 18 discrete outcomes. Left or top: the real distribution P, high on the left and decaying with bumps. Right or below: the believed distribution Q, which rises, peaks in the middle, dips and has a second bump. The second outcome, x0, is marked: P(x0) = 0.12 is large, Q(x0) is about 9.0·10⁻⁵, almost zero. Below, the formula H(P, Q) equals the sum over x of P(x) times log of 1 over Q(x). An arrow labels P(x) as how often x is observed; another labels log 1 over Q(x) as how surprised we are to see it.P (real)xx₀P(x₀)Q (believed)xx₀Q(x₀) ≈ 0H(P, Q) =∑xP(x)log1Q(x)how often x is observedhow surprised we are to see itat x₀: P(x₀) = 0.12, Q(x₀) ≈ 9.0·10⁻⁵, so ln 1/Q(x₀) ≈ 9.3 natsReal distribution P, believed distribution Q and the cross-entropy formulaTwo bar charts over the same 18 discrete outcomes. Left or top: the real distribution P, high on the left and decaying with bumps. Right or below: the believed distribution Q, which rises, peaks in the middle, dips and has a second bump. The second outcome, x0, is marked: P(x0) = 0.12 is large, Q(x0) is about 9.0·10⁻⁵, almost zero. Below, the formula H(P, Q) equals the sum over x of P(x) times log of 1 over Q(x). An arrow labels P(x) as how often x is observed; another labels log 1 over Q(x) as how surprised we are to see it.P (real)xx₀P(x₀)Q (believed)xx₀Q(x₀) ≈ 0H(P, Q) =∑xP(x)log1Q(x)how often x is observedhow surprised we are to see itat x₀: ln 1/Q(x₀) ≈ 9.3 nats
Both panels are distributions over the same discrete outcomes x. Outcomes are drawn from the real P, but surprise is measured with the believed Q. The marked outcome x₀ is common under P (tall red bar, P(x₀) = 0.12) yet nearly impossible under Q (Q(x₀) ≈ 9.0·10⁻⁵, a bar too small to see), so each time it occurs it costs a large surprise, ln 1/Q(x₀) ≈ 9.3 nats. The shapes are illustrative.

No discrepancy. If Q=PQ = P, cross-entropy reduces to entropy: H(P,P)=H(P)H(P, P) = H(P).

Always (Gibbs’ inequality):

H(P,Q)  ≥  H(P),H(P, Q) \;\ge\; H(P),

with equality only when Q=PQ = P (Cover and Thomas, 2006, Theorem 2.6.3). Believing in a wrong distribution can only increase the average surprise. The proof takes one line once the difference H(P,Q)−H(P)H(P, Q) - H(P) has a name; it is given in the next section.

One consequence settles the question left open by the boards. Let QQ be uniform over the ∣X∣|\mathcal X| outcomes. Then log⁡1Q(x)=log⁡∣X∣\log\frac{1}{Q(x)} = \log|\mathcal X| for every xx, so H(P,Q)=log⁡∣X∣H(P, Q) = \log|\mathcal X|, and Gibbs’ inequality gives H(P)≤log⁡∣X∣H(P) \le \log|\mathcal X|, with equality only for the uniform PP (Cover and Thomas, 2006, Theorem 2.6.4). For two outcomes the bound is log⁡22=1\log_2 2 = 1 bit.

Asymmetry. In general H(P,Q)≠H(Q,P)H(P, Q) \ne H(Q, P). Keep PP as the rigged coin and QQ as the fair one, and use one flip and natural logarithms. The first argument is always the distribution that generates the outcomes. With a fair belief and a rigged reality, and then with a rigged belief and a fair reality,

H(P,Q)=0.99ln⁡2+0.01ln⁡2=ln⁡2≈0.69,H(Q,P)=0.5ln⁡10.99+0.5ln⁡10.01≈2.31.\begin{aligned} H(P, Q) &= 0.99\ln 2 + 0.01\ln 2 \\ &= \ln 2 \approx 0.69, \\ H(Q, P) &= 0.5\ln\frac{1}{0.99} + 0.5\ln\frac{1}{0.01} \\ &\approx 2.31 . \end{aligned}

In each sum the weights are the actual probabilities and the logarithms contain the believed ones. Believing that a fair coin is rigged is punished much harder: tails then occur half the time, and the rigged belief finds every one of them very surprising.

Kullback–Leibler divergence#

Cross-entropy mixes two sources of surprise: the surprise that the real distribution produces anyway, and the extra surprise caused by the wrong model. To isolate the second, subtract the entropy of the real distribution:

H(P,Q)−H(P)=∑xP(x)log⁡1Q(x)−∑xP(x)log⁡1P(x)=∑x∈XP(x)log⁡P(x)Q(x)=DKL(P ∥ Q).\begin{aligned} H(P, Q) - H(P) &= \sum_x P(x)\log\frac{1}{Q(x)} \\ &\quad - \sum_x P(x)\log\frac{1}{P(x)} \\ &= \sum_{x\in\mathcal X} P(x)\log\frac{P(x)}{Q(x)} \\ &= D_{\mathrm{KL}}(P \,\|\, Q). \end{aligned}

The KL divergence (Kullback and Leibler, 1951) is the extra surprise from using QQ as the model instead of PP. The subtraction needs both terms to be finite; the sum on the right is the general definition. Its terms follow the same conventions as before. A term with P(x)=0P(x) = 0 contributes 00. A term with P(x)>0P(x) > 0 but Q(x)=0Q(x) = 0 is P(x)log⁡P(x)0=+∞P(x)\log\frac{P(x)}{0} = +\infty, and then so is DKL(P ∥ Q)D_{\mathrm{KL}}(P\,\|\,Q). So KL is finite only when QQ gives positive probability to every outcome to which PP does, that is, when PP is absolutely continuous with respect to QQ (Cover and Thomas, 2006, §2.3). The next note shows what this condition means in training.

So KL is non-negative and equals zero only when Q=PQ = P. It is not symmetric and does not satisfy the triangle inequality (Cover and Thomas, 2006, §2.3; an example follows below), so it is a divergence rather than a distance. For the two coins, in nats and with four decimals so that the parts add up,

DKL(P ∥ Q)≈0.6931−0.0560=0.6371,DKL(Q ∥ P)≈2.3076−0.6931=1.6145.\begin{aligned} D_{\mathrm{KL}}(P\,\|\,Q) &\approx 0.6931 - 0.0560 = 0.6371, \\ D_{\mathrm{KL}}(Q\,\|\,P) &\approx 2.3076 - 0.6931 = 1.6145 . \end{aligned}
Figure

Cross-entropy = entropy + KL divergence

Cross-entropy split into entropy and KL divergenceTop bar: believe the coin is fair while it is rigged 0.99 to 0.01. Cross-entropy H(P, Q) = 0.6931 nats, made of entropy H(P) = 0.0560 nats and KL(P‖Q) = 0.6371 nats. Bottom bar: believe the coin is rigged while it is fair. Cross-entropy H(Q, P) = 2.3076 nats, made of entropy H(Q) = 0.6931 nats and KL(Q‖P) = 1.6145 nats.Believe fair, reality rigged:H(P, Q) = 0.6931H(P) = 0.0560KL(P‖Q) = 0.6371Believe rigged, reality fair:H(Q, P) = 2.3076H(Q) = 0.6931KL(Q‖P) = 1.614500.511.522.5nats per flipentropyKL: extra surprise from the wrong modelCross-entropy split into entropy and KL divergenceTop bar: believe the coin is fair while it is rigged 0.99 to 0.01. Cross-entropy H(P, Q) = 0.6931 nats, made of entropy H(P) = 0.0560 nats and KL(P‖Q) = 0.6371 nats. Bottom bar: believe the coin is rigged while it is fair. Cross-entropy H(Q, P) = 2.3076 nats, made of entropy H(Q) = 0.6931 nats and KL(Q‖P) = 1.6145 nats.Believe fair, reality rigged:H(P, Q) = 0.6931H(P) = 0.0560KL(P‖Q) = 0.6371Believe rigged, reality fair:H(Q, P) = 2.3076H(Q) = 0.6931KL(Q‖P) = 1.614500.511.522.5nats per flipentropyKL: extra surprise fromthe wrong model
Each bar is the average surprise per flip under a wrong belief. The red part is the surprise that the real coin produces by itself (its entropy); the amber part is the extra surprise caused by the wrong model, the KL divergence. Swapping belief and reality changes both parts. Values in nats, to four decimals so that the parts add up.

The two boards from the start of the note give every mark positive probability, so they have a finite KL divergence in both directions, and its value depends on the direction:

DKL(A ∥ B)=12log⁡21/29/10+12log⁡21/21/10≈0.737 bits,DKL(B ∥ A)=910log⁡29/101/2+110log⁡21/101/2≈0.531 bits.\begin{aligned} D_{\mathrm{KL}}(A\,\|\,B) &= \tfrac12\log_2\frac{1/2}{9/10} + \tfrac12\log_2\frac{1/2}{1/10} \\ &\approx 0.737 \text{ bits},\\ D_{\mathrm{KL}}(B\,\|\,A) &= \tfrac{9}{10}\log_2\frac{9/10}{1/2} + \tfrac{1}{10}\log_2\frac{1/10}{1/2} \\ &\approx 0.531 \text{ bits}. \end{aligned}

As a check, H(B,A)=HB+DKL(B ∥ A)=0.469+0.531=1H(B, A) = H_B + D_{\mathrm{KL}}(B\,\|\,A) = 0.469 + 0.531 = 1 bit: measuring surprise with the uniform board A costs exactly one bit per draw, whatever the true board is.

Figure

The two boards compared with KL

KL between the balanced and the skewed boardTwo bar charts with O in blue and X in red. Board A has bars of height one half for O and for X, entropy 1 bit. Board B has bars of 9/10 for O and 1/10 for X, entropy 0.469 bits. A curved arrow from A to B is labelled KL(A‖B) = 0.737 bits; a curved arrow back from B to A is labelled KL(B‖A) = 0.531 bits.Board A1/2O1/2XH = 1 bitBoard B9/10O1/10XH = 0.469 bitsKL(A‖B) = 0.737KL(B‖A) = 0.531bits; not symmetricKL between the balanced and the skewed boardTwo bar charts with O in blue and X in red. Board A has bars of height one half for O and for X, entropy 1 bit. Board B has bars of 9/10 for O and 1/10 for X, entropy 0.469 bits. A curved arrow from A to B is labelled KL(A‖B) = 0.737 bits; a curved arrow back from B to A is labelled KL(B‖A) = 0.531 bits.Board A1/2O1/2XH = 1 bitBoard B9/10O1/10XH = 0.469 bitsKL(A‖B) = 0.737KL(B‖A) = 0.531bits; not symmetric
The two boards from the start of the note as distributions over {O, X}, with noughts in blue and crosses in red as before. Entropies are 1 bit and 0.469 bits; the KL divergence between them is 0.737 bits one way and 0.531 bits the other. Both boards give every outcome positive probability, so both directions are finite. Each arrow runs from the distribution treated as the truth (the first argument) to the one treated as the model.

The same distributions show that KL breaks the triangle inequality. Identify O with heads and X with tails, and compare board A with the rigged coin P=(0.99,0.01)P = (0.99, 0.01), once directly and once through board B. Directly, DKL(A ∥ P)≈2.329D_{\mathrm{KL}}(A\,\|\,P) \approx 2.329 bits. Through B, DKL(A ∥ B)+DKL(B ∥ P)≈0.737+0.208=0.945D_{\mathrm{KL}}(A\,\|\,B) + D_{\mathrm{KL}}(B\,\|\,P) \approx 0.737 + 0.208 = 0.945 bits, which is less.

Why cross-entropy is the loss we minimize#

For the true data distribution PP and a model QθQ_\theta:

DKL(P ∥ Qθ)⏟minimize w.r.t. θ=H(P,Qθ)⏟minimize w.r.t. θ−H(P)⏟constant: entropyof the data\underbrace{D_{\mathrm{KL}}(P \,\|\, Q_\theta)}_{\text{minimize w.r.t. } \theta} = \underbrace{H(P, Q_\theta)}_{\text{minimize w.r.t. } \theta} - \underbrace{H(P)}_{\substack{\text{constant: entropy} \\ \text{of the data}}}
  • Changing the model’s parameters cannot change the entropy of the data, so H(P)H(P) is a constant in the optimization.
  • Nor do we need its value. For high-dimensional data such as images, estimating H(P)H(P) from samples is itself a hard problem.
  • So minimizing KL with respect to θ\theta and minimizing cross-entropy have the same solution, and cross-entropy is the part we can estimate from samples. This is why classifiers and language models are trained with a cross-entropy loss. There the same argument is applied to the conditional distribution of the label (or of the next token) given the input. The target P(⋅∣x)P(\cdot \mid x) is then the true conditional law of the label, which we never see directly. Each training example supplies one observed label, a one-hot vector, and the average negative log-likelihood of the observed labels is a sample estimate of the conditional cross-entropy Ex H(P(⋅∣x),Q(⋅∣x))\mathbb E_x\, H\big(P(\cdot \mid x), Q(\cdot \mid x)\big). Soft targets, such as label smoothing or a teacher model’s probabilities, replace the one-hot vector by another estimate of P(⋅∣x)P(\cdot \mid x).

Given samples x1,…,xNx_1, \dots, x_N from PP, the cross-entropy is estimated by the average negative log-likelihood,

H(P,Qθ)=Ex∼P[−log⁡Qθ(x)]≈−1N∑i=1Nlog⁡Qθ(xi).\begin{aligned} H(P, Q_\theta) &= \mathbb E_{x\sim P}\big[-\log Q_\theta(x)\big] \\ &\approx -\frac1N\sum_{i=1}^N \log Q_\theta(x_i). \end{aligned}

Minimizing it is maximum-likelihood estimation. For discrete outcomes the average negative log-likelihood is exactly the cross-entropy H(P^,Qθ)H(\hat P, Q_\theta) between the empirical distribution P^\hat P of the samples (probability 1/N1/N on each xix_i) and the model, so maximum likelihood minimizes DKL(P^ ∥ Qθ)D_{\mathrm{KL}}(\hat P\,\|\,Q_\theta) (Goodfellow, Bengio and Courville, 2016, §5.5). As NN grows, the average converges to H(P,Qθ)H(P, Q_\theta) by the law of large numbers, and that differs from DKL(P ∥ Qθ)D_{\mathrm{KL}}(P\,\|\,Q_\theta) only by the constant H(P)H(P). So “minimize DKL(P ∥ Qθ)D_{\mathrm{KL}}(P\,\|\,Q_\theta)”, “minimize H(P,Qθ)H(P, Q_\theta)” and “maximize likelihood” are three names for the same training objective: exactly for the empirical distribution, and in the limit of many samples for PP itself.

Later families of generative models differ mostly in how they deal with the fact that log⁡Qθ(x)\log Q_\theta(x) is hard to compute: VAEs bound it, normalizing flows compute it exactly, GANs avoid it altogether, and diffusion models bound it again, with a fixed noising process in place of a learned encoder.

Jensen–Shannon divergence#

The Jensen–Shannon divergence (Lin, 1991) uses the same building block, but it is symmetric and bounded. It compares both distributions with their mixture M=12(P+Q)M = \tfrac12(P + Q):

DJS(P ∥ Q)=12DKL(P ∥ M)+12DKL(Q ∥ M).\begin{aligned} D_{\mathrm{JS}}(P \,\|\, Q) &= \tfrac12 D_{\mathrm{KL}}(P \,\|\, M) \\ &\quad + \tfrac12 D_{\mathrm{KL}}(Q \,\|\, M). \end{aligned}

Because M(x)>0M(x) > 0 wherever P(x)>0P(x) > 0 or Q(x)>0Q(x) > 0, both terms are always finite. Both are non-negative, so DJS≥0D_{\mathrm{JS}} \ge 0, with equality only when P=M=QP = M = Q. For the upper bound, note that P(x)≤P(x)+Q(x)=2M(x)P(x) \le P(x) + Q(x) = 2M(x). Every term of DKL(P ∥ M)D_{\mathrm{KL}}(P\,\|\,M) therefore has log⁡P(x)M(x)≤log⁡2\log\frac{P(x)}{M(x)} \le \log 2, so DKL(P ∥ M)≤log⁡2D_{\mathrm{KL}}(P\,\|\,M) \le \log 2, with equality only if P(x)=2M(x)P(x) = 2M(x), that is Q(x)=0Q(x) = 0, wherever P(x)>0P(x) > 0. The same holds for the second term. Hence

0  ≤  DJS(P ∥ Q)  ≤  ln⁡2 nats=1 bit,0 \;\le\; D_{\mathrm{JS}}(P \,\|\, Q) \;\le\; \ln 2 \text{ nats} = 1 \text{ bit},

and the maximum is reached exactly when PP and QQ do not overlap. For the two coins, DJS≈0.193D_{\mathrm{JS}} \approx 0.193 nats (0.2790.279 bits).

JS will matter twice. In the next note it is one of the losses compared on a two-mode target. In the GAN note, the original GAN objective with an optimal discriminator turns out to equal 2 DJS(P ∥ Q)−2ln⁡22\,D_{\mathrm{JS}}(P\,\|\,Q) - 2\ln 2, with PP the data distribution and QQ the generator’s (Goodfellow et al., 2014). The saturation of JS at ln⁡2\ln 2 for non-overlapping distributions then explains why GAN training can stall (Arjovsky and Bottou, 2017).

Next#

We now have a number for how far a model QQ is from the data PP, and we know that minimizing DKL(P ∥ Qθ)D_{\mathrm{KL}}(P\,\|\,Q_\theta) is maximum likelihood. The next note puts this to work on the Gaussian model from the previous note. It trains a Gaussian QQ by minimizing a sample estimate of the KL, asks what the formula assumes (common support, direction), and compares what forward KL, reverse KL and JS do when one Gaussian must fit two modes. Its Notebook section describes the code, where KL and JS are estimated from samples.

References#