Unit 2.4 · about 3 h
139 / 324Softmax regression and one-versus-rest
Most real decisions choose among more than two outcomes. Softmax generalizes the sigmoid without breaking probability semantics, and one-versus-rest is the fallback every library reaches for when a solver only does binary.
- derive
- implement
You can now
- Derive the softmax from \(K\) linear scores, its cross-entropy loss, and the prediction-error-times-input gradient.
- Implement max-subtracted softmax and multiclass cross-entropy that stay finite on extreme logits.
- Contrast joint multinomial fitting with one-versus-rest on parameter counts, calibration and solver limits.
Covers
- Softmax regression and multiclass cross-entropy
- One-versus-rest classification
Study, in this order
6 steps
- Softmax, vectorization caution and cross-entropy lossDive into Deep Learning - linear models slice
Section 4.1: The Softmax (ordering preservation, argmax needs no exponentials), Vectorization (row-wise softmax with the overflow-underflow caution), Loss Function with Log-Likelihood and Softmax and Cross-Entropy Loss
- Softmax from scratch, including the instability warningDive into Deep Learning - linear models slice
Section 4.4: The Softmax (naive implementation with the do-not-use-verbatim caution), The Model, The Cross-Entropy Loss, Training, Prediction
Depth · Read the naive
softmaxas the failure demo. Use the frameworksoftmaxwith built-in protections for every real fit. - Multinomial logistic regressionAn Introduction to Statistical Learning with Python
Chapter 4, Section 4.3.5 (p. 144): the \(K\)-class extension (4.13) with log odds linear in \(x\) (4.14)
- Multiclass logistic form and gradientTom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic Regression
Section 3.4 (\(K - 1\) linear functions in equations 27-28, regularized gradient rule 29)
- Multinomial geometry, OvR solvers and calibrationscikit-learn - linear models, discriminant analysis and naive Bayes
Section 1.1.11.2 (deliberate \(K\)-vector overparameterization, non-unique unpenalized solutions) and 1.1.11.3 with its solver table and Solvers' details (
liblinearcannot fit a multinomial model, so multiclass use wraps it inOneVsRestClassifier; the multinomial loss is expected to calibrate better than one-versus-rest) - One-versus-rest in practiceHands-On Machine Learning with Scikit-Learn and PyTorch - classification and linear models
Book Chapter 3: Multiclass Classification (printed pp. 124-126). Notebook 03 cells: Multiclass Classification section: the
SVCOvO-training note,OneVsRestClassifierwith its 10 estimators, and theSGDClassifiermulticlass run
Focus on
- Softmax preserves order, so \(\operatorname{argmax}\) needs no exponentials. Probabilities still need the max-subtracted form, because \(\exp(1000)\) overflows to \(\infty\) and \(\infty\) divided by \(\infty\) is nan.
- sklearn fits \(K\) vectors for \(K\) classes on purpose, for symmetry under regularization. Without penalty that redundancy makes the solution non-unique, which is one more reason the default \(L_2\) matters.
- One-versus-rest trains \(K\) binary problems and compares uncalibrated margins, while multinomial optimizes one joint loss. Expect worse-calibrated probabilities from the OvR scheme.
Reproduce closed-book
softmax of [1000, 1001, 999] returns [nan, nan, nan] while the max-subtracted form returns [0.2447, 0.6652, 0.0900]. Then do the D2L 4.4 exercise in float32, the dtype of D2L's PyTorch code: naive softmax of [-110, -111] returns [nan, nan] because both exponentials underflow to 0, and [-100, -101] gives 0.7297 instead of 0.7311 from subnormal rounding. In float64 both inputs still work; the cliff sits near -745.Traps
- Copying the D2L 4.4 teaching
softmaxinto real code. The page itself warns against verbatim use; framework implementations subtract the row maximum internally. - Calling OvR margins probabilities. One-versus-rest
decision_functionscores are not calibrated across the K classifiers; takepredict_probafrom a joint fit or calibrate afterwards. - Passing
multi_classtoLogisticRegressionunder sklearn 1.9. The parameter is gone and raisesTypeError. Multiclass fits are multinomial under the defaultlbfgs,liblinearraises aValueErroron three or more classes, and one-versus-rest now means wrapping the estimator inOneVsRestClassifier.
Practice
D2L 4.4 Exercises: the sub-minus-100 softmax fix
Exercise 1: test softmax with an input of 100, then with the largest input below -100, then implement the fix relative to the largest entry
Write the max-subtracted version from a blank file, run both tests in float32 and float64, and match it against the framework softmax on random and extreme logits.
HoML 04 Exercise 12: batch gradient descent with early stopping for softmax regression
Exercise solutions, problem 12: NumPy-only batch gradient descent with early stopping on iris
Reuse your stable loss and stop on validation error, not training error.
Self-test
-
Why can
argmaxskip thesoftmaxentirely?Softmax is monotone in each logit and preserves their order, so the largest logit is always the most probable class. Computing probabilities still needs the stable form. -
sklearn fits 3 vectors for 3 classes while Mitchell fits \(K - 1 = 2\) linear functions. Is one of them wrong?
No. \(K\) vectors deliberately overparameterize for symmetry under regularization, while \(K - 1\) suffices because probabilities sum to one. Without penalty the \(K\)-vector solution is not unique. -
Naive
softmaxof[1000, 1001, 999]returnsnan. Show the exact failure and the fix.Each exponential overflows to \(\infty\) and \(\infty/\infty\) isnan. Subtract the row maximum first: \(\exp([-1, 0, -2])\) over its sum gives[0.2447, 0.6652, 0.0900]with the same \(\operatorname{argmax}\). -
liblinearis your only allowed solver on a 5-class problem. Which scheme, and what do you lose?One-versus-rest: wrap it inOneVsRestClassifier, which fits 5 binary estimators, because in sklearn 1.9liblinearraises aValueErroron three or more classes. You lose the joint multinomial objective and should expect worse-calibrated probabilities.
Completion criterion
Stop when
Your max-subtracted softmax matches the framework on random and extreme logits, your multiclass gradient passes a numeric check, and you can state when OvR is forced and what it costs.
Mark passed, then open 2.5 Only mark this when you can do it without notes.Leads to
- 2.8 Probability estimates, class priors and asymmetric thresholds Turn multiclass scores into decisions with costs attached.
- 2.5 Residual, leverage, separation and misspecification diagnostics Watch separation inflate the weights here exactly as in binary logistic regression.
Comes after
- 2.3 Logistic regression and stable binary cross-entropyGeneralize the sigmoid, the log likelihood and the stable loss to K classes.
Resources for this unit
- An Introduction to Statistical Learning with Python Use Chapters 3, 4 and 6 with their Python labs as the first pass: least squares and its diagnostics, logistic regression, LDA, QDA and naive Bayes, basis expansion and regularization paths.
- Dive into Deep Learning - linear models slice Use 3.1, 3.4, 3.6, 3.7, 4.1, 4.4, 22.7 and 22.9 for linear regression, generalization, weight decay, softmax, maximum likelihood and naive Bayes. Implement with NumPy first and use the PyTorch versions only as a differential reference.
- scikit-learn - linear models, discriminant analysis and naive Bayes Use the official Linear Models, LDA and QDA, and Naive Bayes guides to verify estimator semantics and selected edge cases after the independent implementation works.
- Hands-On Machine Learning with Scikit-Learn and PyTorch - classification and linear models Read the Chapter 3 and 4 sections each unit names, then run notebooks 03 and 04 for classification diagnostics, linear and polynomial regression, regularization and logistic regression. Recreate the target mechanism independently before inspecting worked exercise code.
- Tom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic Regression Read Sections 2 (naive Bayes, the smoothed estimates (7) and (9), parameter counts), 3 (Gaussian naive Bayes implies the logistic form, gradient ascent, the \(L_2\) penalty, the \(K\)-class rules) and 4 (generative versus discriminative, Ng and Jordan rates). This is the CS446 reading for Lectures 6-8; rework each derivation on a hand-sized dataset.
Also in this section
- NeetCode ML - linear-model closing drill After the section gate, solve Gradient Descent, Sigmoid and ReLU, Softmax, Cross-Entropy Loss, Linear Regression Forward and Linear Regression Training cold. Repeat only failed items from a blank file with changed values.
- Deep-ML - linear and probabilistic model problems Use 15 Linear Regression Using Gradient Descent, 106 Train Logistic Regression with Gradient Descent and 140 Bernoulli Naive Bayes Classifier as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin. The local implementation remains the evidence.