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 \(1\) through \(10\) and apply linear regression directly? Because integer codes for unordered categories are arbitrary names, not numerical quantities: a prediction of \(5.5\) would place a photo halfway between a coat and a sandal, and squared error would penalize mistaking a T-shirt (\(1\)) for an ankle boot (\(10\)) \(81\) times more heavily than mistaking it for a trouser (\(2\)). 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 \(2 \times 2\) grayscale image classification problem with four scalar pixel features \(x_1, x_2, x_3, x_4\) and three categories: cat (\(1\)), chicken (\(2\)), and dog (\(3\)). In general, with \(q\) classes, an example’s label is an integer \(y \in \{1, \ldots, q\}\).
To represent unordered categories without imposing a false numerical ordering, statisticians use a one-hot encoding: a vector \(\mathbf{y} \in \{0, 1\}^q\) with a \(1\) in the coordinate of the true class (\(y_y = 1\)) and \(0\) everywhere else. In our three-class example, a cat is \((1, 0, 0)\), a chicken is \((0, 1, 0)\), and a dog is \((0, 0, 1)\). Every pair of distinct classes now sits at the same Euclidean distance \(\sqrt{2}\), and \(\mathbf{y}\) 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 \(\hat{\mathbf{y}}\). (In equations we use \(1\)-based class index \(y\) and one-hot vector \(\mathbf{y}\); in Python code we store the \(0\)-based integer index directly.)
3.1.1.2 Linear Scores
To score all \(q\) classes simultaneously, softmax regression assigns each class \(j \in \{1, \ldots, q\}\) its own affine function of the input features. Writing \(w_{kj}\) for the weight connecting feature \(k\) to class \(j\) and \(b_j\) for class \(j\)’s bias, our \(2 \times 2\) image classifier computes three unnormalized scores (logits):
\[ \begin{aligned} o_1 &= x_1 w_{11} + x_2 w_{21} + x_3 w_{31} + x_4 w_{41} + b_1,\\ o_2 &= x_1 w_{12} + x_2 w_{22} + x_3 w_{32} + x_4 w_{42} + b_2,\\ o_3 &= x_1 w_{13} + x_2 w_{23} + x_3 w_{33} + x_4 w_{43} + b_3. \end{aligned} \]
Viewed as a neural network (Figure 3.1.1), softmax regression is a single-layer fully connected network with \(d\) inputs and \(q\) output units (\(d \cdot q\) weights and \(q\) biases).
Collecting the weights into a matrix \(\mathbf{W} \in \mathbb{R}^{d \times q}\) (one row per feature, one column \(\mathbf{w}_j \in \mathbb{R}^d\) per class) and the biases into \(\mathbf{b} \in \mathbb{R}^q\), the logit vector for an input \(\mathbf{x} \in \mathbb{R}^d\) is compactly written
\[\mathbf{o} = \mathbf{W}^\top \mathbf{x} + \mathbf{b}, \tag{3.1.1}\]
where \(o_j = \mathbf{w}_j^\top \mathbf{x} + b_j\). On the \(28 \times 28\) Fashion-MNIST clothing images we classify in Section 3.2, \(d = 784\) and \(q = 10\), giving \(7{,}840\) weights and \(10\) biases.
3.1.1.3 The Softmax
Suppose our linear layer outputs the logits \(\mathbf{o} = (1.0, 2.2, 0.3)\) for cat, chicken, and dog. The chicken has the highest score, yet raw logits are not probabilities: they sum to \(3.5\) rather than \(1\), and nothing stops an affine score from turning negative or exceeding \(1\). To convert any real vector \(\mathbf{o} \in \mathbb{R}^q\) into a valid probability distribution \(\hat{\mathbf{y}}\) (\(q\) positive numbers summing to \(1\)) while preserving the ranking of the scores, the softmax function exponentiates each logit and divides by their sum:
\[\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{o}) \quad \textrm{where} \quad \hat{y}_j = \frac{\exp(o_j)}{\sum_{k=1}^q \exp(o_k)}. \tag{3.1.2}\]
For \(\mathbf{o} = (1.0, 2.2, 0.3)\), the exponentials are \((2.72, 9.03, 1.35)\) with sum \(13.09\), giving \(\hat{\mathbf{y}} = (0.21, 0.69, 0.10)\): a \(69\%\) predicted probability for chicken. Because \(\exp\) is strictly increasing, softmax preserves the order of the logits, so the most probable class is always the class with the largest logit:
\[\operatorname*{argmax}_j \hat{y}_j = \operatorname*{argmax}_j o_j. \tag{3.1.3}\]
At inference time, if we only need the top predicted category, we can skip the exponentials altogether and take \(\operatorname{argmax}_j o_j\).
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 \(c\) to every entry of \(\mathbf{o}\) multiplies both numerator and denominator of Equation 3.1.2 by \(\exp(c)\), leaving the probabilities unchanged: \(\mathrm{softmax}(\mathbf{o} + c\mathbf{1}) = \mathrm{softmax}(\mathbf{o})\). Equivalently, the difference between any two logits is the log-odds ratio of their predicted probabilities: \[o_i - o_j = \log \frac{\hat{y}_i}{\hat{y}_j}. \tag{3.1.4}\] In our example, \(o_2 - o_1 = 1.2\), so chicken is \(e^{1.2} \approx 3.3\) times as probable as cat (\(0.69 / 0.21\)). This shift invariance also gives us a critical numerical safeguard (Section 3.3): subtracting \(o_{\max} = \max_k o_k\) before exponentiating prevents floating-point overflow without changing the result.
- Reduction to logistic regression for \(q = 2\): With two classes, the probabilities depend solely on the single difference \(o = o_1 - o_2\): \[\hat{y}_1 = \frac{\exp(o_1)}{\exp(o_1) + \exp(o_2)} = \frac{1}{1 + \exp(-o)} = \sigma(o), \tag{3.1.5}\] where \(\sigma(o)\) is the logistic sigmoid. Two-class softmax regression is thus identical to classic logistic regression, and \(o = \log(\hat{y}_1 / \hat{y}_2)\) is the log-odds—the historical origin of the word logit.
- 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 \(\hat{\mathbf{y}} - \mathbf{y}\).
3.1.1.4 Minibatches
To vectorize over a minibatch of \(n\) examples with \(d\) features, we stack the inputs into \(\mathbf{X} \in \mathbb{R}^{n \times d}\), weights into \(\mathbf{W} \in \mathbb{R}^{d \times q}\), and biases into \(\mathbf{b} \in \mathbb{R}^{1 \times q}\):
\[ \begin{aligned} \mathbf{O} &= \mathbf{X} \mathbf{W} + \mathbf{b},\\ \hat{\mathbf{Y}} &= \mathrm{softmax}(\mathbf{O}), \end{aligned} \tag{3.1.6}\]
where \(\mathbf{b}\) broadcasts across the \(n\) rows of \(\mathbf{O} \in \mathbb{R}^{n \times q}\) and \(\mathrm{softmax}\) is applied rowwise (exponentiating \(\mathbf{O}\) and dividing each row by its own row sum).
3.1.1.5 Decision Regions
Because softmax preserves the ordering of the affine logits \(o_j = \mathbf{w}_j^\top\mathbf{x} + b_j\), softmax regression partitions the input space \(\mathbb{R}^d\) into flat-sided convex polyhedra (Figure 3.1.2). Class \(j\) wins wherever \(o_j \geq o_k\) for all \(k \neq j\), which is the intersection of \(q - 1\) halfspaces \((\mathbf{w}_j - \mathbf{w}_k)^\top\mathbf{x} + (b_j - b_k) \geq 0\), 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).
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 \(\hat{\mathbf{y}}\) and the observed label \(y\)? Following the maximum-likelihood principle of Section 2.1, we interpret \(\hat{y}_j = P(y = j \mid \mathbf{x})\) as the conditional probability of class \(j\). Using the one-hot vector \(\mathbf{y} \in \{0, 1\}^q\), we can write the probability assigned to the observed class \(y\) as
\[P(y \mid \mathbf{x}) = \hat{y}_y = \prod_{j=1}^q \hat{y}_j^{y_j}.\]
Across \(n\) independent training examples, the negative log-likelihood is the sum of per-example losses:
\[ \begin{aligned} -\log \prod_{i=1}^n P(y^{(i)} \mid \mathbf{x}^{(i)}) &= \sum_{i=1}^n l(\mathbf{y}^{(i)}, \hat{\mathbf{y}}^{(i)}), \\ \textrm{where} \quad l(\mathbf{y}, \hat{\mathbf{y}}) &= -\sum_{j=1}^q y_j \log \hat{y}_j = -\log \hat{y}_y. \end{aligned} \tag{3.1.7}\]
This objective is the cross-entropy loss. Notice how it behaves:
- Because \(\hat{y}_y \in (0, 1)\), \(l(\mathbf{y}, \hat{\mathbf{y}}) > 0\) always. It approaches \(0\) as \(\hat{y}_y \to 1\) and diverges to \(+\infty\) as \(\hat{y}_y \to 0\) (heavily penalizing confident mistakes).
- On our image with logits \((1.0, 2.2, 0.3)\) and probabilities \((0.21, 0.69, 0.10)\), if the true label is chicken (\(y = 2\)), the loss is \(-\log 0.69 \approx 0.37\) nats; if the image is actually a dog (\(y = 3\)), the loss jumps sixfold to \(-\log 0.10 \approx 2.30\) nats.
3.1.2.2 The Gradient
Let us differentiate the cross-entropy loss with respect to the logits \(\mathbf{o}\). Substituting Equation 3.1.2 into Equation 3.1.7 and using \(\sum_{j=1}^q y_j = 1\) expresses the loss directly in terms of \(\mathbf{o}\):
\[ \begin{aligned} l(\mathbf{y}, \hat{\mathbf{y}}) &= -\sum_{j=1}^q y_j \log \frac{\exp(o_j)}{\sum_{k=1}^q \exp(o_k)} \\ &= \sum_{j=1}^q y_j \log \sum_{k=1}^q \exp(o_k) - \sum_{j=1}^q y_j o_j \\ &= \log \sum_{k=1}^q \exp(o_k) - o_y. \end{aligned} \]
The first term, \(\log \sum_{k=1}^q \exp(o_k)\), is the log-sum-exp function—a smooth convex upper bound on \(\max_k o_k\) that exceeds \(\max_k o_k\) by at most \(\log q\) (Exercise 4). Differentiating with respect to \(o_j\) gives
\[ \begin{aligned} \frac{\partial l}{\partial o_j} &= \frac{\exp(o_j)}{\sum_{k=1}^q \exp(o_k)} - y_j = \mathrm{softmax}(\mathbf{o})_j - y_j, \\ \textrm{or} \quad \nabla_{\mathbf{o}}\, l &= \hat{\mathbf{y}} - \mathbf{y}. \end{aligned} \]
Just as in linear regression under squared loss, the gradient with respect to the natural parameters \(\mathbf{o}\) is simply prediction minus observation, \(\hat{\mathbf{y}} - \mathbf{y}\) (a universal property of exponential-family generalized linear models; see Section 36.4.3.3). On our chicken image (\(\mathbf{y} = (0, 1, 0)\)), \(\nabla_{\mathbf{o}}\, l = (0.21, -0.31, 0.10)\): 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 \(\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}\), the minibatch gradient with respect to \(\mathbf{W}\) is \(\frac{1}{n}\mathbf{X}^\top(\hat{\mathbf{Y}} - \mathbf{Y})\), and the loss is globally convex in \((\mathbf{W}, \mathbf{b})\) (its Hessian with respect to \(\mathbf{o}\) is the covariance matrix of a categorical draw from \(\hat{\mathbf{y}}\); see Exercise 2).
| Linear regression | Softmax regression | |
|---|---|---|
| Target | continuous \(y \in \mathbb{R}\) | class \(y \in \{1, \ldots, q\}\), one-hot \(\mathbf{y}\) |
| Prediction | \(\hat{y} = \mathbf{w}^\top \mathbf{x} + b\) | \(\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{W}^\top \mathbf{x} + \mathbf{b})\) |
| Probabilistic model | Gaussian \(\mathcal{N}(\hat{y}, \sigma^2)\) | categorical \(\mathrm{Cat}(\hat{\mathbf{y}})\) |
| Loss (NLL) | \(\frac{1}{2}(\hat{y} - y)^2\) | \(-\sum_{j=1}^q y_j \log \hat{y}_j = -\log \hat{y}_y\) |
| Gradient | \(\hat{y} - y\) (w.r.t. \(\hat{y}\)) | \(\hat{\mathbf{y}} - \mathbf{y}\) (w.r.t. \(\mathbf{o}\)) |
3.1.2.3 Entropy and Cross-Entropy
The name cross-entropy comes from Claude Shannon’s information theory (Section 37.1). When an outcome with probability \(p\) occurs, Shannon defined its surprisal (information content) as \(-\log p\) (measured in nats when using natural logarithms, or bits when using \(\log_2\), with \(1\textrm{ nat} = 1/\log 2 \approx 1.44\textrm{ bits}\)). For a true distribution \(\mathbf{p} = (p_1, \ldots, p_q)\) over \(q\) classes, the expected surprisal is its entropy:
\[H(\mathbf{p}) = -\sum_{j=1}^q p_j \log p_j, \tag{3.1.8}\]
which ranges from \(0\) (when one outcome is certain) to \(\log q\) (when all \(q\) outcomes are equally likely). If an observer instead encodes outcomes drawn from \(\mathbf{p}\) using a code optimized for a model distribution \(\hat{\mathbf{p}}\), their average code length (expected surprisal) is the cross-entropy:
\[H(\mathbf{p}, \hat{\mathbf{p}}) = -\sum_{j=1}^q p_j \log \hat{p}_j. \tag{3.1.9}\]
By Gibbs’ inequality, \(H(\mathbf{p}, \hat{\mathbf{p}}) \geq H(\mathbf{p})\) with equality if and only if \(\hat{\mathbf{p}} = \mathbf{p}\) (their gap is the Kullback–Leibler divergence \(D_{\mathrm{KL}}(\mathbf{p} \,\|\, \hat{\mathbf{p}}) = H(\mathbf{p}, \hat{\mathbf{p}}) - H(\mathbf{p}) \geq 0\)). Comparing \(H(\mathbf{p}, \hat{\mathbf{p}})\) with Equation 3.1.7, our per-example loss \(l(\mathbf{y}, \hat{\mathbf{y}}) = H(\mathbf{y}, \hat{\mathbf{y}})\) is literally the cross-entropy between the empirical label distribution \(\mathbf{y}\) and the predicted distribution \(\hat{\mathbf{y}}\). Better still, when an input is inherently ambiguous, say a blurry photo that is \(60\%\) likely to be a shirt and \(40\%\) 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 \((0.6, 0.4)\) 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 \(= 1 - \textrm{accuracy}\)), 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:
\[m = o_y - \max_{j \neq y} o_j. \tag{3.1.10}\]
The classifier makes an error (\(m < 0\)) or a correct prediction (\(m > 0\)) according to a discontinuous step function of \(m\) (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 (\(\log(1 + e^{-m})\) for \(q = 2\)) that upper-bounds the zero-one error (when measured in bits by dividing by \(\log 2\)) and supplies a nonzero gradient for every example.
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 \(m > 0\) and the classification decision is already correct. If a training dataset is linearly separable, meaning some \((\mathbf{W}, \mathbf{b})\) classifies every training example correctly (\(m^{(i)} > 0\) for all \(i\)), then multiplying \((\mathbf{W}, \mathbf{b})\) by any scale factor \(c > 1\) multiplies every margin by \(c\) and drives the training loss toward zero without bound (Exercise 6), pushing all predicted probabilities toward \(0\) and \(1\) without moving the decision boundary at all.
More generally, scaling all logits by the inverse of a positive temperature \(T > 0\) before applying the softmax,
\[\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{o} / T), \tag{3.1.11}\]
sharpens the distribution toward a one-hot argmax as \(T \to 0\) and flattens it toward the uniform distribution \((1/q, \ldots, 1/q)\) as \(T \to \infty\) (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.
3.1.4 Summary
Softmax regression predicts unordered discrete categories by computing one affine logit per class, \(\mathbf{o} = \mathbf{W}^\top\mathbf{x} + \mathbf{b}\), and normalizing them into probabilities \(\hat{y}_j = \exp(o_j)/\sum_k \exp(o_k)\), partitioning input space into convex polyhedral decision regions bounded by hyperplanes. Because the softmax operator depends only on pairwise logit differences \(o_i - o_j = \log(\hat{y}_i/\hat{y}_j)\), it is invariant to uniform shifts of \(\mathbf{o}\) and reduces to binary logistic regression when \(q = 2\). Maximizing the categorical likelihood of one-hot targets \(\mathbf{y}\) yields the convex cross-entropy loss \(l(\mathbf{y}, \hat{\mathbf{y}}) = -\log \hat{y}_y = \log\sum_k \exp(o_k) - o_y\), a smooth upper bound on zero-one classification error whose gradient with respect to the logits collapses to the residual \(\hat{\mathbf{y}} - \mathbf{y}\). Dividing the logits by a temperature \(T > 0\) 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 Equation 3.1.5, logistic regression is softmax regression with two classes and one redundant logit removed. A colleague hands you a fitted logistic model \(P(y = 1 \mid x) = \sigma(\hat\beta_0 + \hat\beta_1 x)\) with \(\hat\beta_0 = 2\) and \(\hat\beta_1 = -1\).
- Characterize all two-class softmax coefficients \((w_1, b_1)\) and \((w_2, b_2)\) whose predictions coincide with the logistic model for every \(x\), and identify the pair with \(o_2 \equiv 0\).
- Show that gradient descent on the cross-entropy loss of the two-class softmax model never changes \(w_1 + w_2\) or \(b_1 + b_2\). Suppose that gradient descent starts from \(w_1 = w_2 = b_1 = b_2 = 0\) 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, \(l(\mathbf{y}, \mathbf{o}) = g(\mathbf{o}) - \mathbf{y}^\top \mathbf{o}\) with \(g(\mathbf{o}) = \log \sum_k \exp(o_k)\).
- Compute the Hessian \(\partial^2_{\mathbf{o}}\, l(\mathbf{y}, \mathbf{o})\) and show that it does not depend on \(\mathbf{y}\).
- Let \(\mathbf{e}_Y\) be the one-hot vector of a class \(Y\) drawn from \(\mathrm{softmax}(\mathbf{o})\). Compute the covariance matrix of \(\mathbf{e}_Y\) and show that it equals the Hessian from the previous step.
- Conclude that \(g\) 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, \(o_{\textrm{apple}}\) and \(o_{\textrm{orange}}\). Now add a default option of choosing neither, with a fixed score \(o_{\textrm{none}} = 0\).
- Determine whether adding the same constant to \(o_{\textrm{apple}}\) and \(o_{\textrm{orange}}\) 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 \(P(\textrm{apple}) / P(\textrm{orange})\) 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 \(\mathrm{lse}(a, b) = \log(\exp(a) + \exp(b))\) is the log-sum-exp of Section 3.1.2.2 with two arguments, so its gradient is the softmax of \((a, b)\).
- Prove that \[\max(a, b) < \mathrm{lse}(a, b) \leq \max(a, b) + \log 2, \tag{3.1.12}\] with equality on the right exactly when \(a = b\), and show that the gap to \(\max(a, b)\) can be made arbitrarily small. Hint: without loss of generality set \(b = 0\) and \(a \geq 0\).
- Prove that for every \(\lambda > 0\) \[\max(a, b) < \lambda^{-1} \mathrm{lse}(\lambda a, \lambda b) \leq \max(a, b) + \lambda^{-1} \log 2, \tag{3.1.13}\] and conclude that \(\lambda^{-1} \mathrm{lse}(\lambda a, \lambda b) \to \max(a, b)\) as \(\lambda \to \infty\).
- Construct an analogous smooth minimum.
- Extend the definition and both bounds to \(q\) numbers, showing that the gap to \(\max_i a_i\) is at most \(\log q\).
Temperature. Let \(P = \mathrm{softmax}(\mathbf{o})\), and let the distribution at temperature \(T\) be \(\mathrm{softmax}(\mathbf{o}/T)\). Suppose we pick another distribution \(Q\) with \(Q(i) \propto P(i)^\alpha\) for \(\alpha > 0\).
- Which choice of \(\alpha\) corresponds to doubling the temperature? Which choice corresponds to halving it?
- Suppose that exactly \(s\) of the \(q\) logits attain the largest value. Find the limit of \(\mathrm{softmax}(\mathbf{o}/T)\) as \(T \to 0\).
- Let \(\bar{o} = \frac{1}{q}\sum_j o_j\) be the mean logit. Show that for large \(T\) \[\mathrm{softmax}(\mathbf{o}/T)_i = \frac{1}{q} + \frac{o_i - \bar{o}}{qT} + O(T^{-2}). \tag{3.1.14}\]
- Temperature scaling fits a single \(T\) 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 \(\beta = 1/T\), so that the fit is a one-dimensional convex problem. Hint: use the convexity of \(g\) from exercise 2.
Separable data. ● Suppose that some parameters \((\mathbf{W}, \mathbf{b})\) 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 \((c\mathbf{W}, c\mathbf{b})\) for \(c > 0\).
- Show that the cross-entropy loss of every training example strictly decreases as \(c\) grows and tends to \(0\) as \(c \to \infty\).
- Conclude that the training loss has no minimizer and that every sequence of parameters whose training loss tends to \(0\) has unbounded norm.
- Add the weight decay penalty of Section 2.7, applied to both weights and biases, \(\frac{\lambda}{2}(\|\mathbf{W}\|^2 + \|\mathbf{b}\|^2)\) with \(\lambda > 0\), 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 \(\frac{1}{2}\|\hat{\mathbf{y}} - \mathbf{y}\|^2\).
- Show that the derivatives of the softmax are \(\partial \hat{y}_k / \partial o_j = \hat{y}_k(\mathbf{1}(j = k) - \hat{y}_j)\), 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 \(m\) and compute their derivatives with respect to \(m\). Show that as \(m \to -\infty\), that is, for a confident mistake, the derivative of the squared loss tends to 0 while that of the cross-entropy tends to \(-1\).
- 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, \(y = \operatorname*{argmax}_i \, (o_i + \gamma_i)\). Gaussian noise gives the probit model, whose class probabilities have no closed form; one other noise distribution reproduces the softmax probabilities exactly. Let \(\gamma_1, \ldots, \gamma_q\) be i.i.d. draws from the standard Gumbel distribution, whose CDF is \(P(\gamma \leq z) = \exp(-\exp(-z))\).
- Show that \(P(o_k + \gamma_k \leq z) = \exp(-\exp(o_k)\exp(-z))\).
- Show that \(P\left(\operatorname{argmax}_i \, (o_i + \gamma_i) = k\right) = \mathrm{softmax}(\mathbf{o})_k\). Hint: condition on the value of \(o_k + \gamma_k\) and use the substitution \(u = \exp(-z)\).
- Conclude that scaling the noise, \(\gamma_i \mapsto T\gamma_i\), samples from \(\mathrm{softmax}(\mathbf{o}/T)\).
- Verify your result numerically: for \(\mathbf{o} = (1.0, 2.2, 0.3)\) and \(T \in \{0.25, 1, 4\}\), draw \(10^5\) samples of \(\operatorname{argmax}_i (o_i + T\gamma_i)\) and confirm that the label frequencies match \(\mathrm{softmax}(\mathbf{o}/T)\) up to Monte Carlo error.