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 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 its own weights and bias, and so its own score, . Then turn the scores into probabilities with softmax:
In words: raise 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 times as likely. With two classes, softmax is exactly lesson 3.9's sigmoid. Here's the whole model on one image:
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.
The second cell divides the scores by a temperature first. At the top class takes 86%; at the three are nearly even. Training uses ; lesson 13.4 turns the dial to make a language model's choices bolder or safer.
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:
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 cancels top and bottom). Subtract the largest, so the biggest score becomes 0 and nothing can overflow:
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 classes: 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 : all 0s except a 1 at the true class (lesson 2.3). Then
where is the softmax probability of class for example . Only the true class's term survives, since every other is 0. This is categorical cross-entropy.
Its gradient with respect to the scores is the neatest result in this stage:
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 again, for every class. With all the examples as rows of , probabilities and one-hot labels , the gradient for the weights is : 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.
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:
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 identity matrix (lesson 1.4), and indexing it with the labels picks out one row per example.
scikit-learn, both ways:
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
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.
- Goodfellow, Bengio and Courville, Deep Learning, chapter 6: Deep Feedforward Networks: softmax units for many classes, and their loss (6.2.2.3)
- Goodfellow, Bengio and Courville, Deep Learning, chapter 4: Numerical Computation: softmax overflow and the subtract-the-maximum fix (4.1)
- Alpaydin and Kaynak, Optical Recognition of Handwritten Digits, UCI Machine Learning Repository, 1998: the 8 × 8 digits that scikit-learn’s load_digits loads
- scikit-learn: Multiclass and multioutput algorithms: one-vs-rest, and models that handle many classes directly