Linear models · lesson 11 of 12
Parts in this lesson
Ae = np.exp(z - z.max())softmax, without overflowing
Bnp.eye(10)[y]one-hot labels
CX.T @ (P - Y) / nthe gradient for every class’s weights
DOneVsRestClassifier(LogisticRegression())ten yes-or-no models instead

Many classes: softmax regression

Last updated

Logistic regression answers yes or no. Reading a handwritten digit has ten answers. Softmax regression gives each class its own score and turns the scores into ten probabilities that add up to 1; its loss and its gradient are lesson 3.10’s, one class at a time. This is the output layer of nearly every classifier in the rest of the course, up to the language models that choose the next word from 100,000.

By the end of this lesson you can

  • Compare one-vs-rest with a single softmax model
  • Compute softmax, safely, and explain what temperature does
  • Write categorical cross-entropy and its gradient yˆ−y with one-hot labels
  • Train softmax regression on handwritten digits in NumPy

One-vs-rest

The simplest way to get ten answers from a yes-or-no model: train ten of them. Model 0 answers "is it a 0, or anything else?", model 1 "is it a 1?", and so on. For a new image, ask all ten and pick the one that's most sure. That's one-vs-rest.

It works, but the ten models are trained separately and never compared during training, and their ten probabilities don't add up to 1, so they aren't a probability distribution over the digits. Better: one model that scores all ten classes together.

Softmax

Give each class k its own weights and bias, and so its own score, zk=wk⋅x+bk. Then turn the scores into probabilities with softmax:

softmax⁡(z)k=ezk∑j=1Kezj

In words: raise e to each score, which makes every one positive and keeps their order, then divide by the total so they add to 1. The biggest score gets the biggest probability, and differences in score become ratios: a score 1 higher is e≈2.7 times as likely. With two classes, softmax is exactly lesson 3.9's sigmoid. Here's the whole model on one image:

Softmax regression on one digit64 pixels in, 10 probabilities out
8 × 8 imagepixels 0 to 1⋮x: 64x W + bW: 64 × 100−1.210.321.134.64−0.851.96−270.682.291.410 scoressoftmax0010.0120.0230.794050.056070.0180.0790.0310 probabilities, adding to 1

The model's answer is the digit with the biggest probability: 3, at 0.79. Training changes W and b so that the right digit's probability goes up for every training image.

softmax.ipynb

The second cell divides the scores by a temperature T first. At T=0.5 the top class takes 86%; at T=5 the three are nearly even. Training uses T=1; lesson 13.4 turns the dial to make a language model's choices bolder or safer.

Softmax barsscores in, probabilities out
00.510.165digit 3score 20.061digit 5score 10.738digit 8score 3.50.037digit 9score 0.5

Each probability is e to the power of its score over the temperature, divided by the sum of all four, so they add to 1 and keep the scores' order. The top score, digit 8, gets 0.738.

Wrong way: softmax overflowing

Scores in a real network can be large:

softmax.ipynb

np.exp(1000) is too big for a float, so it's inf, and inf / inf is nan. The fix uses the fact that softmax doesn't change if you subtract the same number from every score (the e−c cancels top and bottom). Subtract the largest, so the biggest score becomes 0 and nothing can overflow:

softmax.ipynb

The scores 1000, 1001 and 1002 give 0.09, 0.245 and 0.665: the same as 0, 1 and 2 would. Every softmax in every library does this. The softmax in step 2 already did; now you know why.

Categorical cross-entropy and its gradient

The loss is lesson 3.10's, with K classes: −log⁡ of the probability given to the true class, averaged over the examples. To write it as one formula, label each example with a one-hot vector y: all 0s except a 1 at the true class (lesson 2.3). Then

ℒ=−1n∑i=1n∑k=1Kyiklog⁡yˆik,

where yˆik is the softmax probability of class k for example i. Only the true class's term survives, since every other yik is 0. This is categorical cross-entropy.

Its gradient with respect to the scores is the neatest result in this stage:

∂ℒ∂z=yˆ−y

The predicted probabilities minus the one-hot truth: push the true class's score up by how far its probability is short of 1, and every other score down by its probability. That's lesson 3.10's p−y again, for every class. With all the examples as rows of X, probabilities P and one-hot labels Y, the gradient for the weights is 1nX⊤(P−Y): one column of 64 numbers for each of the 10 classes.

Handwritten digits

scikit-learn comes with 1,797 handwritten digits, each 8 by 8 pixels, from 43 people. Each pixel is a number from 0 to 16; dividing by 16 puts them between 0 and 1.

digits.ipynb

Each image is a row of 64 numbers in X, read across the rows of pixels. Now softmax regression, trained by full-batch gradient descent:

digits.ipynb

After 500 steps the training loss is 0.169, and 96% of the test digits are read correctly. The second cell shows the one-hot labels: np.eye(10) is a 10×10 identity matrix (lesson 1.4), and indexing it with the labels picks out one row per example.

scikit-learn, both ways:

digits.ipynb

One-vs-rest gets 0.96 and a single softmax model 0.969. Close here; on harder problems the single model usually wins, and it's the one that gives proper probabilities. (scikit-learn's LogisticRegression uses softmax automatically when there are more than two classes.) The stage project builds the full digit reader, with mini-batches, and looks inside its weights.

Check what you learned

Scores are (2, 1, 0). Which is true of softmax’s probabilities?
Predict, then check with the softmax bars: you raise the temperature from 1 to 5. What happens?
The true digit is 3, and the model gives 3 a probability of 0.7. What’s the gradient of the loss with respect to the score for 3?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning