CodeRigor

LESSON

Empirical risk, softmax and cross-entropy

Why training minimizes an average loss over samples, why that loss cannot be the error count, and a stable softmax cross-entropy with its gradient.

Training a classifier means choosing weights that make a loss small, so the loss decides what the gradient can see, what the network is rewarded for and whether the arithmetic stays finite. This lesson pairs with Lecture 3 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build a stable softmax cross-entropy with its gradient, plus an error counter to compare it with.

What you want is a low expected loss on data the model has not seen. Write ℓ for the loss of one prediction. The risk is R(θ) = E[ℓ(f(x; θ), y)], an expectation over the distribution that produces examples. You never see that distribution, only N samples from it, so training minimizes the empirical risk: the average R̂(θ) = (1/N) Σᵢ ℓ(f(xᵢ; θ), yᵢ). For weights fixed before looking at the samples, R̂ is an unbiased estimate of R. Trained weights are chosen after looking at them, to make that very average small, so the training average is optimistic. A held-out set that never influenced the weights gives an honest estimate again.

The most natural score for a classifier is its error count, but it cannot be minimized by gradient descent. It is a step function of the weights: nudge a weight slightly and almost every prediction stays the same, so the count stays the same and the slope is zero. The run below keeps a single example whose label is class 0 while the scores are (w, 3). The error is 1 for all three values of w, yet the cross-entropy falls as w grows and so tells you which way to move.

Python
import numpy as np

for w in (-2.0, 0.0, 2.0):
    logits = np.array([w, 3.0])
    p = np.exp(logits - logits.max())
    p /= p.sum()
    print(w, int(logits.argmax() != 0), round(-np.log(p[0]), 4))   # w, error, loss

So the loss is a differentiable divergence between the network's output and the target. Softmax turns the C scores (logits) of one example into a distribution, pⱼ = exp(zⱼ) / Σₖ exp(zₖ): every pⱼ is positive and they sum to 1. The cross-entropy of an example with label t is −log pₜ, and the loss is its mean over the N examples. A probability of 1 costs 0, a probability of 0.5 costs 0.6931, and 0.01 costs 4.6052. The cost grows without bound as p shrinks, so a confident wrong answer is punished hard. Equal scores give pⱼ = 1/C and a loss of log C, which is 2.3026 for C = 10.

The price of the right answer
−log p against the probability p given to the correct class. Equal scores over 10 classes give p = 0.1 and a loss of 2.3026.
The price of the right answer
−log p against the probability p given to the correct class. Equal scores over 10 classes give p = 0.1 and a loss of 2.3026.

Floating point adds one more demand. In float64, exp(709) is finite and exp(710) is inf, so scores in the thousands overflow and the ratio becomes inf / inf = nan. Softmax does not change when you add the same constant c to every score of a row, because the factor exp(c) cancels from top and bottom. Subtract the row's maximum m: the largest shifted score is 0, so no exp exceeds 1 and the sum is at least 1. Then work with log-probabilities, log pⱼ = (zⱼ − m) − log Σₖ exp(zₖ − m), and never take the log of a probability that may have underflowed to 0.

Python
import numpy as np

z = np.array([1002.0, 1001.0, 1000.0])
with np.errstate(all="ignore"):
    print(np.exp(z) / np.exp(z).sum())                  # naive: inf / inf
s = z - z.max()
p = np.exp(s) / np.exp(s).sum()
print(np.round(p, 4), round(-np.log(p[0]), 4))           # shifted: fine
One row, step by step
start / 5
Three scores around 1000 with label 0, computed with the stable recipe. The gradient is p − onehot, here with N = 1.
One row, step by step
Three scores around 1000 with label 0, computed with the stable recipe. The gradient is p − onehot, here with N = 1.

The gradient of the loss with respect to the logits is (p − y) / N, where y is the one-hot label and the 1/N belongs to the mean. It is the error itself: the entry at the label is p − 1, which pushes that score up, and every other entry is its own probability, which pushes it down. Each row sums to 0. Compare squared error E = ½‖p − y‖² applied to the softmax output. Its gradient is (diag(p) − ppᵀ)(p − y), and the matrix in front shrinks to zero as softmax saturates. The run takes one example with label 0 and the scores (−g, g), so the wrong class wins and the larger g is, the more confident the mistake.

Python
import numpy as np

y = np.array([1.0, 0.0])
for g in (0.0, 2.0, 8.0):
    z = np.array([-g, g])
    p = np.exp(z - z.max())
    p /= p.sum()
    ce = (p - y)[0]
    se = ((np.diag(p) - np.outer(p, p)) @ (p - y))[0]
    print(g, round(ce, 4), f"{se:.2e}")   # gradient at the label's score

As the mistake becomes more confident, the cross-entropy gradient at the label's score approaches −1, while the squared-error gradient falls toward 0: squared error nearly goes silent exactly when the model needs the most correction.

Three mistakes show up again and again. The first is exponentiating raw scores, or subtracting one maximum for the whole batch: a row far below that maximum then shifts so far that every exp underflows to 0, the row's sum is 0, and its loss is no longer finite. Use the maximum of each row. The second is dividing by N × C, the number of entries, instead of N, the number of examples. Every gradient comes out C times too small, which behaves like a learning rate C times too small. The third is indexing: a label of −1 silently selects the last class in NumPy, and a tie in error_rate must go to the lowest index, which is what np.argmax returns.

The tests compare your log-softmax, loss and gradient with PyTorch's log_softmax and cross_entropy, and with the gradient autograd computes, in float64. They also check hand-worked rows, scores of ±5000 and gradient rows that sum to zero. That shows your code computes the function you meant. It does not show that cross-entropy is the right objective for your task, or that a low training loss means a low risk: that is what the held-out set is for. Loss and error rate can also move differently, so watch both.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The lecture this lesson is built around: learning a network by minimizing a loss averaged over training samples, and the choice of a differentiable divergence between output and target. Watch it first, then build the loss and its gradient here.

A recitation on common loss functions. Useful after the lecture if you want a second walk through squared error versus cross-entropy and what each one asks of the network.