ContentsChapter 2 · Probability6 of 6

2.6

Entropy and cross-entropy

In this chapter
  1. 2.1Conditional probability and Bayes' rule
  2. 2.2Random variables
  3. 2.3Expectation, variance, covariance
  4. 2.4Bernoulli, binomial and Gaussian
  5. 2.5Change of variables
  6. 2.6Entropy and cross-entropy
Before you readTwo models look at a scan that does show a tumour. One says the probability is 0.6, the other 0.99. Both are right. Which deserves the better score, and by how much?
Watch: A Short Introduction to Entropy, Cross-Entropy and KL-Divergence · Aurélien Géron

An outcome with probability p carries −log⁡2p-\log_2 p bits of surprise: a certain event carries none, and a one-in-1,024 event carries 10. The entropy of a distribution is its average surprise:

H(p)=−∑xp(x)log⁡p(x).H(p) = -\sum_x p(x) \log p(x).

It is 0 when one outcome is certain, and largest, log⁡2K\log_2 K bits, when all K outcomes are equally likely.

If the data come from p but you predict with a model q, your average surprise is the cross-entropy, and the extra over the entropy is the KL divergence:

H(p,q)=−∑xp(x)log⁡q(x),KL⁡(p ∥ q)=H(p,q)−H(p)=∑xp(x)log⁡p(x)q(x)≥0.H(p, q) = -\sum_x p(x) \log q(x), \qquad \operatorname{KL}(p \,\|\, q) = H(p, q) - H(p) = \sum_x p(x) \log \frac{p(x)}{q(x)} \ge 0.

KL is zero only when q=pq = p and it is not symmetric: in general KL⁡(p ∥ q)≠KL⁡(q ∥ p)\operatorname{KL}(p \,\|\, q) \ne \operatorname{KL}(q \,\|\, p)

Classifiers are trained by minimising cross-entropy. The label is a p that puts all its mass on the true class, so the loss for one example is −log⁡q(true class)-\log q(\text{true class}) That answers the question above: −ln⁡0.6≈0.51-\ln 0.6 \approx 0.51 against −ln⁡0.99≈0.01-\ln 0.99 \approx 0.01 Minimising it is the same as maximising the likelihood (see Statistics and optimisation). In ML the log is usually natural, which measures surprise in nats instead of bits.

123400.250.50.751
H(p) = 0.881 bitsH(p, q) = 1.146 bitsKL(p ‖ q) = 0.265 bits
A coin lands heads with chance p, and a model predicts q. The pink curve is the cross-entropy H(p, q), the average surprise when you expect q. Its lowest point is at q = p, where it meets the dashed entropy H(p). The purple gap is the KL divergence, the extra bits paid for the wrong model.
Recall
What is the entropy H(p)H(p) of a distribution?
Recall
What is the cross-entropy H(p,q)H(p, q) and when is it smallest?
Recall
What is the cross-entropy loss for one labelled example?
Exercise
What is the entropy, in bits, of a fair four-sided die?
Exercise
What is the entropy, in bits, of p=(12,14,14)p = \left(\frac12, \frac14, \frac14\right)
Exercise
A classifier gives the true class probability 0.8. What is its cross-entropy loss in nats, to three decimal places?