3.1 Softmax Regression
Regression is the tool we reach for when answering how much? or how many? questions. Many supervised learning problems, however, ask which category? instead: a spam filter sorts email into two classes, a clinical tool chooses among candidate diagnoses, and a language model predicts the next token from a vocabulary of tens of thousands of words.
Suppose an online retailer wants to sort product photos into ten apparel categories: T-shirt, trouser, pullover, dress, coat, sandal, shirt, sneaker, bag, and ankle boot. Why not number those categories through and apply linear regression directly? Because integer codes for unordered categories are arbitrary names, not numerical quantities: a prediction of would place a photo halfway between a coat and a sandal, and squared error would penalize mistaking a T-shirt () for an ankle boot () times more heavily than mistaking it for a trouser (). Moreover, even when we ultimately need a hard assignment (picking a single category), we almost always want a model that outputs soft assignments (a calibrated probability for every candidate class) so downstream decisions can weigh confidence against the cost of a mistake.
Softmax regression (also called multinomial logistic regression) solves both problems cleanly: it computes one affine score per class and maps those scores into a valid probability distribution via the softmax operator. Following the maximum-likelihood recipe of Section 2.1, minimizing the negative log-likelihood of the observed categories yields the cross-entropy loss.
3.1.1 The Model#
3.1.1.1 Class Labels#
Let us start with a concrete grayscale image classification problem with four scalar pixel features and three categories: cat (), chicken (), and dog (). In general, with classes, an example's label is an integer .
To represent unordered categories without imposing a false numerical ordering, statisticians use a one-hot encoding: a vector with a in the coordinate of the true class () and everywhere else. In our three-class example, a cat is , a chicken is , and a dog is . Every pair of distinct classes now sits at the same Euclidean distance , and is itself a valid probability distribution—the degenerate distribution placing all of its mass on the true class—which we can compare directly against our model's predicted distribution . (In equations we use -based class index and one-hot vector ; in Python code we store the -based integer index directly.)
3.1.1.2 Linear Scores#
To score all classes simultaneously, softmax regression assigns each class its own affine function of the input features. Writing for the weight connecting feature to class and for class 's bias, our image classifier computes three unnormalized scores (logits):
Viewed as a neural network (Figure 3.1.1), softmax regression is a single-layer fully connected network with inputs and output units ( weights and biases).
Softmax regression as a single-layer fully connected neural network. Each input connects to each output logit through weight .
Collecting the weights into a matrix (one row per feature, one column per class) and the biases into , the logit vector for an input is compactly written
where . On the Fashion-MNIST clothing images we classify in Section 3.2, and , giving weights and biases.
3.1.1.3 The Softmax#
Suppose our linear layer outputs the logits for cat, chicken, and dog. The chicken has the highest score, yet raw logits are not probabilities: they sum to rather than , and nothing stops an affine score from turning negative or exceeding . To convert any real vector into a valid probability distribution ( positive numbers summing to ) while preserving the ranking of the scores, the softmax function exponentiates each logit and divides by their sum:
For , the exponentials are with sum , giving : a predicted probability for chicken. Because is strictly increasing, softmax preserves the order of the logits, so the most probable class is always the class with the largest logit:
At inference time, if we only need the top predicted category, we can skip the exponentials altogether and take .
Why use the exponential rather than some other positive increasing function? Because exponentials turn addition into multiplication, endowing the softmax with three foundational properties:
- Shift invariance (only differences between logits matter): Adding any scalar constant to every entry of multiplies both numerator and denominator of (3.1.2) by , leaving the probabilities unchanged: . Equivalently, the difference between any two logits is the log-odds ratio of their predicted probabilities:
In our example, , so chicken is times as probable as cat (). This shift invariance also gives us a critical numerical safeguard (Section 3.3): subtracting before exponentiating prevents floating-point overflow without changing the result. 2. Reduction to logistic regression for : With two classes, the probabilities depend solely on the single difference :
where is the logistic sigmoid. Two-class softmax regression is thus identical to classic logistic regression, and is the log-odds—the historical origin of the word logit. 3. Clean gradients under maximum likelihood: As we show below, the exponential in the softmax pairs with the logarithm in the likelihood so that the gradient of the loss collapses to the residual .
3.1.1.4 Minibatches#
To vectorize over a minibatch of examples with features, we stack the inputs into , weights into , and biases into :
where broadcasts across the rows of and is applied rowwise (exponentiating and dividing each row by its own row sum).
3.1.1.5 Decision Regions#
Because softmax preserves the ordering of the affine logits , softmax regression partitions the input space into flat-sided convex polyhedra (Figure 3.1.2). Class wins wherever for all , which is the intersection of halfspaces , and neighboring classes meet along the hyperplane where their two logits tie. Just as in linear regression, boundaries between classes are always flat hyperplanes; carving curved or non-convex decision regions requires hidden layers (Chapter 4).
Decision regions of softmax regression in . Left: with three classes, the plane splits into three convex regions meeting along the lines where pairs of logits tie. Right: with two classes, contours of constant probability are parallel lines perpendicular to , with the decision boundary at .
Keep in mind our core structural assumption: each example belongs to exactly one class from an unordered set. When multiple tags can apply to the same input simultaneously (multi-label classification), one uses an independent binary sigmoid per tag rather than a competing softmax (Tsoumakas and Katakis, 2007); when classes follow a natural rank order (ordinal regression), specialized threshold models exploit that ordering (Moon et al., 2010).
3.1.2 The Cross-Entropy Loss#
3.1.2.1 Maximum Likelihood#
How should we measure the discrepancy between our predicted probability distribution and the observed label ? Following the maximum-likelihood principle of Section 2.1, we interpret as the conditional probability of class . Using the one-hot vector , we can write the probability assigned to the observed class as
Across independent training examples, the negative log-likelihood is the sum of per-example losses:
This objective is the cross-entropy loss. Notice how it behaves:
- Because , always. It approaches as and diverges to as (heavily penalizing confident mistakes).
- On our image with logits and probabilities , if the true label is chicken (), the loss is nats; if the image is actually a dog (), the loss jumps sixfold to nats.
3.1.2.2 The Gradient#
Let us differentiate the cross-entropy loss with respect to the logits . Substituting (3.1.2) into (3.1.7) and using expresses the loss directly in terms of :
The first term, , is the log-sum-exp function—a smooth convex upper bound on that exceeds by at most (Exercise 4). Differentiating with respect to gives
Just as in linear regression under squared loss, the gradient with respect to the natural parameters is simply prediction minus observation, (a universal property of exponential-family generalized linear models; see Section 24.4.3.3). On our chicken image (), : one gradient descent step boosts the chicken's logit while pushing down the cat and dog logits in exact proportion to the probability mass each rival wrongly claimed. By the chain rule through , the minibatch gradient with respect to is , and the loss is globally convex in (its Hessian with respect to is the covariance matrix of a categorical draw from ; see Exercise 2).
| Linear regression | Softmax regression | |
|---|---|---|
| Target | continuous | class , one-hot |
| Prediction | ||
| Probabilistic model | Gaussian | categorical |
| Loss (NLL) | ||
| Gradient | (w.r.t. ) | (w.r.t. ) |
3.1.2.3 Entropy and Cross-Entropy#
The name cross-entropy comes from Claude Shannon's information theory (Section 25.1). When an outcome with probability occurs, Shannon defined its surprisal (information content) as (measured in nats when using natural logarithms, or bits when using , with ). For a true distribution over classes, the expected surprisal is its entropy:
which ranges from (when one outcome is certain) to (when all outcomes are equally likely). If an observer instead encodes outcomes drawn from using a code optimized for a model distribution , their average code length (expected surprisal) is the cross-entropy:
By Gibbs' inequality, with equality if and only if (their gap is the Kullback--Leibler divergence ). Comparing with (3.1.7), our per-example loss is literally the cross-entropy between the empirical label distribution and the predicted distribution . Better still, when an input is inherently ambiguous, say a blurry photo that is likely to be a shirt and likely to be a T-shirt, Gibbs' inequality guarantees that the expected cross-entropy loss is uniquely minimized when the model reports the true calibrated probabilities rather than an overconfident guess.
3.1.3 Accuracy and Confidence#
3.1.3.1 The Error Rate#
Although we evaluate classifiers by accuracy (or error rate ), we cannot train by differentiating the zero-one error directly. Define the margin of an example as its true class's logit minus the highest competing logit:
The classifier makes an error () or a correct prediction () according to a discontinuous step function of (Figure 3.1.3) whose derivative is zero everywhere it exists, starving gradient descent of any learning signal. Cross-entropy replaces that flat step with a smooth, strictly decreasing convex surrogate ( for ) that upper-bounds the zero-one error (when measured in bits by dividing by ) and supplies a nonzero gradient for every example.
Zero-one classification error and two-class cross-entropy loss (in bits, ) as functions of the margin .
3.1.3.2 Calibration and Temperature#
Notice one consequence of the smooth curve in Figure 3.1.3: cross-entropy keeps decreasing even after and the classification decision is already correct. If a training dataset is linearly separable, meaning some classifies every training example correctly ( for all ), then multiplying by any scale factor multiplies every margin by and drives the training loss toward zero without bound (Exercise 6), pushing all predicted probabilities toward and without moving the decision boundary at all.
More generally, scaling all logits by the inverse of a positive temperature before applying the softmax,
sharpens the distribution toward a one-hot argmax as and flattens it toward the uniform distribution as (Figure 3.1.4), while leaving the ranking of the logits (and therefore the classifier's accuracy) unchanged. Whether a trained model's predicted probabilities match true empirical accuracy (calibration) is an empirical question we test on held-out data in Section 3.4.
Softmax probabilities for logits at three temperatures: (peaked), (standard softmax), and (nearly uniform).
3.1.4 Summary#
Softmax regression predicts unordered discrete categories by computing one affine logit per class, , and normalizing them into probabilities , partitioning input space into convex polyhedral decision regions bounded by hyperplanes. Because the softmax operator depends only on pairwise logit differences , it is invariant to uniform shifts of and reduces to binary logistic regression when . Maximizing the categorical likelihood of one-hot targets yields the convex cross-entropy loss , a smooth upper bound on zero-one classification error whose gradient with respect to the logits collapses to the residual . Dividing the logits by a temperature tunes prediction confidence between a deterministic argmax and a uniform distribution without altering class rankings or accuracy.
3.1.5 Exercises#
-
Softmax and sigmoid. By (3.1.5), logistic regression is softmax regression with two classes and one redundant logit removed. A colleague hands you a fitted logistic model with and .
- Characterize all two-class softmax coefficients and whose predictions coincide with the logistic model for every , and identify the pair with .
- Show that gradient descent on the cross-entropy loss of the two-class softmax model never changes or . Suppose that gradient descent starts from on the colleague's training data and converges to coefficients that reproduce the logistic model. Determine which pair it reaches.
Adapted from James, Witten, Hastie, and Tibshirani, An Introduction to Statistical Learning, Exercise 4.12.
-
Softmax Hessian. As in Section 3.1.2.2, write the cross-entropy loss as a function of the logits, with .
- Compute the Hessian and show that it does not depend on .
- Let be the one-hot vector of a class drawn from . Compute the covariance matrix of and show that it equals the Hessian from the previous step.
- Conclude that is convex and that the cross-entropy loss is convex in the logits.
-
Bradley--Terry model. The Bradley--Terry model (Bradley and Terry, 1952) uses a logistic model to capture preferences. A user who chooses between apples and oranges picks each item with the probability given by the softmax of two scores, and . Now add a default option of choosing neither, with a fixed score .
- Determine whether adding the same constant to and changes the choice probabilities, first without and then with the default option. Conclude which scores the observed choices can determine in each model.
- Compare the ratio with and without the default option. Describe a choice situation in which real users would not keep this ratio fixed.
-
Log-sum-exp. The function is the log-sum-exp of Section 3.1.2.2 with two arguments, so its gradient is the softmax of .
- Prove that
with equality on the right exactly when , and show that the gap to can be made arbitrarily small. Hint: without loss of generality set and .
- Prove that for every
and conclude that as .
- Construct an analogous smooth minimum.
- Extend the definition and both bounds to numbers, showing that the gap to is at most .
- Temperature. Let , and let the
distribution at temperature be .
Suppose we pick another distribution with
for .
- Which choice of corresponds to doubling the temperature? Which choice corresponds to halving it?
- Suppose that exactly of the logits attain the largest value. Find the limit of as .
- Let be the mean logit. Show that for large
- Temperature scaling fits a single by minimizing the cross-entropy on a held-out set with the logits of the classifier held fixed. Show that this cross-entropy is a convex function of , so that the fit is a one-dimensional convex problem. Hint: use the convexity of from exercise 2.
-
Separable data. ● Suppose that some parameters classify every training example correctly and without ties: on each example, the logit of the true class strictly exceeds every other logit. Consider the scaled parameters for .
- Show that the cross-entropy loss of every training example strictly decreases as grows and tends to as .
- Conclude that the training loss has no minimizer and that every sequence of parameters whose training loss tends to has unbounded norm.
- Add the weight decay penalty of Section 2.7, applied to both weights and biases, with , to the training loss. Show that the penalized loss has a minimizer.
-
Squared error on probabilities. Instead of cross-entropy, we could fit the predicted probabilities to the one-hot label with the squared loss .
- Show that the derivatives of the softmax are , and use them to compute the gradient of the squared loss with respect to the logits.
- For two classes, write both losses as functions of the margin and compute their derivatives with respect to . Show that as , that is, for a confident mistake, the derivative of the squared loss tends to 0 while that of the cross-entropy tends to .
- Explain what this difference means for a model that starts training with confident wrong predictions.
-
[code] Gumbel-max trick. ● Suppose that a label is generated by perturbing every logit with independent noise and reporting the class with the largest perturbed score, . Gaussian noise gives the probit model, whose class probabilities have no closed form; one other noise distribution reproduces the softmax probabilities exactly. Let be i.i.d. draws from the standard Gumbel distribution, whose CDF is .
- Show that .
- Show that . Hint: condition on the value of and use the substitution .
- Conclude that scaling the noise, , samples from .
- Verify your result numerically: for and , draw samples of and confirm that the label frequencies match up to Monte Carlo error.