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.
The previous note ended with a concrete task: fit the distribution we are training, Q, to a target distribution P. To do that we need a number that measures how far Q is from P. The standard first choice is the Kullback–Leibler divergence:
DKL(P∥Q)=x∈X∑P(x)logQ(x)P(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∈X∑P(x)logP(x),H(P,Q)=−x∈X∑P(x)logQ(x).
Notation.P is the real (data, target) distribution and Q the believed (model) distribution. H(P) is the entropy of X∼P, sometimes also written H(X). For continuous distributions, lowercase p and q denote densities and sums become integrals; what changes for densities is noted at the end of the KL section. log2 gives bits and ln gives nats; a plain log means either, as long as one base is used throughout.
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?
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)=21,P(X)=21,B:P(O)=109,P(X)=101.
The cross is clearly more surprising on board B, so surprise must grow as the probability falls.
First attempt: 1/p. To compare 21 and 101, flip them: 1/P(X) is 2 on board A and 10 on board B. This ranks the boards correctly, and as a function of p it is a decreasing curve.
Problem. Take a rigged coin that always lands heads: HHHHHHHHHH. Its two outcomes give
P(H)=1P(T)=0:P(H)1=11=1,:P(T)1=01.
Getting heads should not surprise us at all, so the first value should be 0. The second is not even a number.
The undefined case is harmless: an outcome with probability 0 never happens, so its surprise is never needed. This gives the definition of surprise, also called self-information:
s(x)=logP(x)1=−logP(x).
It equals 0 when P(x)=1 and grows without bound as P(x)→0.
Figure
Surprise must vanish for a certain outcome
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 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) for all p,q∈(0,1] and put g(t)=s(e−t) for t≥0. Then g(t+u)=g(t)+g(u), and the only continuous solutions of this equation are linear, g(t)=ct. Hence s(p)=clogp1. Requiring rare outcomes to be surprising makes c>0, and the choice of c 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
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.
Now estimate the total surprise after 100 flips. We expect about 90 heads and 10 tails:
number of H(0.9⋅100)⋅surprise of H0.152+(0.1⋅100)⋅3.322≈46.9 bits.
Dividing by 100 gives the surprise per flip:
0.9⋅0.152+0.1⋅3.322≈0.469 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) is the surprise of a random outcome X∼P, then E[S]=∑xP(x)s(x). The expected surprise is the entropy:
H(P)=x∑P(x)logP(x)1=−x∑P(x)logP(x),
the quantity introduced by Claude Shannon in 1948 (Shannon, 1948).
Outcomes with P(x)=0 never occur, so their terms are left out of the sum. Equivalently, we use the convention 0⋅log01=0, which is the limit of plogp1 as p→0 (Cover and Thomas, 2006, §2.1). The rigged coin that always lands heads therefore has entropy 1⋅log1=0: it holds no surprise at all.
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.
Take a coin that our model believes to be fair, Q=(0.5,0.5), while in reality it is rigged, P=(0.99,0.01). We observe ten heads in a row:
Probability of 10 heads
Surprise (nats)
Model Q
0.510≈0.001
ln0.5−10≈6.93
Reality P
0.9910≈0.90
ln0.99−10≈0.10
Figure
Ten heads: surprising under the model, ordinary in reality
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-entropyH(P,Q) is the average surprise when the real distribution is P while we believe in Q:
H(P,Q)=x∈X∑how often xis observedP(x)how surprised weare to see itlogQ(x)1Figure
Reading the cross-entropy formula
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=P, cross-entropy reduces to entropy: H(P,P)=H(P).
Always (Gibbs’ inequality):
H(P,Q)≥H(P),
with equality only when Q=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) has a name; it is given in the next section.
One consequence settles the question left open by the boards. Let Q be uniform over the ∣X∣ outcomes. Then logQ(x)1=log∣X∣ for every x, so H(P,Q)=log∣X∣, and Gibbs’ inequality gives H(P)≤log∣X∣, with equality only for the uniform P (Cover and Thomas, 2006, Theorem 2.6.4). For two outcomes the bound is log22=1 bit.
Asymmetry. In general H(P,Q)=H(Q,P). Keep P as the rigged coin and Q 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,
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.
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:
The KL divergence (Kullback and Leibler, 1951) is the extra surprise from using Q as the model instead of P. 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)=0 contributes 0. A term with P(x)>0 but Q(x)=0 is P(x)log0P(x)=+∞, and then so is DKL(P∥Q). So KL is finite only when Q gives positive probability to every outcome to which P does, that is, when P is absolutely continuous with respect to Q (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=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,
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:
As a check, H(B,A)=HB+DKL(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
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), once directly and once through board B. Directly, DKL(A∥P)≈2.329 bits. Through B, DKL(A∥B)+DKL(B∥P)≈0.737+0.208=0.945 bits, which is less.
minimize w.r.t. θDKL(P∥Qθ)=minimize w.r.t. θH(P,Qθ)−constant: entropyof the dataH(P)
Changing the model’s parameters cannot change the entropy of the data, so H(P) is a constant in the optimization.
Nor do we need its value. For high-dimensional data such as images, estimating H(P) from samples is itself a hard problem.
So minimizing KL with respect to θ 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) 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 ExH(P(⋅∣x),Q(⋅∣x)). Soft targets, such as label smoothing or a teacher model’s probabilities, replace the one-hot vector by another estimate of P(⋅∣x).
Given samples x1,…,xN from P, the cross-entropy is estimated by the average negative log-likelihood,
Minimizing it is maximum-likelihood estimation. For discrete outcomes the average negative log-likelihood is exactly the cross-entropy H(P^,Qθ) between the empirical distribution P^ of the samples (probability 1/N on each xi) and the model, so maximum likelihood minimizes DKL(P^∥Qθ) (Goodfellow, Bengio and Courville, 2016, §5.5). As N grows, the average converges to H(P,Qθ) by the law of large numbers, and that differs from DKL(P∥Qθ) only by the constant H(P). So “minimize DKL(P∥Qθ)”, “minimize H(P,Qθ)” and “maximize likelihood” are three names for the same training objective: exactly for the empirical distribution, and in the limit of many samples for P itself.
Later families of generative models differ mostly in how they deal with the fact that logQθ(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.
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=21(P+Q):
DJS(P∥Q)=21DKL(P∥M)+21DKL(Q∥M).
Because M(x)>0 wherever P(x)>0 or Q(x)>0, both terms are always finite. Both are non-negative, so DJS≥0, with equality only when P=M=Q. For the upper bound, note that P(x)≤P(x)+Q(x)=2M(x). Every term of DKL(P∥M) therefore has logM(x)P(x)≤log2, so DKL(P∥M)≤log2, with equality only if P(x)=2M(x), that is Q(x)=0, wherever P(x)>0. The same holds for the second term. Hence
0≤DJS(P∥Q)≤ln2 nats=1 bit,
and the maximum is reached exactly when P and Q do not overlap. For the two coins, DJS≈0.193 nats (0.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 2DJS(P∥Q)−2ln2, with P the data distribution and Q the generator’s (Goodfellow et al., 2014). The saturation of JS at ln2 for non-overlapping distributions then explains why GAN training can stall (Arjovsky and Bottou, 2017).
We now have a number for how far a model Q is from the data P, and we know that minimizing DKL(P∥Qθ) is maximum likelihood. The next note puts this to work on the Gaussian model from the previous note. It trains a Gaussian Q 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.
C. E. Shannon. A Mathematical Theory of Communication. Bell System Technical Journal, 27(3), 379–423 and 27(4), 623–656, 1948. Theorem 2: uniqueness of the entropy formula.
T. M. Cover, J. A. Thomas. Elements of Information Theory, 2nd ed. Wiley, 2006. §2.1 (entropy, the convention 0log0=0), §2.3 (relative entropy), Theorems 2.6.3 (information inequality) and 2.6.4 (maximum entropy); §8.1 and §8.5–8.6 (differential entropy and relative entropy for densities).
I. Goodfellow, Y. Bengio, A. Courville. Deep Learning. MIT Press, 2016. §3.13 (information theory) and §5.5 (maximum likelihood and cross-entropy).
I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, Y. Bengio. Generative adversarial nets. NeurIPS, 2014.