Softmax Regression

Dive into Deep Learning · §3.1

Softmax Regression: Linear Models for Categorical Probabilities
one-hot encoding · affine logits · softmax · shift invariance · cross-entropy · \hat{\mathbf{y}} - \mathbf{y} gradient · temperature

Why Scalar Regression Fails on Unordered Categories

Motivation & Failure Mode

Sorting clothing photos into q = 10 unordered categories via continuous scalar regression breaks down immediately:

  • Arbitrary metric ordering: Predicting \hat{y} = 5.5 places a photo halfway between coat (5) and sandal (6), imposing a false numerical order.
  • Distorted squared-error penalties: Under \frac{1}{2}(\hat{y} - y)^2, mistaking T-shirt (1) for ankle boot (10) costs (10 - 1)^2 = 81\times as much as mistaking it for trouser (2).
  • Need for calibrated distributions: Downstream decisions require a complete probability vector \hat{\mathbf{y}} \in \Delta^q across all q candidate classes.

One-Hot Encoding Represents Categories as Distributions

Target Representation

Consider a 2 \times 2 grayscale image with four pixel features (x_1, x_2, x_3, x_4) and q = 3 classes—cat (1), chicken (2), and dog (3):

  • One-hot label vector: Encode class y \in \{1, \ldots, q\} as \mathbf{y} \in \{0, 1\}^q with y_y = 1 and 0 elsewhere: cat (1, 0, 0), chicken (0, 1, 0), dog (0, 0, 1).
  • Symmetric simplex vertices: Every pair of distinct categories sits at exact Euclidean distance \|\mathbf{e}_i - \mathbf{e}_j\|_2 = \sqrt{2}, eliminating any artificial ordering.
  • Memory convention: Math uses one-hot \mathbf{y} \in \{0, 1\}^q; code stores integer index y \in \{0, \ldots, q-1\} in O(1) space.

One Affine Score (Logit) per Candidate Class

The Linear Layer

Softmax regression assigns each class j \in \{1, \ldots, q\} its own weight vector \mathbf{w}_j \in \mathbb{R}^d and bias b_j \in \mathbb{R}:

  • Unnormalized class scores (logits): For input \mathbf{x} \in \mathbb{R}^d, class j receives the affine score o_j = \mathbf{w}_j^\top\mathbf{x} + b_j.
  • Matrix form: Stacking the columns \mathbf{w}_j into \mathbf{W} \in \mathbb{R}^{d \times q} and biases into \mathbf{b} \in \mathbb{R}^q yields: \mathbf{o} = \mathbf{W}^\top \mathbf{x} + \mathbf{b}
  • Parameter count: A 2\times 2 image (d=4, q=3) uses 4\times 3 + 3 = 15 parameters; a 28\times 28 Fashion-MNIST image (d=784, q=10) uses 7{,}840 + 10 = 7{,}850 parameters.

The Softmax Operator Maps Logits to Probabilities

Probability Normalization

The softmax operator exponentiates each logit and divides by their partition sum:

\hat{y}_j = \mathrm{softmax}(\mathbf{o})_j = \frac{\exp(o_j)}{\sum_{k=1}^q \exp(o_k)}

  • Concrete trace: Logits \mathbf{o} = (1.0, 2.2, 0.3) exponentiate to (2.72, 9.03, 1.35) (sum 13.09), giving \hat{\mathbf{y}} = (0.21, 0.69, 0.10).
  • Valid simplex & order preservation: Every \hat{y}_j \in (0, 1), \sum_j \hat{y}_j = 1, and \operatorname{argmax}_j \hat{y}_j = \operatorname{argmax}_j o_j.

Shift Invariance and Log-Odds Ratios

Structural Properties of Softmax

Exponentials convert additive shifts into a common factor that cancels out:

\mathrm{softmax}(\mathbf{o} + c\mathbf{1})_j = \frac{\exp(c)\exp(o_j)}{\exp(c)\sum_{k=1}^q \exp(o_k)} = \mathrm{softmax}(\mathbf{o})_j

  • Logit differences are log-odds: o_i - o_j = \log(\hat{y}_i / \hat{y}_j), so chicken (2.2) vs. cat (1.0) has odds e^{1.2} \approx 3.3\times.
  • Overflow safeguard: Subtracting c = \max_k o_k keeps every exponent \le 0, preventing float32 overflow (o > 88.7).

Two-Class Softmax Reduces to Logistic Regression

Connection to Binary Classification

When q = 2, shift invariance implies that the two probabilities depend solely on the scalar difference o = o_1 - o_2:

\hat{y}_1 = \frac{1}{1 + \exp(-(o_1 - o_2))} = \sigma(o_1 - o_2)

  • Equivalence to logistic sigmoid: Here \sigma(o) = (1 + e^{-o})^{-1} and \hat{y}_2 = 1 - \hat{y}_1 = \sigma(-o).
  • Redundant parameterization: Parameters (\mathbf{w}_1, b_1), (\mathbf{w}_2, b_2) collapse to a single difference vector (\mathbf{w}_1 - \mathbf{w}_2, b_1 - b_2) with log-odds o = \log(\hat{y}_1 / \hat{y}_2).

Vectorizing Softmax Across a Minibatch

Batched Matrix Formulation

In code, we process a minibatch of n examples with d features in a single GEMM followed by a rowwise softmax:

\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}, \qquad \hat{\mathbf{Y}} = \mathrm{softmax}(\mathbf{O})

  • Tensor shapes: \mathbf{X} \in \mathbb{R}^{n \times d} times \mathbf{W} \in \mathbb{R}^{d \times q} plus broadcast \mathbf{b} \in \mathbb{R}^{1 \times q} produces \mathbf{O} \in \mathbb{R}^{n \times q}.
  • Rowwise normalization: Divide each row i by its own partition sum \sum_{k=1}^q \exp(O_{ik}) (axis=1, keepdims=True).

Geometry of Softmax Decision Regions

Linear Decision Boundaries

Because softmax preserves logit ordering, class j wins wherever o_j \ge o_k for all k \neq j:

  • Intersection of halfspaces: The condition o_j \ge o_k expands to (\mathbf{w}_j - \mathbf{w}_k)^\top\mathbf{x} + (b_j - b_k) \ge 0, so each decision region is a flat-sided convex polyhedron formed by intersecting q - 1 halfspaces.
  • Pairwise hyperplane boundaries: Neighboring classes j and k meet along the flat hyperplane where their logits tie (o_j = o_k).
  • Scope assumption: Competing softmax outputs assume mutually exclusive, unordered classes (multi-label tasks use independent binary sigmoids per tag).

Maximum Likelihood Yields the Cross-Entropy Loss

Probabilistic Loss Derivation

The negative log-likelihood of observing true class y (one-hot \mathbf{y} \in \{0, 1\}^q) under \hat{y}_j = P(y = j \mid \mathbf{x}) is the cross-entropy loss:

l(\mathbf{y}, \hat{\mathbf{y}}) = -\sum_{j=1}^q y_j \log \hat{y}_j = -\log \hat{y}_y

  • Boundary behavior: l \to 0 as \hat{y}_y \to 1 and diverges to +\infty as \hat{y}_y \to 0, heavily penalizing confident mistakes.
  • Concrete trace on (0.21, 0.69, 0.10): True chicken (y = 2) costs -\log 0.69 \approx 0.37\text{ nats}; true dog (y = 3) jumps sixfold to -\log 0.10 \approx 2.30\text{ nats}.

Why Squared Error Fails on Softmax Probabilities

Optimization Pitfall: Vanishing Gradients on Blunders

Minimizing squared error \frac{1}{2}\|\hat{\mathbf{y}} - \mathbf{y}\|_2^2 on softmax outputs stalls on confident blunders:

  • Softmax Jacobian saturation: Because \partial \hat{y}_k / \partial o_j = \hat{y}_k(\mathbf{1}_{j=k} - \hat{y}_j) carries a factor of \hat{y}_k, any class with \hat{y}_y \to 0 has a vanishing logit derivative.
  • Log cancels exp in cross-entropy: For two-class margin m = o_y - o_{\text{other}} \ll 0, squared-loss gradient -2\sigma(m)(1-\sigma(m))^2 \to 0, whereas cross-entropy gradient -(1-\sigma(m)) \to -1 supplies a full unit restoring force.

Log-Sum-Exp Form and the Residual Gradient

Exact Gradient Derivation

Writing cross-entropy directly in terms of the logits \mathbf{o} via the log-sum-exp function:

l(\mathbf{y}, \hat{\mathbf{y}}) = \log \sum_{k=1}^q \exp(o_k) - o_y

Differentiating with respect to o_j yields the exact residual vector:

\nabla_{\mathbf{o}}\, l = \hat{\mathbf{y}} - \mathbf{y}

  • Prediction minus observation: For \hat{\mathbf{y}} = (0.21, 0.69, 0.10) and true chicken \mathbf{y} = (0, 1, 0), \nabla_{\mathbf{o}}\, l = (0.21, -0.31, 0.10) boosts chicken and suppresses rivals proportionally.

Weight Gradients and Global Convexity

Chain Rule to Parameters

Backpropagating through \mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b} gives the minibatch parameter gradients:

\nabla_{\mathbf{W}} L = \frac{1}{n}\mathbf{X}^\top(\hat{\mathbf{Y}} - \mathbf{Y}), \qquad \nabla_{\mathbf{b}} L = \frac{1}{n}(\hat{\mathbf{Y}} - \mathbf{Y})^\top\mathbf{1}_n

  • Template nudging: For a single example \mathbf{x}, -\nabla_{\mathbf{w}_j} l = (y_j - \hat{y}_j)\mathbf{x} pulls the true class template \mathbf{w}_y toward \mathbf{x} and pushes rival templates \mathbf{w}_{j \neq y} away.
  • Global convexity: The logit Hessian \nabla^2_{\mathbf{o}}\, l = \mathrm{diag}(\hat{\mathbf{y}}) - \hat{\mathbf{y}}\hat{\mathbf{y}}^\top \succeq \mathbf{0} is a categorical covariance matrix, making L(\mathbf{W}, \mathbf{b}) globally convex.

Information-Theoretic View: Surprisal, Entropy, and KL

Why It Is Called Cross-Entropy

In Shannon’s information theory, an event of probability p carries surprisal -\log p:

  • Decomposition into entropy + KL divergence: H(\mathbf{p}, \hat{\mathbf{p}}) = -\sum_{j=1}^q p_j \log \hat{p}_j = H(\mathbf{p}) + D_{\mathrm{KL}}(\mathbf{p} \,\|\, \hat{\mathbf{p}})
  • Gibbs’ inequality (D_{\mathrm{KL}} \ge 0): Because D_{\mathrm{KL}}(\mathbf{p} \,\|\, \hat{\mathbf{p}}) = 0 \iff \hat{\mathbf{p}} = \mathbf{p}, expected cross-entropy is uniquely minimized when predicted probabilities match the true conditional distribution \hat{\mathbf{p}} = \mathbf{p} (proper scoring rule).

Cross-Entropy as a Smooth Surrogate for 0–1 Error

Accuracy vs. Differentiable Training

Define the classification margin of an example as its true-class logit minus the highest competing logit, m = o_y - \max_{j \neq y} o_j:

  • Zero-one error is non-differentiable: The classifier errs when m < 0 and succeeds when m > 0. This step function has derivative 0 everywhere it exists, providing zero gradient signal.
  • Convex upper bound: Two-class cross-entropy in bits, \log_2(1 + e^{-m}), is a smooth, strictly decreasing convex upper bound on the 0\text{--}1 error.
  • Mistake bound: Every misclassified example (m \le 0) incurs at least \log 2 \approx 0.693\text{ nats} (1\text{ bit}) of cross-entropy loss.

Separable Data, Unbounded Weights, and Temperature

Confidence vs. Decision Boundaries

Because cross-entropy keeps decreasing for m > 0, minimizing it pushes predicted probabilities toward 0 and 1 even after every decision is already correct:

  • Runaway weights on linearly separable data: If (\mathbf{W}, \mathbf{b}) classifies every training point correctly (m^{(i)} > 0), scaling (c\mathbf{W}, c\mathbf{b}) with c \to \infty drives the loss to 0 without bound while leaving the decision boundary unchanged; weight decay (\frac{\lambda}{2}\|\mathbf{W}\|_F^2) restores a finite minimizer.
  • Temperature scaling: Dividing logits by T > 0 before softmax: \hat{\mathbf{y}}(T) = \mathrm{softmax}(\mathbf{o} / T) sharpens toward argmax as T \to 0 and flattens toward (1/q, \ldots, 1/q) as T \to \infty without altering \operatorname{argmax}_j o_j or accuracy.

Concept Check: Softmax Invariance & Cross-Entropy

Concept Check

Work out the following three questions from the properties of softmax and cross-entropy:

  1. Shift invariance: Given \mathrm{softmax}(2, 0, 0) \approx (0.79, 0.11, 0.11) since e^2 \approx 7.39, what is \mathrm{softmax}(102, 100, 100), and how many times more probable is class 1 than class 2?
  2. Honest calibration (Gibbs’ inequality): For ambiguous images that are shirts 60\% of the time and T-shirts 40\% of the time, which constant forecast achieves lower expected cross-entropy: (0.6, 0.4) or (0.9, 0.1)?
  3. Surrogate error bound: If a classifier reaches an average cross-entropy loss of 0.10\text{ nats} across 60{,}000 training images, at most how many training images can it misclassify?

Answers: (1) Subtracting 100 from every logit gives \mathrm{softmax}(2, 0, 0) \approx (0.79, 0.11, 0.11), with ratio e^{102-100} = e^2 \approx 7.39. (2) (0.6, 0.4) gives H(\mathbf{p}) = -0.6\log 0.6 - 0.4\log 0.4 \approx 0.67\text{ nats}, beating (0.9, 0.1) at -0.6\log 0.9 - 0.4\log 0.1 \approx 0.98\text{ nats}. (3) Total loss is 60{,}000 \times 0.10 = 6{,}000\text{ nats}, and each mistake (m \le 0) costs at least \log 2 \approx 0.693\text{ nats}, so at most 6{,}000 / 0.693 \approx 8{,}656 errors (14.4\%).

Summary: Key Takeaways for Softmax Regression

Section Summary

Concept Mathematical Form Key Property / Practical Role
One-hot target \mathbf{y} \in \{0, 1\}^q,\; y_y = 1,\; \sum_j y_j = 1 Places all pairs of classes at equal distance \sqrt{2}; valid categorical distribution
Batched affine logits \mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b} \in \mathbb{R}^{n \times q} d \cdot q + q parameters (7{,}850 on Fashion-MNIST); boundaries are flat hyperplanes
Softmax operator \hat{y}_j = \exp(o_j) / \sum_{k=1}^q \exp(o_k) Order-preserving (\operatorname{argmax} \hat{y}_j = \operatorname{argmax} o_j); shift-invariant (\mathrm{softmax}(\mathbf{o}+c\mathbf{1}) = \mathrm{softmax}(\mathbf{o}))
Log-odds & q=2 limit o_i - o_j = \log(\hat{y}_i / \hat{y}_j),\; \hat{y}_1 = \sigma(o_1 - o_2) Logit differences are log-odds; 2-class softmax equals binary logistic regression
Cross-entropy loss l(\mathbf{y}, \hat{\mathbf{y}}) = -\log \hat{y}_y = \log\sum_k \exp(o_k) - o_y Negative log-likelihood; convex in (\mathbf{W}, \mathbf{b}); upper-bounds 0\text{--}1 error (\ge \log 2 on mistakes)
Logit & weight gradients \nabla_{\mathbf{o}} l = \hat{\mathbf{y}} - \mathbf{y},\; \nabla_{\mathbf{W}} L = \frac{1}{n}\mathbf{X}^\top(\hat{\mathbf{Y}}-\mathbf{Y}) Prediction minus target; non-vanishing on confident mistakes (unlike squared error)
Temperature scaling \hat{\mathbf{y}}(T) = \mathrm{softmax}(\mathbf{o} / T),\; T > 0 Tunes confidence (T \to 0 argmax, T \to \infty uniform) without changing class predictions