Contents
04Cross-entropy: the newcomer’s surprise
4.1Wrong expectations
A Cupertino native moves to Miami in July but keeps expecting Cupertino’s weather: rain with probability q=0.0032. Reality is Miami’s p=0.558. Every rainy day surprises him with \log_2(1/0.0032)=8.28 bits, and it rains more than half the time. His average surprise weights his surprises by how often things really happen:
Definition 2 (Cross-entropy). The cross-entropy of a model q on data from p is
Read it as “how often it really happens” times “your surprise when it does” (Murphy, 2022, §6.1.2). We write H_{\mathrm{ce}}(p,q) rather than H(p,q), which also denotes the joint entropy.
Worked example 3 (The newcomer in Miami). H_{\mathrm{ce}}(p,q)=0.558\times8.28+0.442\times0.0047=4.62 bits per day, against the locals’ H(p)=0.99. In one real-looking July with 17 rainy days, his average surprise is 4.54 bits per day and the locals’ 0.994: the sample average is close to the expectation. The other way round, a Miami native in Cupertino, still expecting rain 56\% of the time, averages H_{\mathrm{ce}}=1.18 bits per day, against the locals’ 0.03.
Figure 3 plots the newcomer’s cross-entropy against his expected chance of rain q. The curve is lowest, and touches the entropy, exactly at q=p. Expecting too little rain or too much both cost extra, and the cost rises without bound as q approaches 0 or 1.
4.2The coding view
If a weather service designs its code for q, giving each outcome a codeword of about \log_2(1/q(x)) bits, but the weather actually follows p, its messages average H_{\mathrm{ce}}(p,q) bits per day instead of H(p) (Cover and Thomas, 2006, ch. 5). The newcomer’s code would spend 8.28 bits on every rainy Miami day.
4.3Cross-entropy as a loss
A model is the newcomer: its predicted probabilities are its expectations q_\theta, and the training data are reality. For one training example with true outcome y, the surprise is -\log q_\theta(y), the log loss; averaging it over the data gives the cross-entropy between the data and the model. A weather app that said “70\% rain” pays \log_2(1/0.7)=0.51 bits on a rainy day; one that said 10\% pays 3.32; one that said 0\% pays \log_2(1/0)=\infty. With a softmax output and the natural log, this is the categorical cross-entropy of episode 7, with gradient p-y with respect to the logits. Because e^{z}>0, a softmax never outputs an exact zero, so the loss stays finite.
Pause and think. On one particular July, can the Cupertino newcomer in Miami have a lower average surprise than the locals?
Show the answer
Yes, if that July happens to be dry: every day then costs him 0.005 bits and the locals 1.18. Cross-entropy is never below entropy only on average, over Miami’s weather as it really behaves (Section 5). On a small sample a wrong model can look better than the truth, which is one reason we judge models on held-out data.