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

Softmax regression and multiclass cross-entropyOne-versus-rest classification
1

Read

In this order, only the parts listed

0 of 6 done

  1. 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

  2. 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 softmax as the failure demo. Use the framework softmax with built-in protections for every real fit.

  3. 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)

  4. 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)

  5. 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 (liblinear cannot fit a multinomial model, so multiclass use wraps it in OneVsRestClassifier; the multinomial loss is expected to calibrate better than one-versus-rest)

  6. 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 SVC OvO-training note, OneVsRestClassifier with its 10 estimators, and the SGDClassifier multiclass run

2

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 softmax into real code. The page itself warns against verbatim use; framework implementations subtract the row maximum internally.
  • Calling OvR margins probabilities. One-versus-rest decision_function scores are not calibrated across the K classifiers; take predict_proba from a joint fit or calibrate afterwards.
  • Passing multi_class to LogisticRegression under sklearn 1.9. The parameter is gone and raises TypeError. Multiclass fits are multinomial under the default lbfgs, liblinear raises a ValueError on three or more classes, and one-versus-rest now means wrapping the estimator in OneVsRestClassifier.
3

Try it yourself

Closed-book, before checking anything

Derive the gradient from the multiclass negative log likelihood. In NumPy show naive 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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why can argmax skip the softmax entirely?Answer

    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.

  2. 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. 3.Naive softmax of [1000, 1001, 999] returns nan. Show the exact failure and the fix.Answer

    Each 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. 4.liblinear is your only allowed solver on a 5-class problem. Which scheme, and what do you lose?Answer

    One-versus-rest: wrap it in OneVsRestClassifier, which fits 5 binary estimators, because in sklearn 1.9 liblinear raises a ValueError on three or more classes. You lose the joint multinomial objective and should expect worse-calibrated probabilities.

5

Practice

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.