Course contents 03 / 34

03 / 34 · 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 bounded, symmetric Jensen–Shannon divergence.

Prerequisites

Probability · Expectation

On this page 7

A model believes a coin is fair. We flip it ten times and get ten heads. The model is surprised; someone who knew the coin was rigged would not be. How wrong is the model, as a single number we can minimize?

The course’s answer is the Kullback–Leibler divergence, and the trainable Gaussian of the previous note will be fitted with it:

DKL(P ∥ Q)=∑xP(x) log⁡P(x)Q(x),D_{\mathrm{KL}}(P \,\|\, Q) = \sum_{x} P(x)\,\log\frac{P(x)}{Q(x)} ,

where PP is the real distribution that produces the outcomes and QQ the distribution the model believes in. Each piece of the formula has a meaning of its own, and the first piece is surprise.

Surprise#

The route below follows Josh Starmer’s StatQuest (Starmer, 2021); the formal treatment is chapter 2 of Cover and Thomas (2006). 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 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.

On board A a cross has probability 12\tfrac12; on board B, 110\tfrac1{10}. The cross is five times rarer on B, and seeing it there should surprise us more: surprise must grow as the probability falls. A first attempt is 1/P(x)1/P(x): it gives 2 on board A and 10 on board B, which ranks them correctly.

It fails on a certain outcome. A rigged coin that always lands heads has P(H)=1P(H) = 1, and heads should then carry no surprise at all, yet 1/P(H)=11/P(H) = 1. Taking the logarithm moves that point to zero. The surprise, or self-information, of an outcome is

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

It is 00 when P(x)=1P(x) = 1 and grows without bound as P(x)→0P(x) \to 0. An outcome of probability zero never happens, so its infinite surprise is never needed.

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.

The base of the logarithm only sets the unit. Base 2 gives bits, in which one fair binary choice carries exactly 1 bit; base ee gives nats, and 1 bit=ln⁡2≈0.6931 \text{ bit} = \ln 2 \approx 0.693 nats. The coin and board examples below use bits, the cross-entropy examples nats.

For a biased coin with P(H)=0.9P(H) = 0.9 and P(T)=0.1P(T) = 0.1, heads carries log⁡210.9≈0.152\log_2 \frac{1}{0.9} \approx 0.152 bits and tails log⁡210.1≈3.322\log_2 \frac{1}{0.1} \approx 3.322 bits. The rare outcome carries the most surprise.

Surprise is additive#

Flip the coin three times and observe H H T. The flips are independent, so the probability of the sequence is a product, and its surprise is a sum:

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}
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.

No other continuous function turns products into sums. If s(pq)=s(p)+s(q)s(pq) = s(p) + s(q) for all p,q∈(0,1]p, q \in (0, 1], then g(t)=s(e−t)g(t) = s(e^{-t}) satisfies g(t+u)=g(t)+g(u)g(t + u) = g(t) + g(u) for all t,u≥0t, u \ge 0. Adding tt to itself nn times gives g(nt)=n g(t)g(nt) = n\,g(t); putting t=1/nt = 1/n gives g(1/n)=g(1)/ng(1/n) = g(1)/n, and so g(m/n)=mn g(1)g(m/n) = \tfrac mn\, g(1) for every positive rational. A continuous gg is fixed by its values on the rationals, so g(t)=ctg(t) = ct with c=g(1)c = g(1). Hence s(p)=clog⁡1ps(p) = c\log\frac1p, with c>0c > 0 so that rare outcomes are surprising; choosing cc is choosing the base. Shannon proved the matching uniqueness result for entropy itself (Shannon, 1948, Theorem 2).

Entropy: expected surprise#

Over 100 flips of the biased coin we expect about 90 heads and 10 tails, for a total surprise of about 90⋅0.152+10⋅3.322≈46.990 \cdot 0.152 + 10 \cdot 3.322 \approx 46.9 bits. Per flip that is

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}.

Each probability multiplies its own surprise: this is the expected value of the surprise s(X)s(X) of a random outcome X∼PX \sim P. The expected surprise is the entropy (Shannon, 1948):

H(P)=∑xP(x)log⁡1P(x)=−∑xP(x)log⁡P(x).H(P) = \sum_x P(x)\log\frac{1}{P(x)} = -\sum_x P(x)\log P(x).

Outcomes with P(x)=0P(x) = 0 are left out of the sum, which is the convention 0log⁡10=00 \log \frac10 = 0, the limit of plog⁡1pp\log\frac1p as p→0p \to 0: with p=e−tp = e^{-t} the product is t e−tt\,e^{-t}, which tends to 0 as t→∞t \to \infty (Cover and Thomas, 2006, §2.1). The coin that always lands heads has entropy 00.

For 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 the biased coin’s distribution and so its entropy. The balanced board A is less predictable, and higher entropy means more uncertainty. For two outcomes no distribution exceeds 1 bit, and only the uniform one reaches it; the next section proves this.

To compute an entropy we must know the real distribution PP. When we fit a generative model to data, we never do.

Cross-entropy: surprise under a wrong belief#

Back to the opening coin. The model believes it is 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). Ten heads in a row have very different probabilities under the two:

Probability of 10 headsSurprise (nats)
Model QQ0.510≈0.0010.5^{10} \approx 0.0016.936.93
Reality PP0.9910≈0.900.99^{10} \approx 0.900.100.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; the surprise comes from the wrong belief. The cross-entropy H(P,Q)H(P, Q) is the average surprise when outcomes come from PP while we measure surprise with QQ:

H(P,Q)=∑xP(x) log⁡1Q(x).H(P, Q) = \sum_{x} P(x)\,\log\frac{1}{Q(x)} .

The weights say how often xx happens, and the logarithms say how surprised the believer is 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
Two distributions over the same discrete outcomes x: outcomes come from the real P, surprise is measured with the believed Q. The marked x₀ is common under P (P(x₀) = 0.12) yet nearly impossible under Q (Q(x₀) ≈ 9.0·10⁻⁵), so each occurrence costs ln 1/Q(x₀) ≈ 9.3 nats. The shapes are illustrative.

If Q=PQ = P, cross-entropy is entropy: H(P,P)=H(P)H(P, P) = H(P). Otherwise it is larger. Gibbs’ inequality states

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 raise the average surprise. The proof takes one line once the difference has a name, in the next section.

Gibbs’ inequality bounds entropy from above. Let QQ be uniform over ∣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 therefore 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). The Mathematics course reaches the same result with Lagrange multipliers.

Cross-entropy is not symmetric, and the first argument is always the distribution that generates the outcomes. For one flip, in nats:

H(P,Q)=0.99ln⁡2+0.01ln⁡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 \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}

Believing that a fair coin is rigged is punished harder. Tails then come half the time, and the rigged belief finds every one of them very surprising.

Kullback–Leibler divergence#

Cross-entropy mixes two sources of surprise: what the real distribution produces anyway, and the extra caused by the wrong model. Subtracting the entropy isolates the second:

H(P,Q)−H(P)=∑xP(x)log⁡1Q(x)−∑xP(x)log⁡1P(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} 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 sum on the right is the general definition, and the subtraction holds when both terms are finite. A term with P(x)=0P(x) = 0 contributes 00. A term with P(x)>0P(x) > 0 and Q(x)=0Q(x) = 0 is +∞+\infty, and so is the divergence. 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 does in training.

A second reading comes from comparing hypotheses. Bayes’ rule for two hypotheses PP and QQ, divided one by the other, cancels the evidence Pr⁡(x)\Pr(x); taking logarithms turns the product into a sum:

log⁡Pr⁡(P∣x)Pr⁡(Q∣x)=log⁡Pr⁡(P) p(x)Pr⁡(Q) q(x)=log⁡Pr⁡(P)Pr⁡(Q)+log⁡p(x)q(x).\begin{aligned} \log\frac{\Pr(P \mid x)}{\Pr(Q \mid x)} &= \log\frac{\Pr(P)\, p(x)}{\Pr(Q)\, q(x)} \\ &= \log\frac{\Pr(P)}{\Pr(Q)} + \log\frac{p(x)}{q(x)} . \end{aligned}

One observation xx adds log⁡p(x)q(x)\log\frac{p(x)}{q(x)} to the log-odds of PP against QQ: the weight of evidence it carries for PP. DKL(P ∥ Q)D_{\mathrm{KL}}(P\,\|\,Q) is the expected weight of evidence per observation when PP is true. Because it is never negative, data push belief towards the true hypothesis on average (Murphy, 2023, §5.1.3).

So KL is non-negative and zero only when Q=PQ = P. It is neither symmetric nor does it satisfy the triangle inequality (Cover and Thomas, 2006, §2.3), so it is called a divergence and not a distance. For the two coins, in nats 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 real coin's own surprise, its entropy; the amber part is the extra caused by the wrong model, the KL divergence. Swapping belief and reality changes both parts. Nats, to four decimals so that the parts add up.

The two boards give every mark positive probability, so their divergence is finite 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 costs exactly one bit per draw, whatever the true board.

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 as distributions over {O, X}, noughts in blue and crosses in red. Entropies are 1 bit and 0.469 bits. KL is 0.737 bits one way and 0.531 bits the other, both finite because every outcome has positive probability. Each arrow runs from the distribution treated as the truth to the model.

The same distributions break the triangle inequality. Read O as heads and X as tails and compare board A with the rigged coin P=(0.99,0.01)P = (0.99, 0.01). Directly, DKL(A ∥ P)≈2.329D_{\mathrm{KL}}(A\,\|\,P) \approx 2.329 bits. Through board 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, the decomposition reads

DKL(P ∥ Qθ)=H(P,Qθ)−H(P).D_{\mathrm{KL}}(P \,\|\, Q_\theta) = H(P, Q_\theta) - H(P).

The entropy of the data does not depend on θ\theta, so minimizing KL and minimizing cross-entropy have the same solution. We never need the value of H(P)H(P), which for images would be a hard estimation problem of its own. Cross-entropy is the part we can estimate from samples x1,…,xN∼Px_1, \dots, x_N \sim P, 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 is exactly the cross-entropy H(P^,Qθ)H(\hat P, Q_\theta) between the empirical distribution P^\hat P, which puts 1/N1/N on each sample, and the model: P^(x)\hat P(x) is the share of samples equal to xx, so ∑xP^(x)(−log⁡Qθ(x))\sum_x \hat P(x)\big(-\log Q_\theta(x)\big) adds −log⁡Qθ(xi)/N-\log Q_\theta(x_i)/N once for each sample. Hence 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. Minimizing forward KL, minimizing cross-entropy and maximizing likelihood are one objective under three names: exactly for the empirical distribution, and in the limit for PP itself (Isachenko, lecture 1). The standing of maximum likelihood rests on asymptotic results, and they need conditions. The model family must contain PP and be identifiable, its support must not depend on θ\theta, the log-likelihood must be smooth and the true parameter must lie inside the parameter set. Then, with the model fixed and NN growing, the estimate converges to the true θ\theta and, for a single parameter, is approximately normal with variance 1/(NI(θ))1/(N I(\theta)), where II is the Fisher information. That is the Cramér–Rao bound, below which no unbiased estimator goes, so the estimate is asymptotically efficient. The Probability course states these results in Fisher information. If no member of the family equals PP, the estimate converges instead to the member closest to PP in forward KL (when maximum likelihood goes wrong). With few samples per parameter none of this is promised, and that is where priors enter (BMML lecture notes, 2026, lecture 1).

The same argument explains the cross-entropy loss of classifiers and language models, applied to the conditional distribution of the label or next token given the input. Each training example supplies one observed label, a one-hot vector, and the average negative log-likelihood estimates 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).

The direction matters. Forward KL averages over the data, so it heavily penalizes a model that gives low probability to points the data produces, and a model that gives zero probability to one of them pays an infinite loss (Stanford CS236 notes). Generative models differ mostly in how they deal with log⁡Qθ(x)\log Q_\theta(x) being hard to compute: VAEs bound it, normalizing flows compute it exactly, GANs avoid it, and diffusion models bound it again.

Jensen–Shannon divergence#

The Jensen–Shannon divergence (Lin, 1991) builds a symmetric and bounded quantity from the same pieces. It compares both distributions with their mixture M=12(P+Q)M = \tfrac12(P + Q):

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

The mixture is positive wherever PP or QQ is, so both terms are always finite, and both are non-negative, with DJS=0D_{\mathrm{JS}} = 0 only when P=QP = Q. For the upper bound, P(x)≤P(x)+Q(x)=2M(x)P(x) \le P(x) + Q(x) = 2M(x), so every log ratio in DKL(P ∥ M)D_{\mathrm{KL}}(P\,\|\,M) is at most log⁡2\log 2, and equality needs 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},

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

Its square root DJS\sqrt{D_{\mathrm{JS}}} is a true metric on probability distributions: symmetric, zero only for P=QP = Q, and with the triangle inequality (Endres and Schindelin, 2003; HSE, lecture 1). The proof is beyond this course; the local picture shows why a square root is needed. For Q=P+δQ = P + \delta with a small δ\delta, a second-order expansion of the logarithm gives DJS≈∑xδ(x)2/(8P(x))D_{\mathrm{JS}} \approx \sum_x \delta(x)^2 / (8P(x)), a squared length, like the square of a Euclidean distance. A squared distance breaks the triangle inequality (for points 0, 1 and 2 on a line, 4>1+14 > 1 + 1), and its root restores it.

JS matters twice later. 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 equals 2 DJS(P ∥ Q)−2ln⁡22\,D_{\mathrm{JS}}(P\,\|\,Q) - 2\ln 2, with PP the data and QQ the generator (Goodfellow et al., 2014). Its saturation at ln⁡2\ln 2 for non-overlapping distributions then explains why GAN training can stall (where it breaks; Arjovsky and Bottou, 2017).

KL and JS are two members of a larger family. Every f-divergence ∫q f(p/q) dx\int q\, f(p/q)\,dx with a convex ff and f(1)=0f(1) = 0 compares densities through their ratio (HSE, lecture 1). Substituting shows the special cases: f(u)=uln⁡uf(u) = u\ln u gives ∫pln⁡pq dx=DKL(P ∥ Q)\int p \ln\frac pq\,dx = D_{\mathrm{KL}}(P\,\|\,Q), f(u)=−ln⁡uf(u) = -\ln u gives the reverse KL, and f(u)=12∣u−1∣f(u) = \tfrac12|u - 1| gives the total variation distance 12∫∣p−q∣ dx\tfrac12\int |p - q|\,dx. The f-GAN lists the ff of JS and of other divergences and trains with any of them. The Wasserstein GAN leaves the family and measures how far mass has to move, which stays informative when the supports do not overlap.

What you should remember#

  • Surprise −log⁡P(x)-\log P(x); entropy H(P)H(P) is its average under PP.
  • Cross-entropy H(P,Q)H(P, Q) averages under PP the surprise measured with QQ; H(P,Q)≥H(P)H(P, Q) \ge H(P).
  • DKL(P ∥ Q)=H(P,Q)−H(P)≥0D_{\mathrm{KL}}(P\,\|\,Q) = H(P, Q) - H(P) \ge 0; infinite if QQ misses mass of PP; not symmetric.
  • Maximum likelihood = minimum cross-entropy = minimum forward KL from the data to the model.
  • JS compares both with their mixture: symmetric, at most ln⁡2\ln 2, and flat once the supports separate.

Code#

The numbers of this note with SciPy, whose entropy(p) returns H(P)H(P) and entropy(p, q) returns DKL(P ∥ Q)D_{\mathrm{KL}}(P\,\|\,Q), in nats unless a base is given.

import numpy as np
from scipy.stats import entropy             # entropy(p) = H(P); entropy(p, q) = KL(P || Q)

P, Q = np.array([0.99, 0.01]), np.array([0.5, 0.5])    # rigged coin, fair belief
A, B = np.array([0.5, 0.5]), np.array([0.9, 0.1])      # the two boards

cross = lambda p, q: -(p * np.log(q)).sum()            # H(P, Q) in nats
print(round(cross(P, Q), 4), round(entropy(P) + entropy(P, Q), 4))   # H(P,Q) = H(P) + KL
print(round(entropy(P, Q), 4), round(entropy(Q, P), 4))              # KL is not symmetric
print(round(entropy(B, base=2), 3), round(entropy(A, B, base=2), 3), round(entropy(B, A, base=2), 3))

M = (P + Q) / 2
js = 0.5 * entropy(P, M) + 0.5 * entropy(Q, M)
print(round(js, 3), round(js / np.log(2), 3))                         # nats, bits
print(entropy([1.0, 0.0]), entropy(P, [1.0, 0.0]))                   # 0 log 0 = 0; Q misses mass: inf
0.6931 0.6931
0.6371 1.6145
0.469 0.737 0.531
0.193 0.279
0.0 inf

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 trains the Gaussian of the previous note with a sample estimate of KL, asks what the formula assumes, and compares what forward KL, reverse KL and JS do when one Gaussian must fit two modes.

References#