Simple Algorithm
Machine Learning · Convergence · 26 min

Softmax & Multiclass Classification

One-vs-rest, softmax regression and its gradient.

Digits, species, diagnoses, the next word: most classification problems have more than two classes. You can bolt binary classifiers together, or model all the classes at once with the softmax. This lesson compares the two routes, derives the softmax gradient, tames its redundancy and its overflows, and asks a question with a surprising answer: which multiclass losses actually lead to the most likely class?

What you’ll learn

  • Compare one-vs-rest, one-vs-one and error-correcting output codes, with their costs and failure modes.
  • Derive softmax regression's negative log-likelihood, its gradient (p−y) x⊤(\mathbf p - \mathbf y)\,\mathbf x^\top and its Hessian, and prove that it is convex.
  • Explain the shift invariance of the softmax and how to remove it, compute log-sum-exp stably, and use temperature.
  • Prove that softmax cross-entropy is a consistent surrogate for the 0–1 loss, and show that a multiclass hinge loss is not.

Reductions: one-vs-rest, one-vs-one and output codes

Let the labels be y∈{1,…,K}y \in \{1, \dots, K\}. The quickest route to a multiclass classifier reuses binary ones.

  • One-vs-rest (OvR). Train KK binary classifiers, class kk against all the others, and predict arg max⁡kfk(x)\argmax_k f_k(\mathbf x). Each problem is imbalanced (one class against K−1K-1), the KK scores are trained separately and need not be on a common scale, and some regions are claimed by several classifiers or by none. Even so, with well-tuned, well-regularized base classifiers OvR is often as accurate as more elaborate schemes (Rifkin & Klautau, 2004).
  • One-vs-one (OvO). Train a classifier for every pair of classes, K(K−1)/2K(K-1)/2 in all, each on the data of its two classes only, and predict by majority vote, or turn the pairwise probabilities into class probabilities by pairwise coupling (Hastie & Tibshirani, 1998). Each problem is small and balanced, which pays off when training cost grows faster than linearly in the data, as for kernel methods.
  • Error-correcting output codes (Dietterich & Bakiri, 1995). Give each class a binary codeword of length LL, train one binary classifier per bit, and predict the class whose codeword is nearest (in Hamming distance) to the LL predicted bits. If any two codewords differ in at least hh bits, any ⌊(h−1)/2⌋\lfloor (h-1)/2\rfloor wrong bits are corrected. One-vs-rest is the identity code, with h=2h = 2: it corrects nothing.
SchemeBinary problemsData per problemPrediction
One-vs-restKKall nn exampleslargest score
One-vs-oneK(K−1)/2K(K-1)/2two classes, about 2n/K2n/K if balancedvote, or pairwise coupling
Output code of length LLLLall nn, relabeled per bitnearest codeword
Softmax regressionone joint modelall nnlargest probability
Allwein, Schapire & Singer (2000) unified the first three as output codes over {−1,0,+1}\{-1, 0, +1\} (0 = "ignore this class"), and proposed decoding with the binary learner's own loss as an alternative to Hamming distance.
Predict before you look

How many binary classifiers does one-vs-one need for K=10K = 10 classes?

Show the answer

45 classifiers

(102)=10⋅9/2=45\binom{10}{2} = 10 \cdot 9/2 = 45, against 10 for one-vs-rest. With balanced classes each pairwise problem sees only a fifth of the data, so the total training data handled, about 45×2n/10=9n45 \times 2n/10 = 9n, is comparable to one-vs-rest's 10n10n.

Softmax regression

Model all the classes jointly. Give class kk a weight vector wk\mathbf w_k (bias absorbed), score sk=wk⊤xs_k = \mathbf w_k^\top\mathbf x, and normalize with the softmax (a name due to Bridle, 1990):

p(y=k∣x)=pk=esk∑j=1Kesj.p(y = k \mid \mathbf x) = p_k = \frac{e^{s_k}}{\sum_{j=1}^K e^{s_j}}.

This is softmax regression, also called multinomial logistic regression. Write the label as a one-hot vector y∈{0,1}K\mathbf y \in \{0, 1\}^K. Then the negative log-likelihood of the training set is the cross-entropy between labels and predictions:

ℓ(W)=−∑i=1nlog⁡pi,yi=∑i=1n[log⁡∑k=1Kesik−si,yi].\ell(W) = -\sum_{i=1}^n\log p_{i, y_i} = \sum_{i=1}^n\Big[\log\sum_{k=1}^K e^{s_{ik}} - s_{i, y_i}\Big].
DerivationGradient and Hessian
  1. ∂∂sk[log⁡∑jesj−sy]=esk∑jesj−1{k=y}=pk−yk\frac{\partial}{\partial s_k}\Big[\log\sum_j e^{s_j} - s_y\Big] = \frac{e^{s_k}}{\sum_j e^{s_j}} - \mathbf 1\{k = y\} = p_k - y_k

    One example's loss is log-sum-exp minus the true class's score. Differentiate with respect to a score:

  2. ∇wkℓ=∑i=1n(pik−yik) xi,∇Wℓ=X⊤(P−Y)\nabla_{\mathbf w_k}\ell = \sum_{i=1}^n\big(p_{ik} - y_{ik}\big)\,\mathbf x_i, \qquad \nabla_W\ell = X^\top(P - Y)

    The chain rule with ∂sk/∂wk=x\partial s_k/\partial\mathbf w_k = \mathbf x gives the same "prediction minus target, times input" as least squares and logistic regression. Stacking W=[w1⋯wK]∈Rd×KW = [\mathbf w_1 \cdots \mathbf w_K] \in \R^{d\times K} and the probabilities and labels as n×Kn\times K matrices PP and YY:

  3. ∂pk∂sj=pk(1{j=k}−pj)⟹∇s2=diag⁡(p)−pp⊤\frac{\partial p_k}{\partial s_j} = p_k\big(\mathbf 1\{j = k\} - p_j\big) \quad\Longrightarrow\quad \nabla_{\mathbf s}^2 = \diag(\mathbf p) - \mathbf p\mathbf p^\top

    Differentiate pkp_k once more. The Hessian with respect to the scores is the covariance matrix of a one-hot vector drawn from p\mathbf p:

  4. v⊤(diag⁡p−pp⊤)v=Var⁡k∼p(vk) ≥ 0\mathbf v^\top\big(\diag\mathbf p - \mathbf p\mathbf p^\top\big)\mathbf v = \Var_{k\sim\mathbf p}(v_k) \ \ge\ 0

    For any v\mathbf v, v⊤(diag⁡p−pp⊤)v=∑kpkvk2−(∑kpkvk)2\mathbf v^\top(\diag\mathbf p - \mathbf p\mathbf p^\top)\mathbf v = \sum_k p_kv_k^2 - \big(\sum_k p_kv_k\big)^2, the variance of vv under p\mathbf p, which is nonnegative. A convex function of scores that are linear in WW is convex in WW: the full Hessian is ∑i(diag⁡pi−pipi⊤)⊗xixi⊤⪰0\sum_i(\diag\mathbf p_i - \mathbf p_i\mathbf p_i^\top)\otimes\mathbf x_i\mathbf x_i^\top \succeq 0.

With K=2K = 2, p1=es1/(es0+es1)=σ(s1−s0)p_1 = e^{s_1}/(e^{s_0} + e^{s_1}) = \sigma(s_1 - s_0): softmax regression is logistic regression with w=w1−w0\mathbf w = \mathbf w_1 - \mathbf w_0. Only the difference of the two weight vectors is determined, which is the first sign of a redundancy that the next step deals with.

Redundancy, stability and temperature

Shift invariance. Adding the same vector c\mathbf c to every wk\mathbf w_k adds c⊤x\mathbf c^\top\mathbf x to every score, and the softmax ignores a common shift: softmax⁡(s+t1)=softmax⁡(s)\softmax(\mathbf s + t\mathbf 1) = \softmax(\mathbf s). So the loss is constant along these dd directions, the Hessian is singular there ((diag⁡p−pp⊤)1=0(\diag\mathbf p - \mathbf p\mathbf p^\top)\mathbf 1 = \mathbf 0), and the minimizer is never unique. Two standard fixes: pin a reference class, wK=0\mathbf w_K = \mathbf 0, leaving K−1K - 1 free vectors exactly as logistic regression does; or add λ∑k∥wk∥2\lambda\sum_k\norm{\mathbf w_k}^2. The penalty picks the centered representative: since ∑k∥wk+c∥2\sum_k\norm{\mathbf w_k + \mathbf c}^2 is minimized at c=−1K∑kwk\mathbf c = -\frac1K\sum_k\mathbf w_k, the penalized solution satisfies ∑kwk=0\sum_k\mathbf w_k = \mathbf 0.

Log-sum-exp without overflow. In double precision exe^x overflows once xx exceeds about 709.8, and large scores are routine. Subtract the maximum first:

log⁡∑kesk=m+log⁡∑kesk−m,m=max⁡ksk.\log\sum_k e^{s_k} = m + \log\sum_k e^{s_k - m}, \qquad m = \max_k s_k.

Every exponent is now at most 0 and one equals 0, so the sum lies in [1,K][1, K]: no overflow, and no logarithm of an underflowed zero.

python
import numpy as np
from scipy.special import logsumexp, softmax

def softmax_nll(S, y):
    """Mean cross-entropy. S: n-by-K scores, y: integer labels in 0..K-1."""
    return np.mean(logsumexp(S, axis=1) - S[np.arange(len(y)), y])

def softmax_grad(X, S, y):
    P = softmax(S, axis=1)                  # computed stably
    P[np.arange(len(y)), y] -= 1.0          # P - Y
    return X.T @ P / len(y)                 # d-by-K gradient

Computing log⁡py\log p_{y} as sy−logsumexp⁡(s)s_y - \operatorname{logsumexp}(\mathbf s) is both stabler and cheaper than taking the log of a computed probability.

Temperature. Dividing the scores by T>0T > 0 gives softmax⁡(s/T)\softmax(\mathbf s/T). As T→0+T \to 0^+ it approaches a one-hot vector on the top class (if unique), as T→∞T \to \infty it approaches uniform, and for every TT the ranking of the classes, and therefore the predicted class, is unchanged. That makes temperature a free knob for confidence:

  • Calibration. Temperature scaling fits one TT by minimizing the negative log-likelihood on held-out data; Guo, Pleiss, Sun & Weinberger (2017) found it often the most effective post-hoc fix for overconfident neural networks, and it cannot change accuracy.
  • Distillation. Hinton, Vinyals & Dean (2015) trained a small model to match a large model's softmax at a high temperature, where the relative probabilities of wrong classes carry information.

Label smoothing attacks overconfidence during training instead: replace the one-hot target by (1−ϵ)y+ϵ/K(1 - \epsilon)\mathbf y + \epsilon/K. With hard targets on separable data the cross-entropy pushes the score gaps toward infinity, as with logistic regression; smoothed targets have a finite optimum. Introduced by Szegedy et al. (2016), it was found by Müller, Kornblith & Hinton (2019) to improve calibration and tighten class clusters, while making the trained network a worse teacher for distillation.

Predict before you look

A three-class model outputs the scores (2,1,0)(2, 1, 0). What probability does the softmax assign to the first class?

Show the answer

66.5 %

e2≈7.39e^2 \approx 7.39, e1≈2.72e^1 \approx 2.72, e0=1e^0 = 1, total 11.1111.11, so p1≈0.665p_1 \approx 0.665, p2≈0.245p_2 \approx 0.245, p3≈0.090p_3 \approx 0.090. At temperature T=2T = 2 the scores become (1,0.5,0)(1, 0.5, 0) and p1p_1 drops to about 0.510.51; the top class stays the same.

Which multiclass losses are consistent?

We train on a surrogate loss because the 0–1 loss is not differentiable, but what we care about is the 0–1 loss. Call a multiclass surrogate ψ(s,y)\psi(\mathbf s, y) consistent (classification-calibrated) if, for every vector η\boldsymbol\eta of conditional class probabilities, scores that minimize, or nearly minimize, the expected surrogate ∑yηy ψ(s,y)\sum_y\eta_y\,\psi(\mathbf s, y) must rank a most likely class first. Then driving the surrogate risk to its minimum drives the error rate to the Bayes rate. Tewari & Bartlett (2007) showed that "one can lose consistency in generalizing a binary classification method to deal with multiple classes," and gave a necessary and sufficient condition for a large family of surrogates; Zhang (2004) studied the same question for multicategory large-margin methods.

The identity is one line, −∑yηylog⁡py=−∑yηylog⁡ηy+∑yηylog⁡(ηy/py)-\sum_y\eta_y\log p_y = -\sum_y\eta_y\log\eta_y + \sum_y\eta_y\log(\eta_y/p_y), and Gibbs' inequality, DKL≥0\KL \ge 0 with equality only for equal distributions, does the rest. The same argument shows why the log loss is a proper scoring rule, and why one-vs-rest with unrestricted binary logistic models is consistent too: each binary problem's minimizer is the logit of ηk\eta_k, which is increasing in ηk\eta_k.

DerivationA multiclass hinge loss that is not consistent
  1. ψ(s,y)=max⁡(0, 1+max⁡k≠ysk−sy)\psi(\mathbf s, y) = \max\Big(0,\ 1 + \max_{k\ne y}s_k - s_y\Big)

    Take the multiclass hinge loss of Crammer & Singer (2001), which asks the true score to beat every other score by a margin of 1:

  2. ∑yηy ψ(s,y) ≥ 1+ηj(s(2)−s(1))+(1−ηj)(s(1)−s(2))=1+(1−2ηj)(s(1)−s(2))\sum_y\eta_y\,\psi(\mathbf s, y) \ \ge\ 1 + \eta_j\big(s_{(2)} - s_{(1)}\big) + (1 - \eta_j)\big(s_{(1)} - s_{(2)}\big) = 1 + (1 - 2\eta_j)\big(s_{(1)} - s_{(2)}\big)

    Drop the outer max (which can only lower the value) and let jj be a top-scoring class, with s(1)≥s(2)s_{(1)} \ge s_{(2)} the two largest scores. The true class y=jy = j contributes s(2)−s(1)≤0s_{(2)} - s_{(1)} \le 0, and every other class contributes at least s(1)−s(2)≥0s_{(1)} - s_{(2)} \ge 0:

  3. max⁡kηk≤12⟹min⁡s ∑yηy ψ(s,y)=1, attained at s=0\max_k\eta_k \le \tfrac12 \quad\Longrightarrow\quad \min_{\mathbf s}\ \sum_y\eta_y\,\psi(\mathbf s, y) = 1, \ \text{attained at } \mathbf s = \mathbf 0

    If every ηk≤1/2\eta_k \le 1/2, the right side is at least 1, which is exactly the expected loss of the all-zero scores. So tying every class is optimal, and minimizing the surrogate says nothing about which class is most likely.

  4. η=(0.4,0.3,0.3),  s=(0,ϵ,0):∑yηy ψ(s,y)=0.4(1+ϵ)+0.3(1−ϵ)+0.3(1+ϵ)=1+0.4ϵ\boldsymbol\eta = (0.4, 0.3, 0.3),\ \ \mathbf s = (0, \epsilon, 0):\quad \textstyle\sum_y\eta_y\,\psi(\mathbf s, y) = 0.4(1 + \epsilon) + 0.3(1 - \epsilon) + 0.3(1 + \epsilon) = 1 + 0.4\epsilon

    Concretely, with η=(0.4,0.3,0.3)\boldsymbol\eta = (0.4, 0.3, 0.3) the scores s=(0,ϵ,0)\mathbf s = (0, \epsilon, 0) have expected loss 1+0.4ϵ→11 + 0.4\epsilon \to 1, the minimum, yet they predict class 2 rather than the Bayes class 1. A learner that drives this surrogate risk to its minimum need not approach the Bayes error. (With η=(0.6,0.2,0.2)\boldsymbol\eta = (0.6, 0.2, 0.2) the minimizer is (1,0,0)(1, 0, 0), up to a common shift, and the problem disappears: trouble arises only when no class has a majority.)

Key takeaways

  • One-vs-rest (KK classifiers), one-vs-one (K(K−1)/2K(K-1)/2) and error-correcting output codes reduce multiclass to binary problems; a code with minimum Hamming distance hh corrects ⌊(h−1)/2⌋\lfloor(h-1)/2\rfloor binary errors, and well-tuned one-vs-rest is a strong baseline.
  • Softmax regression minimizes the cross-entropy ∑i[logsumexp⁡(si)−si,yi]\sum_i[\operatorname{logsumexp}(\mathbf s_i) - s_{i,y_i}], with gradient X⊤(P−Y)X^\top(P - Y) and score Hessian diag⁡p−pp⊤⪰0\diag\mathbf p - \mathbf p\mathbf p^\top \succeq 0: convex, and for K=2K = 2 exactly logistic regression.
  • The softmax is invariant to common shifts, so fix a reference class or add an L2L_2 penalty. Compute log-sum-exp after subtracting the maximum; temperature rescales confidence without changing predictions.
  • Softmax cross-entropy is consistent, because its expected value is H(η)+DKL(η ∥ p)H(\boldsymbol\eta) + \KL(\boldsymbol\eta\,\|\,\mathbf p). The Crammer–Singer hinge is not: when no class has probability above 1/21/2, tying all scores minimizes it.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

For softmax regression with a one-hot label y\mathbf y, what is the gradient of one example's negative log-likelihood with respect to the score sks_k?

  1. pk(1−pk)p_k(1 - p_k)
  2. yk−pky_k - p_k
  3. pk−ykp_k - y_k
  4. −log⁡pk-\log p_k
Show the answer

C. pk−ykp_k - y_k

∂/∂sk[log⁡∑jesj−sy]=pk−1{k=y}\partial/\partial s_k\big[\log\sum_je^{s_j} - s_y\big] = p_k - \mathbf 1\{k = y\}: predicted probability minus target. Multiplying by x\mathbf x gives the gradient for wk\mathbf w_k.

Question 2

In softmax regression you add the same vector c\mathbf c to every class weight wk\mathbf w_k. What happens?

  1. Every predicted probability, and therefore the loss, stays exactly the same
  2. The probabilities of all classes increase
  3. The predicted class may change
  4. The loss increases by ∥c∥2\norm{\mathbf c}^2
Show the answer

A. Every predicted probability, and therefore the loss, stays exactly the same

Each score shifts by the same amount c⊤x\mathbf c^\top\mathbf x, and the softmax is invariant to common shifts. The parameters are therefore not identifiable: pin one class's weights to zero, or add an L2L_2 penalty, whose solution has ∑kwk=0\sum_k\mathbf w_k = \mathbf 0.

Question 3

You apply temperature scaling, softmax⁡(s/T)\softmax(\mathbf s/T), with TT fitted on a validation set to a trained classifier. Which statement is true?

  1. It can raise accuracy if T>1T > 1
  2. It can lower accuracy if T<1T < 1
  3. It changes the predicted class whenever the top two scores are close
  4. It changes the confidence of the predictions but never which class is predicted
Show the answer

D. It changes the confidence of the predictions but never which class is predicted

Dividing all scores by the same T>0T > 0 preserves their order, so the argmax, and accuracy, are unchanged. Only the spread of the probabilities changes: T>1T > 1 softens overconfident outputs, T<1T < 1 sharpens them.

Question 4

In an error-correcting output code, every pair of class codewords differs in at least 5 bits. How many wrong binary classifiers can nearest-codeword decoding always correct?

  1. 1
  2. 2
  3. 4
  4. 5
Show the answer

B. 2

With minimum distance h=5h = 5, a corrupted word with at most ⌊(5−1)/2⌋=2\lfloor(5-1)/2\rfloor = 2 wrong bits is still strictly closer to the right codeword than to any other. Three wrong bits could land it at distance 2 from another codeword.

Further reading

  • T. G. Dietterich & G. Bakiri, "Solving multiclass learning problems via error-correcting output codes," Journal of Artificial Intelligence Research 2, 263–286 (1995).
  • E. L. Allwein, R. E. Schapire & Y. Singer, "Reducing multiclass to binary: a unifying approach for margin classifiers," Journal of Machine Learning Research 1, 113–141 (2000).
  • R. Rifkin & A. Klautau, "In defense of one-vs-all classification," Journal of Machine Learning Research 5, 101–141 (2004).
  • A. Tewari & P. L. Bartlett, "On the consistency of multiclass classification methods," Journal of Machine Learning Research 8, 1007–1025 (2007).
  • C. Guo, G. Pleiss, Y. Sun & K. Q. Weinberger, "On calibration of modern neural networks," Proceedings of ICML, PMLR 70, 1321–1330 (2017).