deck_order = math.lgamma(53) # ln 52! without forming 52!
print(f'the order of the deck: {deck_order:.2f} nats '
f'= {deck_order / math.log(2):.1f} bits')Dive into Deep Learning · §37.1
Entropy, Cross-Entropy, and KL Divergence
self-information · Shannon entropy · Gibbs’ inequality · irreducible loss · label smoothing · distillation
Motivation & Core Question
Self-Information
How much information do we gain by observing an outcome x of probability p(x)?
Self-Information in Practice
Surprisal scales logarithmically from single coin flips to vast combinatorial spaces without numerical overflow:
| Observation from a Shuffled Deck | Probability p(x) | Surprisal in Nats (-\ln p) | Surprisal in Bits (-\log_2 p) |
|---|---|---|---|
| “I see a card” (certain event) | 1 | 0.00 | 0.00 |
| “I see a heart” (1 of 4 suits) | 1/4 | \ln 4 \approx 1.39 | 2.00 |
| “It is the three of spades” (1 of 52) | 1/52 | \ln 52 \approx 3.95 | 5.70 |
| Full ordering of the entire 52-card deck | 1/52! | \ln \Gamma(53) \approx 156.36 | 225.58 |
the order of the deck: 156.36 nats = 225.6 bits
Discrete Entropy
For a discrete random variable X \sim P with probabilities p_i, Shannon entropy is the expected surprisal:
H(X) = H(P) = -\mathbb{E}_{x \sim P}[\log p(x)] = -\sum_i p_i \log p_i
Entropy & Binary Codes
On a finite set, H_2(P) in bits counts the average number of yes/no questions an optimal strategy needs to identify an outcome:
1, 01, 001, 000): \mathbb{E}[\text{questions}] = \tfrac12 \cdot 1 + \tfrac14 \cdot 2 + \tfrac18 \cdot 3 + \tfrac18 \cdot 3 = 1.75\text{ bits} = H_2(P)H = 1.213 nats = 1.75 bits
Pairs & Sequences
Because \log p(x, y) = \log p(x) + \log p(y \mid x), taking expectations decomposes joint uncertainty additively:
H(X, Y) = H(X) + H(Y \mid X)
Maximum Discrete Entropy
How uncertain can a discrete random variable over k outcomes possibly be?
Kullback–Leibler Divergence
Suppose data are drawn from the true distribution P, but we evaluate probabilities using a model Q. The KL divergence (or relative entropy) averages our extra surprisal under P:
D_{\textrm{KL}}(P \| Q) = \mathbb{E}_{x \sim P}\!\left[\log \frac{p(x)}{q(x)}\right] = \mathbb{E}_{x \sim P}\big[(-\log q(x)) - (-\log p(x))\big]
KL Divergence in Code
If q'(x) = 0 where p(x) > 0, the surprisal -\log q'(x) is infinite and D_{\textrm{KL}}(P \| Q') = +\infty:
def kl_divergence(p, q):
"""KL(P || Q) for two probability vectors, in nats; inf where q = 0 < p."""
p, q = np.asarray(p, dtype=float), np.asarray(q, dtype=float)
m = p > 0
if np.any(q[m] == 0):
return float('inf')
return float(np.dot(p[m], np.log(p[m] / q[m])))
p = np.array([0.6, 0.3, 0.1])
q = np.array([0.2, 0.5, 0.3])
print(f'KL(P||Q) = {kl_divergence(p, q):.4f} nats, '
f'KL(Q||P) = {kl_divergence(q, p):.4f} nats')
print(f"KL(P||Q') = {kl_divergence(p, [0.5, 0.5, 0.0])}")KL(P||Q) = 0.3961 nats, KL(Q||P) = 0.3653 nats
KL(P||Q') = inf
Why Softmax Never Outputs Zero: Because e^{z_j} > 0 for all finite logits z_j, a softmax classifier guarantees q_j > 0 everywhere and avoids infinite KL loss.
Fundamental Theorem
For any distributions P and Q, Gibbs’ inequality states D_{\textrm{KL}}(P \| Q) \ge 0, with equality iff P = Q:
D_{\textrm{KL}}(P \| Q) = -\mathbb{E}_{P}\!\left[\log\frac{q(x)}{p(x)}\right] \ge -\log Q(\textrm{supp}\,P) \ge 0
Uniform Bound & Conditioning
Gibbs’ inequality settles two foundational properties of entropy in a single line each:
The Loss Decomposition
The cross-entropy from P to Q is the average surprisal experienced by Q on data drawn from P:
Supervised Classification Loss
In k-class classification, how does the general cross-entropy formula become our training loss?
Population Loss Decomposition
On fresh test examples (\mathbf{x}, y) \sim P, population cross-entropy splits into conditional label entropy plus expected KL:
\mathbb{E}_{(\mathbf{x}, y)}\big[-\log q(y \mid \mathbf{x})\big] = H(Y \mid X) + \mathbb{E}_{\mathbf{x}}\big[D_{\textrm{KL}}\big(p(\cdot \mid \mathbf{x}) \,\|\, q(\cdot \mid \mathbf{x})\big)\big]
Worked Example: 10% Label Noise
With k = 10 classes and \rho = 0.1 label noise, the floor is H_b(0.1) + 0.1 \ln 9 = 0.325 + 0.220 = 0.545 nats. Compare three predictors on this noisy test distribution:
floor = H(p) = 0.545 nats
uniform CE = 2.303 nats
confident 0.99 CE = 0.689 nats
Bayes q = p CE = 0.545 nats
Why Overconfidence Hurts: A classifier predicting 0.99 on the clean class achieves the maximum possible 90\% accuracy, yet suffers 0.689 nats loss because each 10\% flipped label inflicts -\ln(0.01/9) = 6.80 nats of surprise.
Decision Theory & Calibration
Softened Targets
With one-hot targets (\mathbf{e}_y), reaching q_y = 1 requires an infinite logit gap z_y - z_j \to \infty, causing unbounded weight growth and overconfidence. Label smoothing mixes \mathbf{e}_y with uniform mass \epsilon \in (0, 1):
\mathbf{p}^\epsilon = (1 - \epsilon)\mathbf{e}_y + \frac{\epsilon}{k}\mathbf{1}
Gradient Dynamics
Under gradient descent on one example (\nabla_{\mathbf{z}} \textrm{CE} = \mathbf{q} - \mathbf{p}^\epsilon), a one-hot target (\epsilon = 0) widens the logit gap g_t by \approx k e^{-g_t} per step, causing logarithmic drift g_t \approx \ln(kt), whereas \epsilon = 0.1 arrests the gap at \ln 91 = 4.51:
eps = 0.0 step 10 gap = 4.29 loss = 0.1158
eps = 0.0 step 100 gap = 6.87 loss = 0.0093
eps = 0.0 step 1000 gap = 9.21 loss = 0.0009
eps = 0.0 step 10000 gap = 11.51 loss = 0.0001
eps = 0.1 step 10 gap = 3.81 loss = 0.5243
eps = 0.1 step 100 gap = 4.51 loss = 0.5003
eps = 0.1 step 1000 gap = 4.51 loss = 0.5003
eps = 0.1 step 10000 gap = 4.51 loss = 0.5003
optimum for eps = 0.1: gap = ln 91 = 4.51, loss = H(p_eps) = 0.5003
Teacher-Student Distillation
In knowledge distillation, a compact student network \mathbf{z}^{\textrm{stu}} trains to match the dark knowledge in a teacher’s wrong-class probabilities by softening both with temperature \tau > 0:
p_j^{(\tau)} = \mathrm{softmax}(\mathbf{z}^{\textrm{tea}}/\tau)_j, \qquad q_j^{(\tau)} = \mathrm{softmax}(\mathbf{z}^{\textrm{stu}}/\tau)_j, \qquad \mathcal{L}_{\textrm{distill}} = \tau^2 D_{\textrm{KL}}\!\left(\mathbf{p}^{(\tau)} \,\|\, \mathbf{q}^{(\tau)}\right)
Distillation Numerics
Without the \tau^2 factor, raising \tau from 1 to 20 shrinks the distillation gradient norm 300\times (from 0.64 to 0.0021); multiplying by \tau^2 keeps the gradient magnitude steady near the zero-mean logit-matching limit:
tau |grad| |tau^2 grad| tau^2 grad
1 0.6391 0.639 [-0.462 0.441 0.022]
2 0.2190 0.876 [-0.672 0.549 0.123]
5 0.0368 0.920 [-0.741 0.478 0.263]
10 0.0088 0.884 [-0.719 0.413 0.306]
20 0.0021 0.854 [-0.697 0.374 0.322]
limit 0.816 [-0.667 0.333 0.333]
Continuous Random Variables
For a continuous random variable X with density p(x), the differential entropy is h(X) = -\int p(x)\log p(x)\,dx. Unlike discrete entropy H(X), differential entropy is neither non-negative nor scale-invariant:
Closed Form & Tail Asymmetry
Comparing two Gaussian distributions P = \mathcal{N}(\mu_1, \sigma_1^2) and Q = \mathcal{N}(\mu_2, \sigma_2^2) yields an exact closed form:
Sampling Variance & Gaussian Optimality
Estimating D_{\textrm{KL}}(P \| Q) from n = 2 \times 10^5 samples is 4\times noisier when sampling the wide Gaussian (16\times more samples needed for equal precision) because the divergence lives in the sparse tails:
P || Q closed sampled std err
N(0,1) || N(1,1) 0.5000 0.5010 0.0022
N(0,1) || N(0,4) 0.3181 0.3169 0.0012
N(0,4) || N(0,1) 0.8069 0.8017 0.0047
Gaussian Maximum Entropy Theorem: Because the Gaussian surprisal -\log \varphi(x) = \tfrac12\log(2\pi\sigma^2) + \frac{(x-\mu)^2}{2\sigma^2} is quadratic, \textrm{CE}(P, \varphi) = \tfrac12\log(2\pi e\sigma^2) = h(\varphi) for every density P with mean \mu and variance \sigma^2. Thus h(P) = h(\varphi) - D_{\textrm{KL}}(P \| \varphi) \le \tfrac12\log(2\pi e\sigma^2), with equality if and only if P = \mathcal{N}(\mu, \sigma^2).
Check Your Understanding
Work through these three diagnostic calculations:
Answers:
Key Takeaways
| Quantity | Mathematical Definition | Range & Invariance | Deep Learning Role |
|---|---|---|---|
| Self-Information | I(x) = -\log p(x) | [0, \infty]; additive on independent events | Single-example negative log-likelihood loss |
| Discrete Entropy | H(P) = -\sum_{i=1}^k p_i \log p_i | [0, \log k]; peaks at uniform U | Irreducible loss floor H(Y \mid X); expected questions |
| Differential Entropy | h(P) = -\int p(x)\log p(x)\,dx | (-\infty, \infty); shifts by \mathbb{E}[\log|\det Dg|] | Gaussian max-entropy \tfrac12\log(2\pi e\sigma^2) at fixed variance |
| KL Divergence | D_{\textrm{KL}}(P \| Q) = \mathbb{E}_P[\log(p/q)] | [0, \infty]; 0 \iff P = Q; scale-invariant | Extra surprisal; penalty for model mismatch |
| Cross-Entropy | \textrm{CE}(P, Q) = H(P) + D_{\textrm{KL}}(P \| Q) | [H(P), \infty]; strictly proper log score | Standard training objective for classifiers & LLMs |
| Label Smoothing | \mathbf{p}^\epsilon = (1-\epsilon)\mathbf{e}_y + (\epsilon/k)\mathbf{1} | Optimal logit gap \log(1 + k(1-\epsilon)/\epsilon) | Prevents unbounded logit drift and overconfidence |
| Distillation Loss | \tau^2 D_{\textrm{KL}}(\mathbf{p}^{(\tau)} \| \mathbf{q}^{(\tau)}) | \mathcal{O}(1) gradient scale across all \tau > 0 | Transfers wrong-class dark knowledge from teacher |