Module contents
Lesson 6 of 19Core 110 min

Cross-entropy: loss, likelihood and betting

Define cross-entropy as the expected code length under q and relate it to maximum likelihood and forward KL. Derive the stable softmax cross-entropy loss and its gradient, then interpret log loss as a strictly proper score and through the KL growth difference in Kelly betting.

After this lesson you can

  • Prove H(p,q) = H(p) + D(p‖q) and that minimizing empirical cross-entropy gives the maximum-likelihood estimate.
  • Derive the gradients of softmax cross-entropy and binary cross-entropy with logits.
  • Implement stable cross-entropy with log-sum-exp and check it against PyTorch.
  • Prove that the logarithmic score is strictly proper and connect it to calibration.
  • Derive the horse-race Kelly strategy, show that growth is D(p‖r) − D(p‖b), and show that side information is worth I(X;Y).
  • Analyze label smoothing as cross-entropy with a mixture target.

Before you start

Motivation: the loss that trains almost everything

An image classifier receives three photos and assigns their correct classes probabilities 0.90.9, 0.50.5 and 0.10.1. How wrong was it? The answer used by almost all modern AI is the mean of −ln⁡q(clase correcta)-\ln q(\text{clase correcta}): 0.1050.105, 0.6930.693 and 2.3032.303, with mean 1.0341.034. Notice the penalty’s shape: going from 0.90.9 to 0.50.5 costs 0.590.59, but going from 0.50.5 to 0.10.1 costs 1.611.61, and reaching 00 costs infinity. That loss is cross entropy, and it trains image classifiers, language models, policies that imitate an expert, and much of what you will see in later modules. A language model with a vocabulary of 50 25750\,257 tokens (GPT-2’s) that initially distributes probability nearly uniformly has initial loss ln⁡50257≈10.82\ln 50257 \approx 10.82 nats: if training starts with a very different number, something is miswired before the model has learned anything.

Why the logarithm? The previous lesson gave three reasons that become theorems here:

  • It is code length. −log⁡2q(x)-\log_2 q(x) is the bits required to describe xx with a code fitted to model qq (surprise). Averaged over the data, it is what one pays to encode with the wrong model, and the excess over entropy is Kullback–Leibler divergence.
  • It is likelihood. The logarithm converts a product of probabilities into a sum, and training by maximum likelihood is exactly minimizing this loss.
  • It is the only honest way to score a prediction. If paid according to −ln⁡q(lo que ocurrioˊ)-\ln q(\text{lo que ocurrió}), your best move is to report the probability you truly believe. In another context, betting on a horse race, wealth grows at a rate given by a difference of divergences.

This lesson starts with the definition and decomposition H(p,q)=H⁡(p)+KL⁡(p ∥ q)H(p, q) = \Ent(p) + \KL(p\,\|\,q), proves minimizing loss is equivalent to maximum likelihood and minimizing forward KL (and the implications when the model cannot represent the data), derives softmax cross-entropy loss and its gradient, explains why it requires careful computation, studies logarithmic scoring and calibration, covers soft targets (label smoothing and distillation), and ends with Kelly betting. Conventions: in training sections log⁡\log is the natural logarithm and losses are in nats, as in PyTorch; coding and betting use bits. Convert nats to bits by multiplying by 1/ln⁡2=1.44271/\ln 2 = 1.4427; all identities hold in any base.

Definition and decomposition

Let p,qp, q be distributions over a finite alphabet X\mathcal{X} (lesson 11 extends this to continuous variables). Think of pp as the data distribution and qq as the model.

Proof

If p≪qp \ll q (that is, q(x)>0q(x) > 0 whenever p(x)>0p(x) > 0), sum over the support of pp:

−∑xp(x)log⁡q(x)=−∑xp(x)log⁡p(x)+∑xp(x)log⁡p(x)q(x)=H⁡(p)+KL⁡(p ∥ q).-\sum_x p(x) \log q(x) = -\sum_x p(x) \log p(x) + \sum_x p(x) \log \frac{p(x)}{q(x)} = \Ent(p) + \KL(p\,\|\,q).

If an xx exists with p(x)>0=q(x)p(x) > 0 = q(x), both sides equal +∞+\infty. The inequality and equality case are Gibbs’ inequality: KL⁡(p ∥ q)≥0\KL(p\,\|\,q) \ge 0, with equality only if p=qp = q.

∎

Two immediate interpretations. First: the floor H⁡(p)\Ent(p) does not depend on qq, so minimizing H(p,q)H(p, q) over qq is equivalent to minimizing KL⁡(p ∥ q)\KL(p\,\|\,q); the model controls excess, and minimum possible cross entropy is not 00 but H⁡(p)\Ent(p), irreducible data noise. Second: it is a code length. With lengths ℓ(x)=−log⁡2q(x)\ell(x) = -\log_2 q(x), which satisfy Kraft’s inequality with equality, mean bits per symbol of a source pp is H(p,q)H(p, q) (integer lengths ⌈−log⁡2q(x)⌉\lceil -\log_2 q(x) \rceil cost less than one extra bit, cost of coding with the wrong model).

The first figure lets you explore this identity. A four-class classifier produces logits zz, and its prediction is q=softmax⁡(z)q = \softmax(z) (defined rigorously below). Drag the logits and loss is divided into a stacked bar.

InteractiveThe floor and the excess
Logits zkz_k (drag the tip)
−8−40480.00.00.00.0class 1class 2class 3class 4
Target pp and prediction q=softmax⁡(z)q = \softmax(z)
0.000.250.500.751.000.500.251−log q = 2.000.250.252−log q = 2.000.130.253−log q = 2.000.130.254−log q = 2.00pq
Loss H(p,q)=H⁡(p)+KL⁡(p ∥ q)H(p, q) = \Ent(p) + \KL(p\,\|\,q), in bits
0.00.51.01.52.02.5H(p) = 1.75q uniforme: log K = 2.002.00
irreducible floorexcess due to model mismatch
0.00
Unit
Loss H(p,q)H(p, q)2.000 bits
Floor H⁡(p)\Ent(p)1.750 bits
Excess KL⁡(p ∥ q)\KL(p\,\|\,q)0.250 bits
Margin z1−max⁡k≠1zkz_1 - \max_{k \ne 1} z_k0.0
Descent steps0
Gray bar: target entropy, H⁡(p)=1.750\Ent(p) = 1.750 bits, which no qq can remove. Red bar: model excess KL⁡(p ∥ q)\KL(p\,\|\,q).
Drag the tips of the logit bars (or use arrow keys while a bar is focused). Below, loss H(p,q)H(p, q) is stacked as gray floor H⁡(p)\Ent(p) and red excess KL⁡(p ∥ q)\KL(p\,\|\,q). Start with the 1.75-bit source and zero logits (uniform qq): what is the excess? Press ‘Go to optimum’ and verify that excess disappears but the floor does not. Then choose ‘Hard label’: where is the floor now? Press ‘Train’ and observe the margin as loss falls. Finally increase smoothing ε\varepsilon and train again.

Three things the figure shows and the rest of the lesson proves.

  1. The floor exists. With an ambiguous target, such as the 1.751.75-bit source or two equally likely classes, no logit reduces loss below H⁡(p)\Ent(p). If training loss stalls at ln⁡2=0.69\ln 2 = 0.69 on a balanced two-class task, the model predicts the same as an indifferent one: either data contain no signal (floor ln⁡2\ln 2) or training is failing, and loss alone cannot distinguish them.
  2. With a hard label the floor is zero, reached only at infinity. Target p=eyp = e_y (all mass on one class) has H⁡(p)=0\Ent(p) = 0, so H(p,q)=−log⁡q(y)H(p, q) = -\log q(y) vanishes only if q(y)=1q(y) = 1, i.e. with the correct logit infinitely above the others. However well training goes, gradient descent keeps pushing logits: with four classes and step 11, margin z1−z2z_1 - z_2 is 3.563.56 after 10 steps, 5.975.97 after 100 and 8.298.29 after 1000, growing like ln⁡t\ln t while loss decreases like 1/t1/t. This is the origin of overconfidence in networks trained with hard labels.
  3. A smoothed target has a finite optimum. With ε=0.1\varepsilon = 0.1 and K=4K = 4 the target is (0.925,0.025,0.025,0.025)(0.925, 0.025, 0.025, 0.025), its entropy is 0.3490.349 nats, and the optimum has margin ln⁡(0.925/0.025)=ln⁡37=3.61\ln(0.925/0.025) = \ln 37 = 3.61. This is label smoothing, studied below.

Likelihood, cross entropy and forward KL

Data are y1,…,yny_1, \dots, y_n, independent and identically distributed according to unknown distribution p∗p^\ast, and the model is a family qθq_\theta. Let p^(y)=1n#{i:yi=y}\hat p(y) = \frac1n \#\{i : y_i = y\} be the empirical distribution.

Proof

Group terms by value: ∑i=1n−log⁡qθ(yi)=∑y#{i:yi=y} (−log⁡qθ(y))=n∑yp^(y) (−log⁡qθ(y))=n H(p^,qθ)\sum_{i=1}^n -\log q_\theta(y_i) = \sum_{y} \#\{i : y_i = y\}\,(-\log q_\theta(y)) = n \sum_y \hat p(y)\,(-\log q_\theta(y)) = n\,H(\hat p, q_\theta). The second equality is the decomposition theorem applied to p^\hat p. Since log⁡\log is strictly increasing, maximizing the product is equivalent to minimizing the average of its negated logarithms, and H⁡(p^)\Ent(\hat p) does not depend on θ\theta.

∎

This is what happens in a classifier, where the model is conditional, qθ(y∣x)q_\theta(y \mid x). Training loss is 1n∑i−log⁡qθ(yi∣xi)\frac1n\sum_i -\log q_\theta(y_i \mid x_i), the mean cross entropy between each example’s label, viewed as a concentrated distribution eyie_{y_i}, and the model prediction. If every input appears once, p^(⋅∣xi)=eyi\hat p(\cdot \mid x_i) = e_{y_i} and floor H⁡(p^(⋅∣x))\Ent(\hat p(\cdot\mid x)) is 00: the first figure’s “hard label”.

When the model cannot represent the data

If p∗=qθ0p^\ast = q_{\theta_0} for some θ0\theta_0 in the family, the strong law of large numbers gives H(p^,qθ)→H(p∗,qθ)=H⁡(p∗)+KL⁡(p∗ ∥ qθ)H(\hat p, q_\theta) \to H(p^\ast, q_\theta) = \Ent(p^\ast) + \KL(p^\ast\,\|\,q_\theta) for each θ\theta and, under usual regularity conditions (identifiable parameter and uniform convergence in θ\theta), the estimator converges to true θ0\theta_0, where divergence is 00. But a real model almost never contains the data. Maximum likelihood still converges, to a well-defined quantity: the pseudo-true parameter θ∗=arg min⁡θKL⁡(p∗ ∥ qθ)\theta^\ast = \argmin_\theta \KL(p^\ast\,\|\,q_\theta), the “projection” of p∗p^\ast onto the family in forward-KL terms. The projection is a question of geometry, and for exponential families has a closed form.

Proof

−log⁡qθ(x)=−log⁡h(x)−θ⊤T(x)+A(θ)-\log q_\theta(x) = -\log h(x) - \theta\T T(x) + A(\theta). Taking Ep\E_p and differentiating with respect to θ\theta gives −Ep[T]+∇A(θ)-\E_p[T] + \grad A(\theta), and for an exponential family ∇A(θ)=Eqθ[T]\grad A(\theta) = \E_{q_\theta}[T] (the derivative of the log-partition is the statistic’s mean). Since AA is convex, H(p,qθ)H(p, q_\theta) is convex in θ\theta and stationary points are global minima.

∎

For the Gaussian family, T(x)=(x,x2)T(x) = (x, x^2): the best Gaussian in cross-entropy terms has the data’s mean and variance, whatever their shape (finite variance suffices). If data are a mixture of two separated bells, the result is a wide bell centered between them. The other direction, KL⁡(q ∥ p)\KL(q\,\|\,p), encountered in variational inference, asks the opposite: that qq have no mass where pp has none.

InteractiveWhen the model falls short
Data pp (two-bell mixture) and model qq (one bell), densities discretized into 241 bins
0.00.20.40.6−6−4−20246
  • pp (data)
  • your qq
  • best qq for KL⁡(p ∥ q)\KL(p\,\|\,q) (maximum likelihood)
  • best qq for KL⁡(q ∥ p)\KL(q\,\|\,p)
±2.0
0.50
−2.0
0.7
Your qq: KL⁡(p ∥ q)\KL(p\,\|\,q)7.476 nats
Your qq: KL⁡(q ∥ p)\KL(q\,\|\,p)0.687 nats
Maximum-likelihood fit (μ,σ)(\mu, \sigma)(0.00, 2.12)
ML: KL⁡(p ∥ q)\KL(p\,\|\,q) / KL⁡(q ∥ p)\KL(q\,\|\,p)0.416 / 0.742
Reverse KL fit (μ,σ)(\mu, \sigma)(−2.0, 0.7)
Reverse KL: KL⁡(p ∥ q)\KL(p\,\|\,q) / KL⁡(q ∥ p)\KL(q\,\|\,p)7.476 / 0.687
Your qq covers one mode: KL⁡(q ∥ p)=0.69\KL(q\,\|\,p) = 0.69 is low, but KL⁡(p ∥ q)=7.48\KL(p\,\|\,q) = 7.48 is high because the other mode is uncovered. Cross-entropy would not choose this.
Data pp are a mixture of two bells (blue); model qq can only be one Gaussian (orange). Press ‘Fit by cross entropy’: qq matches the mean and variance of pp (green dashed line) and falls in the valley, where almost no data lie. Press ‘Fit by reverse KL’: qq stays with one mode (magenta dots). Compare both divergences in each case. Change the left mode's weight and the separation: which fit changes continuously, and which jumps from one mode to another?

With initial values (a=2a = 2, two equally weighted modes with standard deviation 0.70.7), maximum-likelihood fit is μ=0\mu = 0 and σ=a2+0.72=2.12\sigma = \sqrt{a^2 + 0.7^2} = 2.12, with KL⁡(p ∥ q)=0.416\KL(p\,\|\,q) = 0.416 nats and KL⁡(q ∥ p)=0.742\KL(q\,\|\,p) = 0.742. Reverse KL stays with one mode (μ=±2\mu = \pm 2, σ=0.7\sigma = 0.7) and has KL⁡(q ∥ p)=0.687≈ln⁡2\KL(q\,\|\,p) = 0.687 \approx \ln 2: covering one of two equal modes costs −ln⁡12-\ln\tfrac12. But KL⁡(p ∥ q)\KL(p\,\|\,q) for that qq exceeds 77 nats (on the interactive’s 241-cell grid; in the continuum it grows without bound with separation), because the other mode is uncovered. Each fit most fears its divergence: cross entropy cannot tolerate leaving a data region uncovered and prefers “overcoverage”; reverse KL cannot tolerate placing mass where there are no data and prefers “choosing a mode”. Lesson 15 develops this. For a generative model trained with cross entropy, the drive to cover everything is one reason sampling at temperature 11 can yield low-quality results in low-probability regions.

Classification: softmax cross-entropy loss

A classifier with KK classes produces logits z∈RKz \in \R^K, unconstrained real numbers converted into probabilities by softmax.

The second form matters: logsumexp⁡\operatorname{logsumexp} is a smoothed maximum, max⁡kzk≤logsumexp⁡(z)≤max⁡kzk+log⁡K\max_k z_k \le \operatorname{logsumexp}(z) \le \max_k z_k + \log K, so L(z,y)L(z, y) is a smooth version of margin max⁡kzk−zy\max_k z_k - z_y between the highest-scored and correct class. It is convex in zz because logsumexp⁡\operatorname{logsumexp} is.

Proof

By the chain rule, ∂∂zklog⁡∑jezj=ezk∑jezj=qk\frac{\partial}{\partial z_k} \log\sum_j e^{z_j} = \frac{e^{z_k}}{\sum_j e^{z_j}} = q_k and ∂zy∂zk=1[k=y]\frac{\partial z_y}{\partial z_k} = \ind[k = y]. Subtracting gives the gradient; for a soft target, ∂∂zk∑jpjzj=pk\frac{\partial}{\partial z_k}\sum_j p_j z_j = p_k. For the Hessian, ∂qk∂zj=qk(δkj−qj)\frac{\partial q_k}{\partial z_j} = q_k(\delta_{kj} - q_j), which is diag⁡(q)−qq⊤\diag(q) - q q\T; and for any vv, v⊤(diag⁡(q)−qq⊤)v=∑kqkvk2−(∑kqkvk)2=Var⁡q(v)≥0v\T(\diag(q) - qq\T)v = \sum_k q_k v_k^2 - (\sum_k q_k v_k)^2 = \operatorname{Var}_{q}(v) \ge 0.

∎

The result is surprisingly simple: error is predicted probability minus target probability. Its practical consequences:

  • It is bounded: each component is in [−1,1][-1, 1] and ∥q−ey∥2≤2\norm{q - e_y}_2 \le \sqrt 2. It never explodes.
  • It does not vanish when the model is confidently wrong. If qy≈0q_y \approx 0, gradient component yy is almost −1-1: loss pushes at full strength just where most needed. It vanishes only when q=pq = p.
  • It sums to zero, ∑k(qk−pk)=0\sum_k (q_k - p_k) = 0, the function’s shift invariance.
  • In a network, the signal reaching the last layer is (q−p)/B(q - p)/B for a batch of BB examples, and the gradient with respect to weight matrix W\mat{W} with z=Wxz = \mat{W}\vb{x} is (q−p) x⊤(q - p)\,\vb{x}\T: residual times input, as in linear regression. This is a property of generalized linear models with their canonical link.

The second figure makes this visible. Three logits have fixed z3=0z_3 = 0 (without loss of generality by invariance), so logit space is a plane. The arrow field is −∇L-\grad L.

InteractiveCross-entropy versus squared-error gradient
Plane (z1,z2)(z_1, z_2) with z3=0z_3 = 0: color = loss, arrows = −∇-\nabla (same scale for both losses)
−6−6−4−4−2−200224466z₁z₂class 1 correct
Gradient norm as correct-class logit zyz_y moves (others fixed)
0.00.51.01.5−8−4048correct-class logit, z_yconfident and wrong
  • cross-entropy
  • squared error on probabilities
  • ball (current position)
Correct class
Loss to minimize
1.0
Speed
Logits (z1,z2,z3)(z_1, z_2, z_3)(−5.0, 5.0, 0)
q1q_1 (correct class)4.5e−5
∥∇z CE∥\lVert\nabla_z\,\text{CE}\rVert1.409
∥∇z MSE∥\lVert\nabla_z\,\text{MSE}\rVert0.0187
Loss CE / MSE10.007 / 1.987
Steps0
The model assigns only 4.5e−5 to the correct class. Cross-entropy still pushes with ∥∇∥=1.41\lVert\nabla\rVert = 1.41; squared error has 0.0190.019: almost no signal to escape.
The ball is at a point in plane (z1,z2)(z_1, z_2); color is loss and arrows are negative gradient (same scale for both losses). Start with ‘Confident and wrong’: the model gives almost all probability to class 2, while the correct class is 1. Press ‘Descend’ with cross entropy: the ball crosses the plane. Switch to ‘Squared error’ (sum of (qk−yk)2(q_k - y_k)^2) and repeat: does it move? Below, gradient norm when moving only the correct-class logit: cross entropy stays between 11 and 2\sqrt 2 until the model gets it right; squared error flattens toward 0 at both extremes. Change the correct class and try large η\eta.

At the starting point z=(−5,5,0)z = (-5, 5, 0), the model assigns q1=4.5⋅10−5q_1 = 4.5 \cdot 10^{-5} to the correct class and the cross-entropy gradient norm is 1.411.41. For squared error on probabilities, ∑k(qk−yk)2\sum_k (q_k - y_k)^2, whose gradient is ∂zj=2qj(qj−yj−∑k(qk−yk)qk)\partial_{z_j} = 2 q_j\big(q_j - y_j - \sum_k (q_k - y_k)q_k\big), the norm is 0.0190.019, 7575 times smaller, and worse the more confidently wrong the model is: it is the gradient of a function that flattens when softmax saturates. With η=1\eta = 1, cross entropy takes correct-class probability above 0.50.5 in 77 steps; squared error barely moves the ball in the first 5050 steps, spends the next hundred lowering the wrong logit while q1q_1 remains below 0.020.02, and needs about 180180. This is the practical reason classification is trained with cross entropy rather than least squares on probabilities: only cross entropy’s signal stays alive when most needed.

The binary version with logits

For two classes a single logit suffices. Let y∈{0,1}y \in \{0, 1\}, z∈Rz \in \R be the logit and q=σ(z)=1/(1+e−z)q = \sigma(z) = 1/(1 + e^{-z}) the class-1 probability. Since −log⁡σ(z)=softplus⁡(−z)-\log\sigma(z) = \operatorname{softplus}(-z) and −log⁡(1−σ(z))=softplus⁡(z)-\log(1 - \sigma(z)) = \operatorname{softplus}(z), with softplus⁡(t)=log⁡(1+et)\operatorname{softplus}(t) = \log(1 + e^t),

L(z,y)=−ylog⁡σ(z)−(1−y)log⁡(1−σ(z))=softplus⁡(z)−y z,∂L∂z=σ(z)−y.L(z, y) = -y\log\sigma(z) - (1 - y)\log(1 - \sigma(z)) = \operatorname{softplus}(z) - y\,z, \qquad \frac{\partial L}{\partial z} = \sigma(z) - y .

This is the K=2K = 2 case of softmax loss with z=z1−z0z = z_1 - z_0 and the loss of logistic regression, where z=w⊤x+bz = \vb{w}\T\vb{x} + b: the likelihood of a Bernoulli model with probability σ(w⊤x+b)\sigma(\vb{w}\T\vb{x} + b). For example, with z=2z = 2 and y=1y = 1, L=softplus⁡(2)−2=0.127L = \operatorname{softplus}(2) - 2 = 0.127 and gradient σ(2)−1=−0.119\sigma(2) - 1 = -0.119. The function is convex in (w,b)(\vb{w}, b) (Hessian ∑iσ(zi)(1−σ(zi)) xixi⊤⪰0\sum_i \sigma(z_i)(1 - \sigma(z_i))\,\vb{x}_i\vb{x}_i\T \succeq 0) and is minimized with optimization-module methods. If data are linearly separable, no finite minimum exists: weights grow without bound, the same overconfidence as in the first figure.

Numerical stability: never compute log⁡(softmax⁡(z))\log(\softmax(z))

Definition −log⁡(ezy/∑jezj)-\log\big(e^{z_y}/\sum_j e^{z_j}\big) is mathematically impeccable but numerically dangerous, because in floating point (floating-point representation) the range of eze^z is narrow: eze^z overflows to ∞\infty at z≈88.72z \approx 88.72 in float32 and at z≈709.78z \approx 709.78 in float64 (special values and subnormals). Two distinct failures occur.

  • Overflow. With logits (1000,0,−1000)(1000, 0, -1000), e1000=∞e^{1000} = \infty and naive softmax computes ∞/∞=NaN\infty/\infty = \mathrm{NaN} for the first class and 1/∞=01/\infty = 0 for the rest: loss becomes NaN or ∞\infty depending on the correct class, and gradient NaN.
  • Underflow and logarithm of zero. With logits (−120,0)(-120, 0) in float32, e−120e^{-120} is smaller than the smallest subnormal and becomes exactly 00; correct-class softmax is 00 and log⁡0=−∞\log 0 = -\infty, although the true value is −120.0-120.0. Infinite loss and a NaN gradient propagating to all weights.

The solution is the log-sum-exp trick. For any constant mm, ∑jezj=em∑jezj−m\sum_j e^{z_j} = e^m\sum_j e^{z_j - m}, and hence with m=max⁡kzkm = \max_k z_k,

logsumexp⁡(z)=m+log⁡∑jezj−m,log⁡softmax⁡(z)k=zk−logsumexp⁡(z).\operatorname{logsumexp}(z) = m + \log\sum_j e^{z_j - m}, \qquad \log\softmax(z)_k = z_k - \operatorname{logsumexp}(z).

The largest exponent is now e0=1e^0 = 1, the sum lies between 11 and KK, and neither overflows nor gives log⁡0\log 0; terms that vanish through underflow were already irrelevant (the sum is already at least 11). This is what log_softmax and F.cross_entropy do, and why loss is calculated directly from logits, in a single fused operation, never by chaining softmax, logarithm and selection. The same principle explains binary_cross_entropy_with_logits: softplus⁡(z)−yz=max⁡(z,0)−yz+log⁡(1+e−∣z∣)\operatorname{softplus}(z) - yz = \max(z, 0) - yz + \log(1 + e^{-\abs{z}}) does not overflow for any zz.

Implementation from scratch

We start with loss, its analytic gradient and a finite-difference check, and the two failures of the naive version.

[ ]log_softmax, loss and gradient, and failures of the naive versionBrowser
import numpy as np

def logsumexp(z):
    m = z.max(axis=-1, keepdims=True)
    return (m + np.log(np.exp(z - m).sum(axis=-1, keepdims=True)))[..., 0]

def log_softmax(z):
    return z - logsumexp(z)[..., None]

def perdida(z, y):
    """Entropía cruzada media (en nats) de logits z (B, K) y etiquetas enteras y (B,)."""
    return -log_softmax(z)[np.arange(len(y)), y].mean()

def gradiente(z, y):
    """dL/dz = (softmax(z) - one_hot(y)) / B."""
    q = np.exp(log_softmax(z))
    q[np.arange(len(y)), y] -= 1.0
    return q / len(y)

# 1) el ejemplo del texto: logits (2, 1, 0) y clase correcta la primera
z = np.array([[2.0, 1.0, 0.0]]); y = np.array([0])
print("pérdida:", round(perdida(z, y), 4), "  gradiente:", np.round(gradiente(z, y)[0], 4))

# 2) el gradiente analítico frente a diferencias finitas centradas
rng = np.random.default_rng(0)
Z = rng.normal(size=(5, 4)) * 2
Y = rng.integers(0, 4, size=5)
G = gradiente(Z, Y)
Gnum = np.zeros_like(Z)
h = 1e-6
for i in range(Z.shape[0]):
    for k in range(Z.shape[1]):
        Zp, Zm = Z.copy(), Z.copy()
        Zp[i, k] += h
        Zm[i, k] -= h
        Gnum[i, k] = (perdida(Zp, Y) - perdida(Zm, Y)) / (2 * h)
print("error máximo del gradiente analítico:", f"{np.abs(G - Gnum).max():.1e}")

# 3) la versión ingenua: softmax, logaritmo y selección por separado
def perdida_ingenua(z, y):
    q = np.exp(z) / np.exp(z).sum(axis=-1, keepdims=True)
    return -np.log(q[np.arange(len(y)), y]).mean()

with np.errstate(all="ignore"):
    z_grande = np.array([[1000.0, 0.0, -1000.0]])
    print("logits (1000, 0, -1000), clase 1:  ingenua =", perdida_ingenua(z_grande, np.array([1])), " estable =", perdida(z_grande, np.array([1])))
    z32 = np.array([[-120.0, 0.0]], dtype=np.float32)
    print("float32, logits (-120, 0), clase 0: ingenua =", perdida_ingenua(z32, np.array([0])), " estable =", perdida(z32.astype(float), np.array([0])))
print("exp desborda en z =", round(float(np.log(np.finfo(np.float32).max)), 2), "(float32) y", round(float(np.log(np.finfo(np.float64).max)), 2), "(float64)")

Loss for (2,1,0)(2, 1, 0) with the first class correct is 0.40760.4076 nats, and gradient (−0.3348,0.2447,0.0900)(-0.3348, 0.2447, 0.0900) sums to zero and is exactly q−eyq - e_y. The naive version returns inf in both cases, by different routes: in the first, softmax is ∞/∞=NaN\infty/\infty = \mathrm{NaN} for the class with logit 10001000 and 1/∞=01/\infty = 0 for the requested class, whose logarithm is −∞-\infty; in the second, e−120e^{-120} underflows to 00 in float32. The stable version returns 10001000 and 120120, the correct values. Now a real model: softmax regression on scikit-learn digits (17971797 images of 8×88 \times 8, ten classes), using the loss and gradient just written. To give the problem a unique minimum we add penalty ℓ2\ell_2 on weights (not bias), the same used by LogisticRegression with C=1C = 1.

[ ]Softmax regression with custom gradient descent versus scikit-learnBrowser
import numpy as np
from sklearn.datasets import load_digits

d = load_digits()
X, y = d.data / 16.0, d.target
Xtr, ytr, Xte, yte = X[:1200], y[:1200], X[1200:], y[1200:]
n, K = len(ytr), 10
lam = 1.0 / n                    # penalización l2 equivalente a C = 1

def fg(theta, X=Xtr, y=ytr):
    """Pérdida penalizada y su gradiente; theta = (W aplanada, b)."""
    W, b = theta[:64 * K].reshape(64, K), theta[64 * K:]
    lp = log_softmax(X @ W + b)
    f = -lp[np.arange(len(y)), y].mean() + 0.5 * lam * (W ** 2).sum()
    G = np.exp(lp)
    G[np.arange(len(y)), y] -= 1.0
    G /= len(y)
    return f, np.concatenate([(X.T @ G + lam * W).ravel(), G.sum(axis=0)])

theta = np.zeros(64 * K + K)
for paso in range(301):
    f, g = fg(theta)
    if paso in (0, 10, 50, 100, 300):
        print(f"paso {paso:3d}: pérdida = {f:.4f}")
    theta -= 2.0 * g             # descenso por gradiente con paso 2
print("el descenso es lento: la pérdida penalizada óptima es menor (ver abajo)")

Gradient descent reduces loss rapidly at first (2.303=ln⁡102.303 = \ln 10 at step 00, as predicted by an indifferent model’s initial value) and then drags: the problem is ill-conditioned. To reach the minimum, the same fg (function and its analytic gradient) can be passed to an approximate second-order optimizer, L-BFGS, and compared with LogisticRegression and log_loss.

[ ]The same function with L-BFGS versus LogisticRegression and log_lossBrowser
import numpy as np
from scipy.optimize import minimize
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss

res = minimize(fg, np.zeros(64 * K + K), jac=True, method="L-BFGS-B", options=dict(maxiter=500, ftol=1e-14, gtol=1e-9))
W, b = res.x[:64 * K].reshape(64, K), res.x[64 * K:]
print(f"L-BFGS: {res.nit} iteraciones, pérdida penalizada = {res.fun:.5f}")

clf = LogisticRegression(C=1.0, max_iter=2000, tol=1e-10).fit(Xtr, ytr)
print("scikit-learn: diferencia máxima de pesos =", f"{np.abs(clf.coef_.T - W).max():.1e}", " de sesgos =", f"{np.abs(clf.intercept_ - b).max():.1e}")

Q = np.exp(log_softmax(Xte @ W + b))
print("pérdida en test, la nuestra:", round(float(-np.log(Q[np.arange(len(yte)), yte]).mean()), 5),
      " sklearn.metrics.log_loss:", round(float(log_loss(yte, Q)), 5))
print("exactitud en test:", round(float((Q.argmax(axis=1) == yte).mean()), 4), " (sklearn:", round(float(clf.score(Xte, yte)), 4), ")")

With the same objective, L-BFGS and scikit-learn reach the same weights up to rounding (differences from 10−610^{-6} to 10−510^{-5}), and log_loss matches our loss: the library has no magic, it has the same cross entropy. The last cell previews the following sections by simulation: scoring rules, calibration decomposition and the horse race.

[ ]Logarithmic scoring, calibration and Kelly simulationsBrowser
import numpy as np
rng = np.random.default_rng(0)

# 1) pérdida esperada de declarar q cuando la verdad es p = 0.7, para tres reglas
p = 0.7
q = np.linspace(0.001, 0.999, 999)
reglas = {
    "logarítmica": -(p * np.log(q) + (1 - p) * np.log(1 - q)),
    "Brier": p * (1 - q) ** 2 + (1 - p) * q ** 2,
    "lineal": 1 - (p * q + (1 - p) * (1 - q)),
}
for nombre, L in reglas.items():
    print(f"{nombre:12s} mínimo en q = {q[L.argmin()]:.3f}   pérdida con q = p: {L[np.argmin(np.abs(q - p))]:.4f}   con q = 0.999: {L[-1]:.4f}")

# 2) calibración: el pronosticador declara siempre 0.9, pero el suceso ocurre el 70 % de las veces
F, tasa = 0.9, 0.7
Y = rng.random(200_000) < tasa
total = -(Y * np.log(F) + (~Y) * np.log(1 - F)).mean()
klb = lambda a, b: a * np.log(a / b) + (1 - a) * np.log((1 - a) / (1 - b))
refin = -(tasa * np.log(tasa) + (1 - tasa) * np.log(1 - tasa))
print(f"pérdida medida = {total:.4f};  calibración + refinamiento = {klb(tasa, F):.4f} + {refin:.4f} = {klb(tasa, F) + refin:.4f}")

# 3) Kelly: cuotas 4 por 1, p = (1/2, 1/4, 1/8, 1/8); crecimiento medio en bits por carrera
pk = np.array([1 / 2, 1 / 4, 1 / 8, 1 / 8])
carreras = rng.choice(4, size=400_000, p=pk)
def crecimiento(b):
    with np.errstate(divide="ignore"):
        return np.mean(np.log2(b[carreras] * 4))
b18 = pk ** 1.8 / np.sum(pk ** 1.8)
print("Kelly b = p:          medido", round(crecimiento(pk), 4), " teoría", 0.25)
print("creencia b ∝ p^1.8:   medido", round(crecimiento(b18), 4), " teoría", round(float(np.sum(pk * np.log2(pk / 0.25)) - np.sum(pk * np.log2(pk / b18))), 4))
print("b = mercado (uniforme):  medido", round(crecimiento(np.full(4, 0.25)), 4))
print("todo al favorito:      medido", crecimiento(np.array([1.0, 0, 0, 0])), " (probabilidad de sobrevivir 20 carreras: 2^-20 =", 2.0 ** -20, ")")

# 4) información lateral: un soplo Y que acierta el ganador con probabilidad 0.7 (y falla repartido en 0.1 por caballo)
Pxy = np.array([[pk[x] * (0.7 if x == yv else 0.1) for yv in range(4)] for x in range(4)])
py = Pxy.sum(axis=0)
info = float(np.sum(Pxy * np.log2(Pxy / np.outer(pk, py))))
x = rng.choice(4, size=400_000, p=pk)
yv = np.array([rng.choice(4, p=[0.7 if k == xi else 0.1 for k in range(4)]) for xi in x[:20_000]])
b_dado_y = Pxy / py                      # b(x | y) = p(x | y), columnas indexadas por y
print("I(X;Y) =", round(info, 4), "bits;  crecimiento sin soplo 0.25, con soplo", round(0.25 + info, 4),
      " medido en 20 000 carreras:", round(float(np.mean(np.log2(4 * b_dado_y[x[:20_000], yv]))), 4))

Two observations. In (1), logarithmic and Brier rules attain their minimum at q=p=0.7q = p = 0.7, while the linear rule’s minimum is q=0.999q = 0.999: it rewards exaggeration. In (3), simulation recovers Kelly’s slope 0.250.25 and the biased-belief slope 0.1120.112, and shows that betting like the market itself (b=rb = r) gains nothing.

Logarithmic scoring and calibration

So far loss has trained models. Another use is evaluating probabilistic predictions from a model, meteorologist or prediction market. A scoring rule assigns a penalty S(q,y)S(q, y) to prediction qq and outcome yy (lower is better). If reality has distribution pp, expected penalty is S(q,p)=EY∼p[S(q,Y)]S(q, p) = \E_{Y \sim p}[S(q, Y)]. The rule is proper if telling the truth is optimal, S(p,p)≤S(q,p)S(p, p) \le S(q, p) for all qq, and strictly proper if its only optimum is q=pq = p. This ensures no one profits by lying.

Proof

S(q,p)=∑yp(y)(−log⁡q(y))=H(p,q)S(q, p) = \sum_y p(y)(-\log q(y)) = H(p, q) by definition, and by the decomposition theorem H(p,q)−H(p,p)=KL⁡(p ∥ q)H(p, q) - H(p, p) = \KL(p\,\|\,q), nonnegative and zero only if p=qp = q (Gibbs). If qq gives zero probability to a possible outcome, expected loss is +∞+\infty.

∎

It is not the only one. The Brier score S(q,y)=∑k(qk−1[k=y])2S(q, y) = \sum_k (q_k - \ind[k = y])^2 is also strictly proper, and its excess is a squared distance: since Ep[(qk−1[Y=k])2]=(qk−pk)2+pk(1−pk)\E_p[(q_k - \ind[Y = k])^2] = (q_k - p_k)^2 + p_k(1 - p_k), expected loss is ∑k(qk−pk)2+∑kpk(1−pk)\sum_k(q_k - p_k)^2 + \sum_k p_k(1 - p_k), with unique minimum at q=pq = p. By contrast, the linear rule S(q,y)=1−q(y)S(q, y) = 1 - q(y) is not proper: expected loss 1−∑kpkqk1 - \sum_k p_k q_k is linear in qq and minimized at vertex earg⁡max⁡pe_{\arg\max p}. It pays to exaggerate to the extreme. Nor, strictly speaking, is a rule rewarding only correct prediction of the most likely class: any qq putting the majority class on the correct side gives the same expected loss.

InteractiveLying does not pay
Logarithmic−ln q(y)01200.51reported probability qBrier(q − 1[y=1])²00.5100.51reported probability qLinear1 − q(y)00.5100.51reported probability q
  • true pp
  • reported qq
  • ★ best possible qq
  • vertical axis: expected loss (lower is better)
0.70
0.95
Logarithmic: your qq / truth0.935 / 0.611
Brier: your qq / truth0.273 / 0.210
Linear: your qq / truth0.320 / 0.420
With q=0.95q = 0.95 you gain 0.100 under the linear rule (exaggeration pays), but lose 0.324 nats under logarithmic and 0.063 under Brier. Only the latter two are proper.
You know true probability pp of an event and report qq (magenta line, draggable in any of the three panels). Each panel plots a rule's expected loss; the star marks the best possible qq. Start with p=0.7p = 0.7 and q=0.95q = 0.95: which rules let you win by lying? Drag qq to pp. Press ‘Exaggerate to the extreme’. Then play 200 rounds and compare actual averages with expected ones: is the benefit of lying visible in the linear rule?

The figure uses binary Brier score (q−1[y=1])2(q - \ind[y = 1])^2, half the sum over two classes. With p=0.7p = 0.7, telling the truth costs 0.6110.611 nats under the logarithmic rule, 0.210.21 under Brier and 0.420.42 under the linear rule. Reporting q=1q = 1 costs ∞\infty under the first (the opposite event occurs with probability 0.30.3), 0.30.3 under the second and 0.30.3 under the third: only the linear rule rewards the lie. And reporting q=0.9q = 0.9 costs 0.1540.154 extra under logarithmic scoring, KL⁡(Bern(0.7) ∥ Bern(0.9))\KL(\mathrm{Bern}(0.7)\,\|\,\mathrm{Bern}(0.9)), and 0.040.04 extra under Brier, (0.7−0.9)2(0.7 - 0.9)^2.

Calibration: what loss actually measures

A forecaster is calibrated if it rains on 70% of days they say “70%”. Log loss mixes two things that can be separated.

Proof

Condition on F=fF = f. Expected loss is H(Bern(π(f)),Bern(f))=H⁡(Bern(π(f)))+KL⁡(Bern(π(f)) ∥ Bern(f))H(\mathrm{Bern}(\pi(f)), \mathrm{Bern}(f)) = \Ent(\mathrm{Bern}(\pi(f))) + \KL(\mathrm{Bern}(\pi(f))\,\|\,\mathrm{Bern}(f)) by the decomposition theorem. Averaging over FF gives first summand H⁡(Y∣F)\Ent(Y \mid F) and second the calibration error. It is zero if and only if π(f)=f\pi(f) = f for almost every ff (Gibbs).

∎

In words: log loss is calibration error plus residual uncertainty. The first is fixed by recalibration (replacing FF by π(F)\pi(F) reduces loss by exactly that term); the second measures how informative predictions are and cannot improve without new information. For a forecaster always reporting 0.90.9 when the true rate is 0.70.7, expected loss is 0.76450.7645 nats, decomposed into 0.15370.1537 calibration (KL⁡(Bern(0.7) ∥ Bern(0.9))\KL(\mathrm{Bern}(0.7)\,\|\,\mathrm{Bern}(0.9))) and 0.61090.6109 refinement (entropy of a coin with bias 0.70.7, since FF is constant). Low loss does not imply good calibration: two models with equal loss can split it very differently, and a highly accurate network can be systematically overconfident, as seen with hard labels.

Soft targets: label smoothing and distillation

Loss H(p,q)H(p, q) is linear in its first argument, so mixing targets equals mixing losses. Label smoothing uses target pε=(1−ε) ey+ε up_\varepsilon = (1 - \varepsilon)\,e_y + \varepsilon\,u, with u=(1/K,…,1/K)u = (1/K, \dots, 1/K) uniform over KK classes (PyTorch’s convention). By linearity,

Lε=H(pε,q)=(1−ε) H(ey,q)+ε H(u,q)=(1−ε) (logsumexp⁡(z)−zy)+ε (logsumexp⁡(z)−zˉ),L_\varepsilon = H(p_\varepsilon, q) = (1 - \varepsilon)\, H(e_y, q) + \varepsilon\, H(u, q) = (1 - \varepsilon)\,\big(\operatorname{logsumexp}(z) - z_y\big) + \varepsilon\,\big(\operatorname{logsumexp}(z) - \bar z\big),

with zˉ=1K∑kzk\bar z = \frac1K\sum_k z_k the mean logit. Gradient is q−pεq - p_\varepsilon. The minimum is no longer at infinity: it occurs at q=pεq = p_\varepsilon, with finite margin between the correct class and each other class

zy−zk=ln⁡1−ε+ε/Kε/K=ln⁡(1+K(1−ε)ε),por ejemplo, K=10, ε=0.1: ln⁡91=4.51,z_y - z_k = \ln\frac{1 - \varepsilon + \varepsilon/K}{\varepsilon/K} = \ln\Big(1 + \frac{K(1 - \varepsilon)}{\varepsilon}\Big), \qquad \text{por ejemplo, } K = 10,\ \varepsilon = 0.1:\ \ln 91 = 4.51,

and floor H⁡(pε)=0.500\Ent(p_\varepsilon) = 0.500 nats. This is what the first figure shows when ε\varepsilon is increased and training repeated: the margin stops growing and stabilizes. Müller, Kornblith and Hinton (2019) study its effects: it often improves calibration and groups each class’s representations into compact clusters; but it erases information about which classes resemble each other still carried by logits of a hard-label-trained model.

This leads to distillation. A student is trained on the teacher’s soft distribution softmax⁡(zmaestro/T)\softmax(z_{\text{maestro}}/T), with temperature T>1T > 1 enhancing small probabilities, by minimizing

T2 H(pT,qT),pT=softmax⁡(zmaestro/T),qT=softmax⁡(zalumno/T)T^2\,H\big(p^T, q^T\big), \qquad p^T = \softmax(z_{\text{maestro}}/T), \quad q^T = \softmax(z_{\text{alumno}}/T)

(Hinton et al., 2015). Factor T2T^2 maintains gradient scale: with respect to student logits, that of H(pT,qT)H(p^T, q^T) is (qT−pT)/T(q^T - p^T)/T, and for large TT the difference qT−pTq^T - p^T itself is order 1/T1/T, so without the factor the gradient would decay like 1/T21/T^2. This loss is often mixed with hard-label loss. The teacher’s soft distribution carries exactly the class-similarity information label smoothing erases, so training the teacher with label smoothing harms the student (Müller et al., 2019). For any soft target, F.cross_entropy also accepts target probabilities.

Log-optimal betting: Kelly and the value of information

There is a third, economic reading of the same loss. A race has mm horses; winner XX has distribution pp and races are independent. A bookmaker pays oio_i for each unit bet on horse ii if it wins (“oio_i to 1”). You have wealth 11 and distribute it all, betting fraction bi≥0b_i \ge 0 on horse ii with ∑ibi=1\sum_i b_i = 1. If XX wins, wealth is multiplied by bX oXb_X\, o_X. Odds are summarized by implied probabilities ri=1/oir_i = 1/o_i; with fair odds, ∑iri=1\sum_i r_i = 1 and rr is a distribution: the market’s belief. After nn races, wealth is Sn=∏t≤nbXt oXtS_n = \prod_{t \le n} b_{X_t}\,o_{X_t}, and what matters is its growth rate W(b,p)=E[log⁡2(bXoX)]=∑ipilog⁡2(bioi)W(b, p) = \E[\log_2 (b_X o_X)] = \sum_i p_i\log_2(b_i o_i) in bits per race, because by the strong law of large numbers 1nlog⁡2Sn→W(b,p)\frac1n\log_2 S_n \to W(b, p) almost surely: Sn≈2nWS_n \approx 2^{nW}.

Proof

Write bioi=bipi⋅pi⋅oib_i o_i = \frac{b_i}{p_i}\cdot p_i \cdot o_i and distribute the logarithm: W=∑ipilog⁡bipi+∑ipilog⁡pi+∑ipilog⁡oi=−KL⁡(p ∥ b)−H⁡(p)+∑ipilog⁡oiW = \sum_i p_i\log\frac{b_i}{p_i} + \sum_i p_i\log p_i + \sum_i p_i\log o_i = -\KL(p\,\|\,b) - \Ent(p) + \sum_i p_i\log o_i. Since oi=1/rio_i = 1/r_i, ∑ipilog⁡oi=−∑ipilog⁡ri=H⁡(p)+KL⁡(p ∥ r)\sum_i p_i\log o_i = -\sum_i p_i \log r_i = \Ent(p) + \KL(p\,\|\,r), and substitution gives W=KL⁡(p ∥ r)−KL⁡(p ∥ b)W = \KL(p\,\|\,r) - \KL(p\,\|\,b). The first term does not depend on bb and KL⁡(p ∥ b)≥0\KL(p\,\|\,b) \ge 0 with equality only at b=pb = p (Gibbs). For the ratio, 1nlog⁡2Sn(b)Sn(b′)→W(b,p)−W(b′,p)\frac1n\log_2\frac{S_n(b)}{S_n(b')}\to W(b, p) - W(b', p) almost surely.

∎

Four consequences that are surprising at first.

  • The optimal bet does not depend on odds. If you must distribute all your wealth, b=pb = p regardless of what each horse pays; odds only determine how much wealth grows, KL⁡(p ∥ r)\KL(p\,\|\,r).
  • No advantage means no growth. If the market knows the truth (r=pr = p), W∗=0W^\ast = 0. And betting like the market, b=rb = r, leaves wealth unchanged in every race, whatever happens.
  • Maximizing expected wealth is a bad idea. With odds 44 to 1 and p=(12,14,18,18)p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18), betting everything on the favorite multiplies expected wealth by 22 each race (4⋅124 \cdot \tfrac12), versus Kelly’s 4∑pi2=1.3754\sum p_i^2 = 1.375. But the probability of surviving nn races is 2−n2^{-n}: its growth rate is −∞-\infty. Kelly has lower expected wealth but almost surely much greater actual wealth: extremely rare events dominate the arithmetic mean, and real growth is the geometric mean, the logarithm.
  • The calculation is the same as compression. With uniform odds oi=mo_i = m, optimal rate is W∗=log⁡2m−H⁡(p)W^\ast = \log_2 m - \Ent(p): the bet wins exactly what a compressor would save. With p=(12,14,18,18)p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18) and m=4m = 4, that is 2−1.75=0.252 - 1.75 = 0.25 bits per race, and after 500500 races wealth is of order 21252^{125}.
InteractiveKelly horse race
Allocation by horse: truth pp, market rr (pays 1/r1/r per 1), and your belief bb
0.00.51.0horse 1 (favorite)horse 2horse 3horse 4
  • true pp
  • market rr
  • your belief bb
Base-2 log wealth, starting at 1: 16 histories per strategy (thin) and their mean (thick)
−500501001502000100200300400500raceswealth 0 (ruin)
  • Kelly b=pb = p
  • belief b∝pγb \propto p^{\gamma}
  • all on favorite
  • theoretical slope KL⁡(p ∥ r)−KL⁡(p ∥ b)\KL(p\,\|\,r) - \KL(p\,\|\,b)
0.00
1.8
500
KL⁡(p ∥ r)\KL(p\,\|\,r) (edge over market)0.250 bits
KL⁡(p ∥ b)\KL(p\,\|\,b) (cost of your belief)0.138 bits
Kelly, bits/race+0.250 (+0.253)
Your belief, bits/race+0.112 (+0.117)
Favorite, bits/race−∞ (−∞)
Ruined paths (favorite)16 of 16
Kelly slope is KL⁡(p ∥ r)=0.250\KL(p\,\|\,r) = 0.250 bits per race. Your belief loses KL⁡(p ∥ b)=0.138\KL(p\,\|\,b) = 0.138, leaving 0.112. Betting only on the favorite is ruined: 16 of 16 paths have zero wealth.
Four horses with true probabilities pp and market odds rr (approaching pp as α\alpha rises). Three strategies distribute all wealth: Kelly (b=pb = p), your biased belief (b∝pγb \propto p^\gamma, with γ=1\gamma = 1 unbiased), and everything on the favorite. Each thin line is a race history; the thick line is the mean of 16; dashed lines show theoretical slopes KL⁡(p ∥ r)−KL⁡(p ∥ b)\KL(p\,\|\,r) - \KL(p\,\|\,b) for Kelly and your belief (in the readouts, the parenthesized value is slope measured over the 16 histories). Start with initial values and press ‘New races’: how much do paths fluctuate around the slope? Raise γ\gamma until your slope crosses 0. Raise α\alpha to almost 11: what happens to the advantage? Set γ=1\gamma = 1.

With initial values Kelly grows at 0.250.25 bits per race, and belief with γ=1.8\gamma = 1.8 at 0.1120.112: the difference 0.1380.138 is KL⁡(p ∥ b)\KL(p\,\|\,b), the cost of believing something other than truth. At γ=2.5\gamma = 2.5 the slope is already negative (−0.184-0.184): a belief too confident in what it knows loses wealth even while “favoring” good horses, because KL⁡(p ∥ b)\KL(p\,\|\,b) exceeds advantage KL⁡(p ∥ r)=0.25\KL(p\,\|\,r) = 0.25. With γ=0\gamma = 0 and α=0\alpha = 0 (uniform belief, matching a uniform market) slope is exactly 00.

The value of information

Before betting, you receive a tip YY correlated with the winner. What is it worth?

Proof

For each value yy this is the race problem with p(⋅∣y)p(\cdot \mid y), whose solution is b=p(⋅∣y)b = p(\cdot \mid y) and growth, by the previous theorem, is ∑xp(x∣y)log⁡ox−H⁡(X∣Y=y)\sum_x p(x \mid y)\log o_x - \Ent(X \mid Y = y). Averaging over YY, W∗(X∣Y)=∑xp(x)log⁡ox−H⁡(X∣Y)W^\ast(X \mid Y) = \sum_x p(x)\log o_x - \Ent(X \mid Y), and subtracting W∗(X)=∑xp(x)log⁡ox−H⁡(X)W^\ast(X) = \sum_x p(x)\log o_x - \Ent(X) leaves H⁡(X)−H⁡(X∣Y)=I(X;Y)\Ent(X) - \Ent(X \mid Y) = I(X; Y).

∎

This gives mutual information an economic interpretation: each bit of mutual information is worth one more bit of growth rate. A tip identifying the winner with probability 0.70.7 (splitting remaining 0.30.3 as 0.10.1 per horse) has I(X;Y)=0.552I(X; Y) = 0.552 bits in the preceding race and raises rate from 0.250.25 to 0.8020.802 bits per race (the simulation above confirms it).

A practical caution. All this assumes you know pp. Betting with an estimate b^\hat b loses KL⁡(p ∥ b^)\KL(p\,\|\,\hat b) per race, and moderate error can exceed your advantage, as with γ=2.5\gamma = 2.5. Hence practice uses a fraction of Kelly: split between the Kelly and market bets (the latter leaves wealth unchanged), b=(1−λ) r+λ p^b = (1 - \lambda)\,r + \lambda\,\hat p with λ<1\lambda < 1. Some growth is sacrificed for much lower variance and robustness to estimation error. The same criterion sizes financial positions (quantitative finance module), and the betting–compression equivalence returns in lesson 8, where bets help estimate English entropy.

The library version

PyTorch implements all this in a fused, stable function.

FunctionExpectsNotes
F.cross_entropy(input, target, weight=None, ignore_index=-100, reduction='mean', label_smoothing=0.0)logits (B, K) or (B, K, d1, ...); target: int64 indices (B) or float probabilities shaped like inputmean loss across nonignored examples; with weight, the mean divides by the sum of weights, not BB
nn.CrossEntropyLosssame, as a module
F.nll_loss(log_probs, target)log probabilities (output of log_softmax)F.cross_entropy = log_softmax + nll_loss
F.binary_cross_entropy_with_logits(input, target, pos_weight=None)logit and target in [0,1][0, 1]stable softplus⁡(z)−yz\operatorname{softplus}(z) - yz
F.binary_cross_entropy(prob, target)probabilitiesclips log⁡\log to −100-100 and is unstable; avoid it
sklearn.metrics.log_loss(y_true, y_pred, labels=None)probabilities (n, K)in nats; clips probabilities to an ε\varepsilon to avoid returning ∞\infty (its value has changed across versions: fix it if relevant)

In a language model, logits have shape B×T×VB \times T \times V and per-token loss is cross entropy: flatten to (B*T, V) or move the class dimension to position 1 (logits.transpose(1, 2)). Its exponential, eHe^{H} with HH in nats, is perplexity, the effective number of choices between which the model hesitates: KK for a uniform model over KK classes. The next cell reproduces F.cross_entropy with label_smoothing and ignore_index, and binary loss with logits, using the implementations above, and measures discrepancy in float32 and bfloat16. It runs on CPU with tiny tensors.

[ ]Exact agreement with PyTorch (CPU, small tensors)Local GPU
import torch
import torch.nn.functional as F

torch.manual_seed(0)
B, K = 8, 5
z = torch.randn(B, K) * 3
y = torch.randint(0, K, (B,))
y[2] = -100                                   # una posición de relleno, que se ignora

def log_softmax(z):
    s = z - z.max(-1, keepdim=True).values
    return s - s.exp().sum(-1, keepdim=True).log()

def ce_propia(z, y, label_smoothing=0.0, ignore_index=-100):
    lp = log_softmax(z)
    valido = y != ignore_index
    nll = -lp.gather(-1, torch.where(valido, y, torch.zeros_like(y))[:, None])[:, 0]
    unif = -lp.mean(-1)                       # entropía cruzada contra la uniforme
    por_ejemplo = (1 - label_smoothing) * nll + label_smoothing * unif
    return (por_ejemplo * valido).sum() / valido.sum()

for eps in (0.0, 0.1):
    ref, mia = F.cross_entropy(z, y, label_smoothing=eps), ce_propia(z, y, eps)
    print(f"label_smoothing = {eps}: torch = {ref.item():.6f}, la nuestra = {mia.item():.6f}, diferencia = {abs(ref - mia).item():.1e}")

def bce_propia(z, t):
    return (z.clamp(min=0) - z * t + torch.log1p(torch.exp(-z.abs()))).mean()
zb = torch.randn(16) * 4
t = (torch.rand(16) < 0.5).float()
print("binaria con logits: diferencia =", f"{abs(F.binary_cross_entropy_with_logits(zb, t) - bce_propia(zb, t)).item():.1e}")
print("con logits x30:  con logits =", round(F.binary_cross_entropy_with_logits(zb * 30, t).item(), 3), "  sigmoide + binary_cross_entropy =", round(F.binary_cross_entropy(torch.sigmoid(zb * 30), t).item(), 3))

# el gradiente de autograd es (softmax - one_hot) en las posiciones válidas
zl = z.clone().requires_grad_(True)
F.cross_entropy(zl, y, reduction="sum").backward()
v = (y != -100)[:, None]
teorico = (F.softmax(z, -1) - F.one_hot(y.clamp(min=0), K).float()) * v
print("gradiente de autograd frente a softmax - one_hot: diferencia =", f"{(zl.grad - teorico).abs().max().item():.1e}")

# precisión: logits en bfloat16 frente a una referencia en float64
ref64 = ce_propia(z.double(), y)
print("float32 frente a float64:", f"{abs(F.cross_entropy(z, y).double() - ref64).item():.1e}",
      "  bfloat16 frente a float64:", f"{abs(F.cross_entropy(z.bfloat16(), y).double() - ref64).item():.1e}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In float32 discrepancy is of rounding order (10−710^{-7}), and handling of label_smoothing and ignore_index matches ours. With bfloat16 logits (eight precision bits, seven explicit in the mantissa, floating-point representation) loss differs from the reference by about 10−310^{-3}: that is why in mixed-precision training cross entropy is computed in float32 even if logits arrive in bfloat16. The last comparison reminds us why the logits version is used: going through sigmoid and binary_cross_entropy, which clips the logarithm, gives an incorrect value for a very confident prediction.

Common mistakes

Exercises

ProofThe softmax loss gradient
Prove: For L(z,y)=−log⁡softmax⁡(z)yL(z, y) = -\log\softmax(z)_y with z∈RKz \in \R^K, ∂L∂zk=softmax⁡(z)k−1[k=y]\dfrac{\partial L}{\partial z_k} = \softmax(z)_k - \ind[k = y] holds for every kk.
0
Write q=softmax⁡(z)q = \softmax(z) and use logsumexp⁡(z)=log⁡∑jezj\operatorname{logsumexp}(z) = \log\sum_j e^{z_j}.

Step 1 of 3. How do you rewrite loss to differentiate without quotients?

ProofLogarithmic scoring is strictly proper
Prove: For distributions p,qp, q on a finite alphabet, EY∼p[−log⁡q(Y)]\E_{Y\sim p}[-\log q(Y)] is minimized over qq uniquely at q=pq = p.
0
Compare expected loss from reporting qq with that from reporting pp.

Step 1 of 3. What is Ep[−log⁡q(Y)]−Ep[−log⁡p(Y)]\E_{p}[-\log q(Y)] - \E_{p}[-\log p(Y)]?

NumericLoss of one example
A three-class classifier returns logits (2,1,0)(2, 1, 0) and the first class is correct. What is the softmax cross-entropy loss in nats?
NumericLoss of an overconfident forecaster
A forecaster always reports rain probability 0.90.9, but it rains on 70 %70\,\% of days. What is expected log loss per day in nats?
NumericOptimal Kelly growth
A race has 4 horses, each with odds 44 to 1, and true probabilities p=(12,14,18,18)p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18). What is Kelly's optimal logarithmic growth rate in bits per race?
NumericThe value of a tip
With odds and probabilities from the preceding exercise, before each race you receive a tip YY that matches winner XX with probability 0.70.7 and otherwise points to each of the other three horses with probability 0.10.1 (independent of everything else). By how much, in bits per race, does the tip increase optimal growth?
CodeCross entropy with label smoothing
Implement ce_suavizada(z, y, eps), receiving logits z of shape (B, K), integer labels y of shape (B,) and ε∈[0,1)\varepsilon \in [0, 1), and returning mean loss with label smoothing (1−ε) H(ey,q)+ε H(u,q)(1 - \varepsilon)\,H(e_y, q) + \varepsilon\,H(u, q), where uu is uniform over KK classes (the F.cross_entropy(..., label_smoothing=eps) convention), in nats. It must be numerically stable: logits of magnitude 1000 must not give nan or inf.
import numpy as np

def ce_suavizada(z, y, eps):
  """Pérdida media con suavizado de etiquetas, en nats."""
  z = np.asarray(z, dtype=float)
  y = np.asarray(y)
  # tu código: logsumexp estable, entropía cruzada con la etiqueta dura y con la uniforme
  return 0.0
Shift+Enter to run
QuizWhich rules are strictly proper?
For a binary event with true probability pp and reported probability qq, which loss rules (lower is better) are strictly proper?

More than one answer may be correct.

QuizWhat maximum likelihood minimizes
Data come from a mixture of two well-separated bells and the model is a single Gaussian. Which KL direction does maximum-likelihood fitting minimize, and what Gaussian results?

Summary

Key idea
Cross entropy H(p,q)=H⁡(p)+KL⁡(p ∥ q)H(p, q) = \Ent(p) + \KL(p\,\|\,q) is model qq‘s mean surprise at data from pp: a floor you cannot control plus an excess you can. Minimizing it over the model equals maximum likelihood and minimizing forward KL. The same loss is a code length, an honest prediction score (strictly proper) and, in betting, the exponent of wealth growth: KL⁡(p ∥ r)−KL⁡(p ∥ b)\KL(p\,\|\,r) - \KL(p\,\|\,b).
  • Decomposition. H(p,q)=H⁡(p)+KL⁡(p ∥ q)≥H⁡(p)H(p, q) = \Ent(p) + \KL(p\,\|\,q) \ge \Ent(p), equality only if q=pq = p. With hard labels the floor is 00 and reached only with infinite logits (overconfidence); a smoothed target has a finite optimum.
  • Likelihood. −1nlog⁡∏iqθ(yi)=H(p^,qθ)-\frac1n\log\prod_i q_\theta(y_i) = H(\hat p, q_\theta): maximum likelihood, minimum cross entropy and minimum KL⁡(p^ ∥ qθ)\KL(\hat p\,\|\,q_\theta) are the same. When the model cannot represent data, cross entropy “covers” (in exponential families, matches moments); reverse KL “selects a mode”.
  • Softmax and gradient. L(z,y)=logsumexp⁡(z)−zyL(z, y) = \operatorname{logsumexp}(z) - z_y, with ∇zL=softmax⁡(z)−ey\grad_z L = \softmax(z) - e_y: bounded, summing to zero, and not vanishing when the model is confidently wrong, unlike squared error on probabilities. The binary version is softplus⁡(z)−yz\operatorname{softplus}(z) - yz, with gradient σ(z)−y\sigma(z) - y.
  • Stability. Never calculate log⁡(softmax⁡(z))\log(\softmax(z)): subtract the maximum (log-sum-exp) and use log_softmax or F.cross_entropy, which accept logits. Double softmax is a silent error.
  • Scoring and calibration. −log⁡q(y)-\log q(y) is strictly proper with excess KL⁡(p ∥ q)\KL(p\,\|\,q) and is the only local rule for K≥3K \ge 3; log loss is calibration error plus refinement. Brier is also proper; linear is not.
  • Soft targets. H(⋅,q)H(\cdot, q) is linear in its first argument: smoothing =(1−ε)H(ey,q)+εH(u,q)= (1 - \varepsilon)H(e_y, q) + \varepsilon H(u, q), optimal margin ln⁡(1+K(1−ε)/ε)\ln\big(1 + K(1 - \varepsilon)/\varepsilon\big); distillation with T2T^2; smoothing the teacher harms the student.
  • Kelly. With fair odds, W(b,p)=KL⁡(p ∥ r)−KL⁡(p ∥ b)W(b, p) = \KL(p\,\|\,r) - \KL(p\,\|\,b), maximized at b=pb = p; side information YY adds exactly I(X;Y)I(X; Y) bits per race; with estimated pp bet a fraction.