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 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 . The quickest route to a multiclass classifier reuses binary ones.
- One-vs-rest (OvR). Train binary classifiers, class against all the others, and predict . Each problem is imbalanced (one class against ), the 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, 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 , train one binary classifier per bit, and predict the class whose codeword is nearest (in Hamming distance) to the predicted bits. If any two codewords differ in at least bits, any wrong bits are corrected. One-vs-rest is the identity code, with : it corrects nothing.
| Scheme | Binary problems | Data per problem | Prediction |
|---|---|---|---|
| One-vs-rest | all examples | largest score | |
| One-vs-one | two classes, about if balanced | vote, or pairwise coupling | |
| Output code of length | all , relabeled per bit | nearest codeword | |
| Softmax regression | one joint model | all | largest probability |
How many binary classifiers does one-vs-one need for classes?
Show the answer
45 classifiers
, 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 , is comparable to one-vs-rest's .
Softmax regression
Model all the classes jointly. Give class a weight vector (bias absorbed), score , and normalize with the softmax (a name due to Bridle, 1990):
This is softmax regression, also called multinomial logistic regression. Write the label as a one-hot vector . Then the negative log-likelihood of the training set is the cross-entropy between labels and predictions:
One example's loss is log-sum-exp minus the true class's score. Differentiate with respect to a score:
The chain rule with gives the same "prediction minus target, times input" as least squares and logistic regression. Stacking and the probabilities and labels as matrices and :
Differentiate once more. The Hessian with respect to the scores is the covariance matrix of a one-hot vector drawn from :
For any , , the variance of under , which is nonnegative. A convex function of scores that are linear in is convex in : the full Hessian is .
With , : softmax regression is logistic regression with . 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 to every adds to every score, and the softmax ignores a common shift: . So the loss is constant along these directions, the Hessian is singular there (), and the minimizer is never unique. Two standard fixes: pin a reference class, , leaving free vectors exactly as logistic regression does; or add . The penalty picks the centered representative: since is minimized at , the penalized solution satisfies .
Log-sum-exp without overflow. In double precision overflows once exceeds about 709.8, and large scores are routine. Subtract the maximum first:
Every exponent is now at most 0 and one equals 0, so the sum lies in : no overflow, and no logarithm of an underflowed zero.
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 gradientComputing as is both stabler and cheaper than taking the log of a computed probability.
Temperature. Dividing the scores by gives . As it approaches a one-hot vector on the top class (if unique), as it approaches uniform, and for every 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 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 . 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.
A three-class model outputs the scores . What probability does the softmax assign to the first class?
Show the answer
66.5 %
, , , total , so , , . At temperature the scores become and drops to about ; 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 consistent (classification-calibrated) if, for every vector of conditional class probabilities, scores that minimize, or nearly minimize, the expected surrogate 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, , and Gibbs' inequality, 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 , which is increasing in .
Take the multiclass hinge loss of Crammer & Singer (2001), which asks the true score to beat every other score by a margin of 1:
Drop the outer max (which can only lower the value) and let be a top-scoring class, with the two largest scores. The true class contributes , and every other class contributes at least :
If every , 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.
Concretely, with the scores have expected loss , 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 the minimizer is , up to a common shift, and the problem disappears: trouble arises only when no class has a majority.)
Key takeaways
- One-vs-rest ( classifiers), one-vs-one () and error-correcting output codes reduce multiclass to binary problems; a code with minimum Hamming distance corrects binary errors, and well-tuned one-vs-rest is a strong baseline.
- Softmax regression minimizes the cross-entropy , with gradient and score Hessian : convex, and for exactly logistic regression.
- The softmax is invariant to common shifts, so fix a reference class or add an 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 . The Crammer–Singer hinge is not: when no class has probability above , 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.
For softmax regression with a one-hot label , what is the gradient of one example's negative log-likelihood with respect to the score ?
Show the answer
C.
: predicted probability minus target. Multiplying by gives the gradient for .
In softmax regression you add the same vector to every class weight . What happens?
- Every predicted probability, and therefore the loss, stays exactly the same
- The probabilities of all classes increase
- The predicted class may change
- The loss increases by
Show the answer
A. Every predicted probability, and therefore the loss, stays exactly the same
Each score shifts by the same amount , and the softmax is invariant to common shifts. The parameters are therefore not identifiable: pin one class's weights to zero, or add an penalty, whose solution has .
You apply temperature scaling, , with fitted on a validation set to a trained classifier. Which statement is true?
- It can raise accuracy if
- It can lower accuracy if
- It changes the predicted class whenever the top two scores are close
- 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 preserves their order, so the argmax, and accuracy, are unchanged. Only the spread of the probabilities changes: softens overconfident outputs, sharpens them.
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
- 2
- 4
- 5
Show the answer
B. 2
With minimum distance , a corrupted word with at most 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).