Unit 4 of 8 · about 3 hours · derive, implement
Softmax 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.
You'll be able to
- Derive the softmax from 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
Read
In this order, only the parts listed
0 of 6 done
- 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
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 -class extension (4.13) with log odds linear in (4.14)
- Multiclass logistic form and gradientTom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic Regression
Section 3.4 ( 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 -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 needs no exponentials. Probabilities still need the max-subtracted form, because overflows to and divided by is nan.
- sklearn fits vectors for classes on purpose, for symmetry under regularization. Without penalty that redundancy makes the solution non-unique, which is one more reason the default matters.
- One-versus-rest trains binary problems and compares uncalibrated margins, while multinomial optimizes one joint loss. Expect worse-calibrated probabilities from the OvR scheme.
Common mistakes · 3
- 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.
Try it yourself
Closed-book, before checking anything
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.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why can
argmaxskip thesoftmaxentirely?AnswerSoftmax 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.
2.sklearn fits 3 vectors for 3 classes while Mitchell fits linear functions. Is one of them wrong?Answer
No. vectors deliberately overparameterize for symmetry under regularization, while suffices because probabilities sum to one. Without penalty the -vector solution is not unique.
3.Naive
softmaxof[1000, 1001, 999]returnsnan. Show the exact failure and the fix.AnswerEach exponential overflows to and is
nan. Subtract the row maximum first: over its sum gives[0.2447, 0.6652, 0.0900]with the same .4.
liblinearis your only allowed solver on a 5-class problem. Which scheme, and what do you lose?AnswerOne-versus-rest: wrap it in
OneVsRestClassifier, 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.
Practice
- D2L 4.4 Exercises: the sub-minus-100 softmax fix
Exercise 1: test
softmaxwith an input of 100, then with the largest input below -100, then implement the fix relative to the largest entryWrite the max-subtracted version from a blank file, run both tests in
float32andfloat64, 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.
You're done 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.
Only when you can do this without notes.
Leads to
Notes
Resources · 5 for this unit, 2 more in the section
- An Introduction to Statistical Learning with PythonJames, Witten, Hastie, Tibshirani and Taylor · primary
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 sliceD2L authors · required
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 Bayesscikit-learn · reference
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 modelsAurelien Geron (O'Reilly, 2025) · support
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 RegressionTom Mitchell, Carnegie Mellon University · required
Read Sections 2 (naive Bayes, the smoothed estimates (7) and (9), parameter counts), 3 (Gaussian naive Bayes implies the logistic form, gradient ascent, the penalty, the -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 drillNeetCode · support
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 problemsDeep-ML · support
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.