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 11 through 1010 and apply linear regression directly? Because integer codes for unordered categories are arbitrary names, not numerical quantities: a prediction of 5.55.5 would place a photo halfway between a coat and a sandal, and squared error would penalize mistaking a T-shirt (11) for an ankle boot (1010) 8181 times more heavily than mistaking it for a trouser (22). 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×22 \times 2 grayscale image classification problem with four scalar pixel features x1,x2,x3,x4x_1, x_2, x_3, x_4 and three categories: cat (11), chicken (22), and dog (33). In general, with qq classes, an example's label is an integer y∈{1,…,q}y \in \{1, \ldots, q\}.

To represent unordered categories without imposing a false numerical ordering, statisticians use a one-hot encoding: a vector y∈{0,1}q\mathbf{y} \in \{0, 1\}^q with a 11 in the coordinate of the true class (yy=1y_y = 1) and 00 everywhere else. In our three-class example, a cat is (1,0,0)(1, 0, 0), a chicken is (0,1,0)(0, 1, 0), and a dog is (0,0,1)(0, 0, 1). Every pair of distinct classes now sits at the same Euclidean distance 2\sqrt{2}, and y\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 y^\hat{\mathbf{y}}. (In equations we use 11-based class index yy and one-hot vector y\mathbf{y}; in Python code we store the 00-based integer index directly.)

3.1.1.2 Linear Scores#

To score all qq classes simultaneously, softmax regression assigns each class j∈{1,…,q}j \in \{1, \ldots, q\} its own affine function of the input features. Writing wkjw_{kj} for the weight connecting feature kk to class jj and bjb_j for class jj's bias, our 2×22 \times 2 image classifier computes three unnormalized scores (logits):

o1=x1w11+x2w21+x3w31+x4w41+b1,o2=x1w12+x2w22+x3w32+x4w42+b2,o3=x1w13+x2w23+x3w33+x4w43+b3.\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 dd inputs and qq output units (d⋅qd \cdot q weights and qq biases).

Figure 3.1.1:

Softmax regression as a single-layer fully connected neural network. Each input xkx_k connects to each output logit ojo_j through weight wkjw_{kj}.

Collecting the weights into a matrix W∈Rd×q\mathbf{W} \in \mathbb{R}^{d \times q} (one row per feature, one column wj∈Rd\mathbf{w}_j \in \mathbb{R}^d per class) and the biases into b∈Rq\mathbf{b} \in \mathbb{R}^q, the logit vector for an input x∈Rd\mathbf{x} \in \mathbb{R}^d is compactly written

o=W⊤x+b,(3.1.1)\mathbf{o} = \mathbf{W}^\top \mathbf{x} + \mathbf{b}, \tag{3.1.1}

where oj=wj⊤x+bjo_j = \mathbf{w}_j^\top \mathbf{x} + b_j. On the 28×2828 \times 28 Fashion-MNIST clothing images we classify in Section 3.2, d=784d = 784 and q=10q = 10, giving 7,8407{,}840 weights and 1010 biases.

3.1.1.3 The Softmax#

Suppose our linear layer outputs the logits o=(1.0,2.2,0.3)\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.53.5 rather than 11, and nothing stops an affine score from turning negative or exceeding 11. To convert any real vector o∈Rq\mathbf{o} \in \mathbb{R}^q into a valid probability distribution y^\hat{\mathbf{y}} (qq positive numbers summing to 11) while preserving the ranking of the scores, the softmax function exponentiates each logit and divides by their sum:

y^=softmax(o)wherey^j=exp⁡(oj)∑k=1qexp⁡(ok).(3.1.2)\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 o=(1.0,2.2,0.3)\mathbf{o} = (1.0, 2.2, 0.3), the exponentials are (2.72,9.03,1.35)(2.72, 9.03, 1.35) with sum 13.0913.09, giving y^=(0.21,0.69,0.10)\hat{\mathbf{y}} = (0.21, 0.69, 0.10): a 69%69\% predicted probability for chicken. Because exp⁡\exp is strictly increasing, softmax preserves the order of the logits, so the most probable class is always the class with the largest logit:

argmax⁡jy^j=argmax⁡joj.(3.1.3)\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 argmax⁡joj\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:

  1. Shift invariance (only differences between logits matter): Adding any scalar constant cc to every entry of o\mathbf{o} multiplies both numerator and denominator of (3.1.2) by exp⁡(c)\exp(c), leaving the probabilities unchanged: softmax(o+c1)=softmax(o)\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:
oi−oj=log⁡y^iy^j.(3.1.4)o_i - o_j = \log \frac{\hat{y}_i}{\hat{y}_j}. \tag{3.1.4}

In our example, o2−o1=1.2o_2 - o_1 = 1.2, so chicken is e1.2≈3.3e^{1.2} \approx 3.3 times as probable as cat (0.69/0.210.69 / 0.21). This shift invariance also gives us a critical numerical safeguard (Section 3.3): subtracting omax⁡=max⁡koko_{\max} = \max_k o_k before exponentiating prevents floating-point overflow without changing the result. 2. Reduction to logistic regression for q=2q = 2: With two classes, the probabilities depend solely on the single difference o=o1−o2o = o_1 - o_2:

y^1=exp⁡(o1)exp⁡(o1)+exp⁡(o2)=11+exp⁡(−o)=σ(o),(3.1.5)\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 σ(o)\sigma(o) is the logistic sigmoid. Two-class softmax regression is thus identical to classic logistic regression, and o=log⁡(y^1/y^2)o = \log(\hat{y}_1 / \hat{y}_2) 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 y^−y\hat{\mathbf{y}} - \mathbf{y}.

3.1.1.4 Minibatches#

To vectorize over a minibatch of nn examples with dd features, we stack the inputs into X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d}, weights into W∈Rd×q\mathbf{W} \in \mathbb{R}^{d \times q}, and biases into b∈R1×q\mathbf{b} \in \mathbb{R}^{1 \times q}:

O=XW+b,Y^=softmax(O),(3.1.6)\begin{aligned} \mathbf{O} &= \mathbf{X} \mathbf{W} + \mathbf{b},\\ \hat{\mathbf{Y}} &= \mathrm{softmax}(\mathbf{O}), \end{aligned} \tag{3.1.6}

where b\mathbf{b} broadcasts across the nn rows of O∈Rn×q\mathbf{O} \in \mathbb{R}^{n \times q} and softmax\mathrm{softmax} is applied rowwise (exponentiating O\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 oj=wj⊤x+bjo_j = \mathbf{w}_j^\top\mathbf{x} + b_j, softmax regression partitions the input space Rd\mathbb{R}^d into flat-sided convex polyhedra (Figure 3.1.2). Class jj wins wherever oj≥oko_j \geq o_k for all k≠jk \neq j, which is the intersection of q−1q - 1 halfspaces (wj−wk)⊤x+(bj−bk)≥0(\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).

Figure 3.1.2:

Decision regions of softmax regression in R2\mathbb{R}^2. 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 y^1=σ(o)\hat{y}_1 = \sigma(o) are parallel lines perpendicular to w1−w2\mathbf{w}_1 - \mathbf{w}_2, with the decision boundary at y^1=1/2\hat{y}_1 = 1/2.

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 y^\hat{\mathbf{y}} and the observed label yy? Following the maximum-likelihood principle of Section 2.1, we interpret y^j=P(y=j∣x)\hat{y}_j = P(y = j \mid \mathbf{x}) as the conditional probability of class jj. Using the one-hot vector y∈{0,1}q\mathbf{y} \in \{0, 1\}^q, we can write the probability assigned to the observed class yy as

P(y∣x)=y^y=∏j=1qy^jyj.P(y \mid \mathbf{x}) = \hat{y}_y = \prod_{j=1}^q \hat{y}_j^{y_j}.

Across nn independent training examples, the negative log-likelihood is the sum of per-example losses:

−log⁡∏i=1nP(y(i)∣x(i))=∑i=1nl(y(i),y^(i)),wherel(y,y^)=−∑j=1qyjlog⁡y^j=−log⁡y^y.(3.1.7)\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 y^y∈(0,1)\hat{y}_y \in (0, 1), l(y,y^)>0l(\mathbf{y}, \hat{\mathbf{y}}) > 0 always. It approaches 00 as y^y→1\hat{y}_y \to 1 and diverges to +∞+\infty as y^y→0\hat{y}_y \to 0 (heavily penalizing confident mistakes).
  • On our image with logits (1.0,2.2,0.3)(1.0, 2.2, 0.3) and probabilities (0.21,0.69,0.10)(0.21, 0.69, 0.10), if the true label is chicken (y=2y = 2), the loss is −log⁡0.69≈0.37-\log 0.69 \approx 0.37 nats; if the image is actually a dog (y=3y = 3), the loss jumps sixfold to −log⁡0.10≈2.30-\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 o\mathbf{o}. Substituting (3.1.2) into (3.1.7) and using ∑j=1qyj=1\sum_{j=1}^q y_j = 1 expresses the loss directly in terms of o\mathbf{o}:

l(y,y^)=−∑j=1qyjlog⁡exp⁡(oj)∑k=1qexp⁡(ok)=∑j=1qyjlog⁡∑k=1qexp⁡(ok)−∑j=1qyjoj=log⁡∑k=1qexp⁡(ok)−oy.\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⁡∑k=1qexp⁡(ok)\log \sum_{k=1}^q \exp(o_k), is the log-sum-exp function—a smooth convex upper bound on max⁡kok\max_k o_k that exceeds max⁡kok\max_k o_k by at most log⁡q\log q (Exercise 4). Differentiating with respect to ojo_j gives

∂l∂oj=exp⁡(oj)∑k=1qexp⁡(ok)−yj=softmax(o)j−yj,or∇o l=y^−y.\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 o\mathbf{o} is simply prediction minus observation, y^−y\hat{\mathbf{y}} - \mathbf{y} (a universal property of exponential-family generalized linear models; see Section 24.4.3.3). On our chicken image (y=(0,1,0)\mathbf{y} = (0, 1, 0)), ∇o l=(0.21,−0.31,0.10)\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 O=XW+b\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}, the minibatch gradient with respect to W\mathbf{W} is 1nX⊤(Y^−Y)\frac{1}{n}\mathbf{X}^\top(\hat{\mathbf{Y}} - \mathbf{Y}), and the loss is globally convex in (W,b)(\mathbf{W}, \mathbf{b}) (its Hessian with respect to o\mathbf{o} is the covariance matrix of a categorical draw from y^\hat{\mathbf{y}}; see Exercise 2).

Linear regressionSoftmax regression
Targetcontinuous y∈Ry \in \mathbb{R}class y∈{1,…,q}y \in \{1, \ldots, q\}, one-hot y\mathbf{y}
Predictiony^=w⊤x+b\hat{y} = \mathbf{w}^\top \mathbf{x} + by^=softmax(W⊤x+b)\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{W}^\top \mathbf{x} + \mathbf{b})
Probabilistic modelGaussian N(y^,σ2)\mathcal{N}(\hat{y}, \sigma^2)categorical Cat(y^)\mathrm{Cat}(\hat{\mathbf{y}})
Loss (NLL)12(y^−y)2\frac{1}{2}(\hat{y} - y)^2−∑j=1qyjlog⁡y^j=−log⁡y^y-\sum_{j=1}^q y_j \log \hat{y}_j = -\log \hat{y}_y
Gradienty^−y\hat{y} - y (w.r.t. y^\hat{y})y^−y\hat{\mathbf{y}} - \mathbf{y} (w.r.t. o\mathbf{o})

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 pp occurs, Shannon defined its surprisal (information content) as −log⁡p-\log p (measured in nats when using natural logarithms, or bits when using log⁡2\log_2, with 1 nat=1/log⁡2≈1.44 bits1\textrm{ nat} = 1/\log 2 \approx 1.44\textrm{ bits}). For a true distribution p=(p1,…,pq)\mathbf{p} = (p_1, \ldots, p_q) over qq classes, the expected surprisal is its entropy:

H(p)=−∑j=1qpjlog⁡pj,(3.1.8)H(\mathbf{p}) = -\sum_{j=1}^q p_j \log p_j, \tag{3.1.8}

which ranges from 00 (when one outcome is certain) to log⁡q\log q (when all qq outcomes are equally likely). If an observer instead encodes outcomes drawn from p\mathbf{p} using a code optimized for a model distribution p^\hat{\mathbf{p}}, their average code length (expected surprisal) is the cross-entropy:

H(p,p^)=−∑j=1qpjlog⁡p^j.(3.1.9)H(\mathbf{p}, \hat{\mathbf{p}}) = -\sum_{j=1}^q p_j \log \hat{p}_j. \tag{3.1.9}

By Gibbs' inequality, H(p,p^)≥H(p)H(\mathbf{p}, \hat{\mathbf{p}}) \geq H(\mathbf{p}) with equality if and only if p^=p\hat{\mathbf{p}} = \mathbf{p} (their gap is the Kullback--Leibler divergence DKL(p ∥ p^)=H(p,p^)−H(p)≥0D_{\mathrm{KL}}(\mathbf{p} \,\|\, \hat{\mathbf{p}}) = H(\mathbf{p}, \hat{\mathbf{p}}) - H(\mathbf{p}) \geq 0). Comparing H(p,p^)H(\mathbf{p}, \hat{\mathbf{p}}) with (3.1.7), our per-example loss l(y,y^)=H(y,y^)l(\mathbf{y}, \hat{\mathbf{y}}) = H(\mathbf{y}, \hat{\mathbf{y}}) is literally the cross-entropy between the empirical label distribution y\mathbf{y} and the predicted distribution y^\hat{\mathbf{y}}. Better still, when an input is inherently ambiguous, say a blurry photo that is 60%60\% likely to be a shirt and 40%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)(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−accuracy= 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=oy−max⁡j≠yoj.(3.1.10)m = o_y - \max_{j \neq y} o_j. \tag{3.1.10}

The classifier makes an error (m<0m \lt 0) or a correct prediction (m>0m > 0) according to a discontinuous step function of mm (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)\log(1 + e^{-m}) for q=2q = 2) that upper-bounds the zero-one error (when measured in bits by dividing by log⁡2\log 2) and supplies a nonzero gradient for every example.

Figure 3.1.3:

Zero-one classification error and two-class cross-entropy loss (in bits, log⁡2(1+e−m)\log_2(1 + e^{-m})) as functions of the margin m=oy−max⁡j≠yojm = o_y - \max_{j \neq y} o_j.

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>0m > 0 and the classification decision is already correct. If a training dataset is linearly separable, meaning some (W,b)(\mathbf{W}, \mathbf{b}) classifies every training example correctly (m(i)>0m^{(i)} > 0 for all ii), then multiplying (W,b)(\mathbf{W}, \mathbf{b}) by any scale factor c>1c > 1 multiplies every margin by cc and drives the training loss toward zero without bound (Exercise 6), pushing all predicted probabilities toward 00 and 11 without moving the decision boundary at all.

More generally, scaling all logits by the inverse of a positive temperature T>0T > 0 before applying the softmax,

y^=softmax(o/T),(3.1.11)\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{o} / T), \tag{3.1.11}

sharpens the distribution toward a one-hot argmax as T→0T \to 0 and flattens it toward the uniform distribution (1/q,…,1/q)(1/q, \ldots, 1/q) as T→∞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.

Figure 3.1.4:

Softmax probabilities for logits o=(1.0,2.2,0.3)\mathbf{o} = (1.0, 2.2, 0.3) at three temperatures: T=0.25T = 0.25 (peaked), T=1T = 1 (standard softmax), and T=4T = 4 (nearly uniform).

3.1.4 Summary#

Softmax regression predicts unordered discrete categories by computing one affine logit per class, o=W⊤x+b\mathbf{o} = \mathbf{W}^\top\mathbf{x} + \mathbf{b}, and normalizing them into probabilities y^j=exp⁡(oj)/∑kexp⁡(ok)\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 oi−oj=log⁡(y^i/y^j)o_i - o_j = \log(\hat{y}_i/\hat{y}_j), it is invariant to uniform shifts of o\mathbf{o} and reduces to binary logistic regression when q=2q = 2. Maximizing the categorical likelihood of one-hot targets y\mathbf{y} yields the convex cross-entropy loss l(y,y^)=−log⁡y^y=log⁡∑kexp⁡(ok)−oyl(\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 y^−y\hat{\mathbf{y}} - \mathbf{y}. Dividing the logits by a temperature T>0T > 0 tunes prediction confidence between a deterministic argmax and a uniform distribution without altering class rankings or accuracy.

3.1.5 Exercises#

  1. 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 P(y=1∣x)=σ(β^0+β^1x)P(y = 1 \mid x) = \sigma(\hat\beta_0 + \hat\beta_1 x) with β^0=2\hat\beta_0 = 2 and β^1=−1\hat\beta_1 = -1.

    1. Characterize all two-class softmax coefficients (w1,b1)(w_1, b_1) and (w2,b2)(w_2, b_2) whose predictions coincide with the logistic model for every xx, and identify the pair with o2≡0o_2 \equiv 0.
    2. Show that gradient descent on the cross-entropy loss of the two-class softmax model never changes w1+w2w_1 + w_2 or b1+b2b_1 + b_2. Suppose that gradient descent starts from w1=w2=b1=b2=0w_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.

  2. Softmax Hessian. As in Section 3.1.2.2, write the cross-entropy loss as a function of the logits, l(y,o)=g(o)−y⊤ol(\mathbf{y}, \mathbf{o}) = g(\mathbf{o}) - \mathbf{y}^\top \mathbf{o} with g(o)=log⁡∑kexp⁡(ok)g(\mathbf{o}) = \log \sum_k \exp(o_k).

    1. Compute the Hessian ∂o2 l(y,o)\partial^2_{\mathbf{o}}\, l(\mathbf{y}, \mathbf{o}) and show that it does not depend on y\mathbf{y}.
    2. Let eY\mathbf{e}_Y be the one-hot vector of a class YY drawn from softmax(o)\mathrm{softmax}(\mathbf{o}). Compute the covariance matrix of eY\mathbf{e}_Y and show that it equals the Hessian from the previous step.
    3. Conclude that gg is convex and that the cross-entropy loss is convex in the logits.
  3. 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, oappleo_{\textrm{apple}} and oorangeo_{\textrm{orange}}. Now add a default option of choosing neither, with a fixed score onone=0o_{\textrm{none}} = 0.

    1. Determine whether adding the same constant to oappleo_{\textrm{apple}} and oorangeo_{\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.
    2. Compare the ratio P(apple)/P(orange)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.
  4. Log-sum-exp. The function lse(a,b)=log⁡(exp⁡(a)+exp⁡(b))\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)(a, b).

    1. Prove that
max⁡(a,b)<lse(a,b)≤max⁡(a,b)+log⁡2,(3.1.12)\max(a, b) \lt \mathrm{lse}(a, b) \leq \max(a, b) + \log 2, \tag{3.1.12}

with equality on the right exactly when a=ba = b, and show that the gap to max⁡(a,b)\max(a, b) can be made arbitrarily small. Hint: without loss of generality set b=0b = 0 and a≥0a \geq 0.

  1. Prove that for every λ>0\lambda > 0
max⁡(a,b)<λ−1lse(λa,λb)≤max⁡(a,b)+λ−1log⁡2,(3.1.13)\max(a, b) \lt \lambda^{-1} \mathrm{lse}(\lambda a, \lambda b) \leq \max(a, b) + \lambda^{-1} \log 2, \tag{3.1.13}

and conclude that λ−1lse(λa,λb)→max⁡(a,b)\lambda^{-1} \mathrm{lse}(\lambda a, \lambda b) \to \max(a, b) as λ→∞\lambda \to \infty.

  1. Construct an analogous smooth minimum.
  2. Extend the definition and both bounds to qq numbers, showing that the gap to max⁡iai\max_i a_i is at most log⁡q\log q.
  1. Temperature. Let P=softmax(o)P = \mathrm{softmax}(\mathbf{o}), and let the distribution at temperature TT be softmax(o/T)\mathrm{softmax}(\mathbf{o}/T). Suppose we pick another distribution QQ with Q(i)∝P(i)αQ(i) \propto P(i)^\alpha for α>0\alpha > 0.
    1. Which choice of α\alpha corresponds to doubling the temperature? Which choice corresponds to halving it?
    2. Suppose that exactly ss of the qq logits attain the largest value. Find the limit of softmax(o/T)\mathrm{softmax}(\mathbf{o}/T) as T→0T \to 0.
    3. Let oˉ=1q∑joj\bar{o} = \frac{1}{q}\sum_j o_j be the mean logit. Show that for large TT
softmax(o/T)i=1q+oi−oˉqT+O(T−2).(3.1.14)\mathrm{softmax}(\mathbf{o}/T)_i = \frac{1}{q} + \frac{o_i - \bar{o}}{qT} + O(T^{-2}). \tag{3.1.14}
  1. Temperature scaling fits a single TT 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 β=1/T\beta = 1/T, so that the fit is a one-dimensional convex problem. Hint: use the convexity of gg from exercise 2.
  1. Separable data. ● Suppose that some parameters (W,b)(\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 (cW,cb)(c\mathbf{W}, c\mathbf{b}) for c>0c > 0.

    1. Show that the cross-entropy loss of every training example strictly decreases as cc grows and tends to 00 as c→∞c \to \infty.
    2. Conclude that the training loss has no minimizer and that every sequence of parameters whose training loss tends to 00 has unbounded norm.
    3. Add the weight decay penalty of Section 2.7, applied to both weights and biases, λ2(∥W∥2+∥b∥2)\frac{\lambda}{2}(\|\mathbf{W}\|^2 + \|\mathbf{b}\|^2) with λ>0\lambda > 0, to the training loss. Show that the penalized loss has a minimizer.
  2. Squared error on probabilities. Instead of cross-entropy, we could fit the predicted probabilities to the one-hot label with the squared loss 12∥y^−y∥2\frac{1}{2}\|\hat{\mathbf{y}} - \mathbf{y}\|^2.

    1. Show that the derivatives of the softmax are ∂y^k/∂oj=y^k(1(j=k)−y^j)\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.
    2. For two classes, write both losses as functions of the margin mm and compute their derivatives with respect to mm. Show that as m→−∞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-1.
    3. Explain what this difference means for a model that starts training with confident wrong predictions.
  3. [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=argmax⁡i (oi+γi)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 γ1,…,γq\gamma_1, \ldots, \gamma_q be i.i.d. draws from the standard Gumbel distribution, whose CDF is P(γ≤z)=exp⁡(−exp⁡(−z))P(\gamma \leq z) = \exp(-\exp(-z)).

    1. Show that P(ok+γk≤z)=exp⁡(−exp⁡(ok)exp⁡(−z))P(o_k + \gamma_k \leq z) = \exp(-\exp(o_k)\exp(-z)).
    2. Show that P(argmax⁡i (oi+γi)=k)=softmax(o)kP\left(\operatorname{argmax}_i \, (o_i + \gamma_i) = k\right) = \mathrm{softmax}(\mathbf{o})_k. Hint: condition on the value of ok+γko_k + \gamma_k and use the substitution u=exp⁡(−z)u = \exp(-z).
    3. Conclude that scaling the noise, γi↦Tγi\gamma_i \mapsto T\gamma_i, samples from softmax(o/T)\mathrm{softmax}(\mathbf{o}/T).
    4. Verify your result numerically: for o=(1.0,2.2,0.3)\mathbf{o} = (1.0, 2.2, 0.3) and T∈{0.25,1,4}T \in \{0.25, 1, 4\}, draw 10510^5 samples of argmax⁡i(oi+Tγi)\operatorname{argmax}_i (o_i + T\gamma_i) and confirm that the label frequencies match softmax(o/T)\mathrm{softmax}(\mathbf{o}/T) up to Monte Carlo error.

Discussions