Foundations to Frontier
Tests
A. Mathematical Foundations › A7 Information Theory

Cross-Entropy and Its Use as a Loss

Cross-entropy measures the average number of bits needed to encode data from one distribution using a code built for another. As a loss it is exactly the negative log-likelihood, which makes it the default objective for classification and language modelling. You will derive its decomposition H(p, q) = H(p) + KL(p‖q), the softmax cross-entropy gradient, numerically stable log-softmax, label smoothing and perplexity, see why it beats squared error for classification, and fix an overconfident terrain classifier with temperature scaling.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Paying for wrong beliefs

Suppose you design a shorthand for a language, giving short codes to words you believe are common. If your beliefs match how people actually talk, your messages are short. If not, you waste space on every message. Cross-entropy is the average message length when you use codes built for your beliefs qq on data that really follows pp.

To train a classifier, we make its beliefs (predicted probabilities) cost as little as possible on the real labels. Confident wrong answers cost a lot.

Why classifiers train on cross-entropy
true class:
cross-entropysquared error on probabilitiestrue-class logit →gradient d loss / d logit
p = (sand 0.039, rock 0.786, ice 0.175) · CE = 3.241 nats · squared error = 1.571 · CE gradient -0.961 vs MSE gradient -0.123
When the model is confidently wrong (true-class logit far left), cross-entropy is large and its gradient approaches −1: a strong push to fix the mistake. The squared error saturates at its maximum and its gradient vanishes, so learning stalls. Cross-entropy is also exactly the negative log-likelihood, so minimizing it is maximum-likelihood estimation. With label smoothing ε, the minimum moves to a finite logit, discouraging extreme overconfidence.
Why engineers care

Every image classifier, terrain classifier, semantic-segmentation network and language model is trained by minimizing cross-entropy. Its value in bits per symbol (or its perplexity) is the standard measure of how well a model predicts.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Cross-entropy is small when the model gives the true class…
  2. 2. Being confidently wrong makes cross-entropy…
  3. 3. Cross-entropy is the most common loss for…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Definition

H(p,q)=−∑xp(x)log⁡q(x)=Ex∼p[−log⁡q(x)]H(p, q) = -\sum_xp(x)\log q(x) = \mathbb E_{x\sim p}[-\log q(x)]

For a single labelled example with one-hot pp, this is −log⁡q(y)-\log q(y), the negative log-probability of the correct class.

Softmax cross-entropy

A network outputs logits zz, and q=softmax⁡(z)q = \operatorname{softmax}(z), qk=ezk/∑jezjq_k = e^{z_k}/\sum_je^{z_j}. The loss is

ℓ(z,y)=−log⁡qy=log⁡∑jezj−zy\ell(z, y) = -\log q_y = \log\sum_je^{z_j} - z_y

Compute it with the log-sum-exp trick: subtract max⁡z\max z first to avoid overflow.

Perplexity

2H(p,q)2^{H(p, q)} (with HH in bits) is the effective number of equally likely choices the model is torn between. A language model with 3 bits per token has perplexity 8.

📝 Quick check (Level 1)
0/3 answered
  1. 1. For a one-hot label, cross-entropy equals…
  2. 2. Uniform guessing over 3 classes costs…
  3. 3. Perplexity at 3 bits/token is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

Decomposition

H(p,q)=H(p)+KL⁡(p ∥ q)H(p, q) = H(p) + \operatorname{KL}(p\,\|\,q)

H(p)H(p) is fixed by the data, so minimizing cross-entropy over the model qq is the same as minimizing KL⁡(p ∥ q)\operatorname{KL}(p\,\|\,q), and the same as maximizing likelihood. That’s why cross-entropy training is maximum-likelihood estimation.

Gradient

∂ℓ∂zk=qk−pk\frac{\partial\ell}{\partial z_k} = q_k - p_k

Prediction minus target: bounded, and large when confidently wrong. Compare squared error on probabilities, whose gradient gets multiplied by the softmax Jacobian and vanishes when the model saturates on the wrong answer.

Practical variants

  • Label smoothing: target (1−ε) one-hot+ε/K(1 - \varepsilon)\,\text{one-hot} + \varepsilon/K (Szegedy et al., 2016). This discourages infinite logits and improves calibration.
  • Class weighting / focal loss: up-weight rare classes or hard examples (Lin et al., 2017, focal loss for dense detection).
  • Binary cross-entropy for independent multi-label outputs (sigmoid per class).
  • Calibration: models trained to near-zero loss become overconfident. Temperature scaling, q=softmax⁡(z/T)q = \operatorname{softmax}(z/T) with TT fitted on validation NLL, fixes this without changing predictions (Guo et al., 2017).
🐍 Exercise 1: cross-entropy mechanics
Implement cross-entropy, a stable log-softmax and softmax cross-entropy with label smoothing. Verify H(p, q) = H(p) + KL, overflow safety, the analytic gradient against finite differences, and the effect of smoothing.
📝 Quick check (Level 2)
0/3 answered
  1. 1. ∂ℓ/∂z for softmax cross-entropy is…
  2. 2. Minimizing cross-entropy over q is equivalent to minimizing…
  3. 3. Temperature scaling changes…

Level 3: Advanced

★★★★☆ Advanced⏱ 40 minGraduate level, with full derivations and proofs.

Deriving the softmax CE gradient

ℓ=log⁡∑jezj−∑kpkzk\ell = \log\sum_je^{z_j} - \sum_kp_kz_k (with ∑pk=1\sum p_k = 1). Then ∂zklog⁡∑ezj=qk\partial_{z_k}\log\sum e^{z_j} = q_k and ∂zk∑pjzj=pk\partial_{z_k}\sum p_jz_j = p_k, so ∇ℓ=q−p\nabla\ell = q - p. ∎

Gibbs’ inequality: cross-entropy is minimized at q = p

H(p,q)−H(p)=∑plog⁡pq=KL⁡(p ∥ q)≥0H(p, q) - H(p) = \sum p\log\frac pq = \operatorname{KL}(p\,\|\,q)\ge0, by Jensen: −∑plog⁡qp≥−log⁡∑q=0-\sum p\log\frac qp\ge-\log\sum q = 0. Equality holds iff q=pq = p. ∎ So the expected loss is minimized by predicting the true conditional probabilities. Cross-entropy is a proper scoring rule.

Cross-entropy = negative log-likelihood

For data {(xi,yi)}\{(x_i, y_i)\}, 1n∑i−log⁡qθ(yi∣xi)\frac1n\sum_i-\log q_\theta(y_i\mid x_i) is the average negative log-likelihood. Minimizing it is MLE (A5.1-4), consistent and asymptotically efficient for well-specified models.

Exercise 3.1: Cross-entropy of p = (½, ½) with q = p

H(p,p)=H(p)=1H(p, p) = H(p) = 1 bit, the minimum possible for this pp.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Cross-entropy is a proper scoring rule, meaning…
  2. 2. ∂/∂z_k of log Σ eᶻʲ is…
  3. 3. Minimizing average cross-entropy over a model is…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Calibrating an overconfident terrain classifier

A softmax classifier with 10 features (2 informative) is trained on only 60 labelled terrain patches until the training loss is nearly zero. On test data it’s overconfident: its stated confidence exceeds its accuracy, with an expected calibration error (ECE) of about 0.12. Fitting a single temperature T≈2.3T\approx2.3 on a validation set lowers the test NLL and cuts the ECE to about 0.05, with accuracy unchanged. A planner deciding whether to cross terrain needs calibrated probabilities, not just correct argmaxes.

🐍 Exercise 2 (research): temperature scaling for calibration
Train an unregularized softmax classifier on a small terrain dataset, measure test NLL and expected calibration error, fit a temperature on validation data, and show that calibration improves while predictions are unchanged.

Cross-entropy in AI, robotics and aerospace

  • Perception: semantic segmentation for terrain classification on planetary rovers trains with per-pixel cross-entropy (Rothrock et al., 2016, SPOC for Mars).
  • Language and multimodal models minimize next-token cross-entropy. Reported in bits per byte or perplexity, it doubles as a compression rate (A7-7).
  • Calibrated uncertainty feeds risk-aware planning and decision thresholds (Guo et al., 2017; Ovadia et al., 2019).
  • Imitation learning: behaviour cloning with discrete actions is cross-entropy on expert actions.

References

  1. T. Cover, J. Thomas (2006). Elements of Information Theory, 2nd ed. Wiley. Ch. 2, 5.
  2. I. Goodfellow, Y. Bengio, A. Courville (2016). Deep Learning. MIT Press. §5.5, 6.2.
  3. C. Guo, G. Pleiss, Y. Sun, K. Weinberger (2017). “On calibration of modern neural networks.” ICML.
  4. C. Szegedy et al. (2016). “Rethinking the Inception architecture for computer vision.” CVPR (label smoothing).
  5. T.-Y. Lin et al. (2017). “Focal loss for dense object detection.” ICCV.
  6. T. Gneiting, A. Raftery (2007). “Strictly proper scoring rules, prediction, and estimation.” JASA, 102(477).
  7. Y. Ovadia et al. (2019). “Can you trust your model’s uncertainty?” NeurIPS.
  8. B. Rothrock et al. (2016). “SPOC: deep learning-based terrain classification for Mars rover missions.” AIAA SPACE.
  9. R. Müller, S. Kornblith, G. Hinton (2019). “When does label smoothing help?” NeurIPS.
  10. G. Delétang et al. (2024). “Language modeling is compression.” ICLR.