A photo goes into a model, and three scores come out: for cat, for dog and for bird. Scores are not yet probabilities. They can be negative, they do not add to , and nobody can say what "" means. One short formula turns them into : positive numbers that add to , with the biggest score getting the biggest share. That formula is the softmax, and a linear model that ends with it is softmax regression.
This lesson builds the model from logistic regression (P3.A7) and the cross-entropy loss (P1.E3). The same few pieces sit at the end of almost every neural-network classifier, so it is worth taking them slowly.
One score per class
Logistic regression has one weight vector and answers a yes/no question. With classes, give every class its own weight vector and bias. For an input with features, the score of class is
Stack the weight vectors as the rows of a matrix of shape and the biases into a vector , and all scores are computed together:
The vector has entries and is called the logits. The model has numbers to learn. A tiny example with made-up weights, features and classes (cat, dog, bird):
With all three biases equal to :
The cat row scores , the dog row , and the bird row . These are the scores from the start of the lesson.
Why not give the classes the numbers and fit one regression to the number? Because that would say that dog is “between” cat and bird, and that cat is as far from dog as dog is from bird. Class labels have no order. One score per class (and a one-hot label, a vector with a at the true class and elsewhere) treats every class alike.
Softmax: scores to probabilities
The softmax exponentiates every logit and divides by the sum:
(A note on names. P1.E3 called the model’s probabilities and the truth . From here on is the model’s output and is the one-hot truth, the names used in P1.C7 and P1.C11.)
For the exponentials are , and , and their sum is . Dividing gives
Four properties, each easy to check:
- Positive. An exponential is never or negative, so every probability is above . (In exact arithmetic a softmax never says “impossible”.)
- Adds to 1. All the numerators share one denominator, which is their sum.
- Same order as the logits. grows with , so the largest logit has the largest probability. The predicted class is therefore , and the softmax is not needed just to predict.
- Logit differences are log-odds. The ratio of two probabilities is , so . Here the cat is times as probable as the dog, because their logits differ by . For two classes is exactly the log-odds that logistic regression models, which is where the name logits comes from.
Try this. Start from the preset and check the three bars against the numbers above. Raise one logit and watch the other bars shrink (they must, because the total is ). Pick the true class (A) to read the loss and the gradient (the widget shows more digits). Drag the shift slider to and see that nothing moves and nothing breaks.
Only differences matter
Add the same number to every logit. Each numerator gets a factor and so does the denominator, and the factor cancels:
So and give the same probabilities. This is the shift invariance that makes the stable softmax possible: subtract the largest logit first, so that no exponential can overflow (P1.G2 shows the failure and the fix). The widget and all the code on this page do that.
Scaling is different. Multiplying every logit by turns into and the probabilities into : same order, much more confident. Dividing by gives : much less confident. The gaps matter, not the level.
A batch of examples. With examples as the rows of (shape ), the logits are the matrix of shape , and the softmax is applied to each row. In NumPy the maximum and the sum run along the last axis with keepdims=True, so the results broadcast back across the columns (P1.B14). The first code cell below does this.
Two classes: back to logistic regression
With the softmax of the first class is
the sigmoid of the difference of the logits (P1.A5). Check with : . And
so softmax regression with two classes is logistic regression (P3.A7) with weight vector and bias .
The next part is the one idea in this lesson that surprises most people: weight vectors are one too many.
This shows something general. Many different give the identical model: add the same vector to every and the same number to every , and every logit grows by , which is a shift that changes nothing. The model is over-parameterized: of the numbers, only matter. Two ways out:
- Pick a reference class. Set and . Then , and for this is exactly the logistic regression formula. Statistics texts usually use this form (the multinomial logit model).
- Keep all rows and live with it. Most machine-learning code does, and a penalty on the weights (P3.A6) removes the ambiguity by preferring the smallest weights.
For the model trained below, subtracting the third row from every row (and the third bias from every bias) gives the reference form: the weight vectors , and , and the biases . Its probabilities equal the original ones to .
Decision regions
The prediction is . (If two logits tie exactly, NumPy’s argmax returns the first; exact ties are rare with real-valued features.) Class beats class where , and the boundary is where they tie:
That is a straight line in 2-D (a flat plane in 3-D, a hyperplane in general), with normal vector . It is the same boundary as in logistic regression, with the difference of the two weight vectors playing the role of the single one. The region of class is where it beats every other class, which is the intersection of half-planes. So each region is convex, and the regions meet along straight edges. With three classes in 2-D, the three boundary lines all pass through one point (unless the lines are parallel), because if and then . Only the parts of the lines where the two tied classes are the top two are real boundaries.
So softmax regression cannot draw curved boundaries, or a class made of two separate islands. For those you change the features or use a network (P4.3).
The map below uses the trained model of the next sections, on the 24 made-up points. It is the signature picture of the lesson: the shading is the predicted class, and a stronger color means the model is more sure.
For this model the boundaries are between A and B, between A and C, and between B and C. They meet at the point , where all three probabilities are .
The loss: cross-entropy from the logits
For one example whose true class is , the model should give a high value. The loss is the negative log of that probability, the cross-entropy of P1.E3 with a one-hot truth (and, by P1.D10, the negative log-likelihood of the label):
For and the cat as the true class, . Substituting the softmax and simplifying (P1.E3, P1.G2) gives the form that software actually computes:
For with the third class true, and nats. For the naive softmax gives NaN, but and the loss is if the first class is true and if the second class is true. The loss is computed from the logits, never from a softmax followed by a log. That is why PyTorch’s nn.CrossEntropyLoss expects logits and applies the softmax inside (P2.7); giving it probabilities by mistake trains badly.
Over a data set of examples the training loss is the average, . For a model that knows nothing (, all probabilities ) it is : for three classes.
The gradient: p minus y
Gradient descent (P1.F3) needs the gradient of . Start with the logits. The derivation is short, and the result is among the most useful in the course (P1.C7 and P1.C11 derive it with Jacobians and matrix calculus):
For the cat example, . The true class has a negative entry (raise its logit), each wrong class has a positive entry equal to its own probability (lower it), the entries add to , and the vector is only when .
Go deeper Why the gradient is p minus y
Write . The derivative of with respect to is if and otherwise, which is . The derivative of with respect to is, by the chain rule on the logarithm, . Adding the two gives .
Because , the chain rule continues: depends on only through , so , and . Hence
Stacking these entries gives matrices and vectors: for one example, (an outer product, shape , the same shape as ) and . For the cat example with :
For a data set, stack the probabilities and one-hot labels into and (both ) and average:
The first has shape , like .
One gradient step. With learning rate (P1.F3), the update is and . On the cat example, the weight rows become , and and the biases . The new logits for the same input are , the new probabilities , and the loss falls from to .
Check a gradient numerically. A formula this neat is easy to get wrong by a transpose or a missing . The second code cell nudges every entry of and by and compares the loss change with the formula (P1.C11 describes the habit). On the 24-point data set with random weights the two agree to about .
Training on a small data set
The data set is made up for this lesson: 24 points in 2-D, 8 per class, drawn around three centres with a fixed seed and rounded to one decimal, so every number here can be reproduced. The three groups overlap a little, so no straight lines separate them perfectly. Training starts from and and uses full-batch gradient descent with .
At the start every probability is , the loss is , and the gradient for is
The step moves in the direction (by half that, since ), toward the lower left where the class-A points are, and toward the right. The results of the run:
- Step : loss , accuracy of ().
- Step : loss .
- Step : loss , accuracy of ().
- Step : loss , accuracy .
The loss falls quickly and then slowly. The lowest the loss can go on these points, found by a library solver without a penalty, is . The two points that stay wrong are one class-A point near the upper left, at , which sits among class C, and one class-C point at , in the middle of the picture, where the model gives class A and the true class .
After 200 steps the weight vectors are , and , and the biases are . The three weight vectors add up to , and so do the three biases. That is not a coincidence: the gradient columns add to (since ), so with plain gradient descent started at zero, the sum of the weight vectors never moves from zero. The code confirms it. It is the same freedom as above: gradient descent never pushes in the direction that would change only the over-parameterized part.
Go deeper The loss is convex, but its minimum is not a single point
The loss is a convex function of (the log-sum-exp is convex, P1.F2), and is a linear function of , so the training loss is convex in the parameters. Gradient descent with a small enough step cannot get stuck in a bad local minimum. But the loss is flat along the shift directions of the last section, so the minimizer is a whole flat family of parameter settings ( free directions), not one point, unless a penalty or a reference class removes the freedom. A minimizer exists only for data that cannot be separated; see the next box.
Go deeper When the classes can be separated, the weights never stop growing
Suppose some gives every training point a true-class logit strictly larger than every other logit. Multiply the parameters by a factor : every gap grows by , so every rises and the loss falls. It keeps falling as grows and approaches without reaching it. So the best parameters are infinitely large, and gradient descent makes the weights grow without end (more and more slowly), with probabilities that get closer and closer to and on the training data. Over-confident outputs are the result. The usual cure is a penalty on the weight size (L2, P3.A6), which gives a finite answer. scikit-learn applies one by default, as described below. The toy data set above overlaps on purpose, so its minimum is finite.
Temperature: a preview
Before the softmax, divide the logits by a number , the temperature: . For :
| Probabilities | |
|---|---|
A low sharpens the distribution toward for the largest logit; a high flattens it toward . The order never changes (for ), so the predicted class does not either. Dividing by is the same as scaling the logits by , as in the section “Only differences matter”. Language models use when they sample the next token (P10.A5), and the entropy changes this way in P1.E2. Try it with the temperature slider in the first widget.
One-vs-rest versus softmax
Another way to handle classes is one-vs-rest: train separate binary logistic regressions (P3.A7), the -th answering “class or not?”, and predict the class whose model gives the highest score. It reuses binary tools, but the models are trained independently, and their outputs need not add to . On the 24 points, a nearly unregularized one-vs-rest fit gives the scores at the origin (sum ) and at (sum ). Normalizing them afterwards gives probabilities, but they are not what any loss trained.
Softmax regression is one model: the scores compete inside one softmax, and one cross-entropy loss trains all of the weights together. Its outputs are a probability distribution by construction. The two methods minimize different losses, so their predictions can differ.
Two previews
Label smoothing (P4.17). Training with one-hot targets keeps pushing toward , which rewards ever larger logit gaps. Label smoothing replaces the one-hot target by . For and , becomes , and the gradient is still minus the target.
Calibration (P3.A10). Whether a softmax output of is right nine times in ten is a separate question, taken up in P3.A10.
Intuition
Each class has a “detector”: a weight vector that measures how much the input looks like that class. The softmax lets the detectors compete for one unit of belief. Adding the same amount to every detector does not change who wins or by how much, because only the gaps decide how belief is shared. Training raises the detector of the true class and lowers the others, in proportion to how much belief each one currently holds.
Math
Model: , , .
Loss: .
Gradients: , , . For a batch, .
Invariances: ; gives ; boundary between classes and : .
Code
The NumPy version is in the Try it cells below. With scikit-learn, one call fits the multinomial model. (These blocks are static: scikit-learn and PyTorch are not available in the in-browser runner, and the output shown comes from running them locally with scikit-learn 1.8 on the 24-point data set of this lesson, X and y.)
import numpy as np
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(C=np.inf, max_iter=1000)
clf.fit(X, y)
print(clf.coef_.shape, clf.intercept_.shape)
print(clf.coef_)
print(clf.intercept_)
print(clf.score(X, y))
print(clf.predict_proba([[0.0, 0.0]]))(3, 2) (3,)
[[-2.872 -1.226]
[ 2.944 0.007]
[-0.072 1.219]]
[-0.946 -0.665 1.611]
0.9166666666666666
[[0.066 0.087 0.847]]Facts about scikit-learn 1.8 that matter here. For three or more classes, LogisticRegression minimizes the multinomial (softmax) loss with every solver except liblinear, which raises an error for multi-class data; there is no multi_class argument any more. coef_ has shape (K, d) (for two classes it has shape (1, d), the single logistic-regression weight vector). And regularization is on by default: an L2 penalty with C=1.0. On these 24 points LogisticRegression() gives smaller weights and an accuracy of (21 of 24), against with C=np.inf (no penalty). (scikit-learn 1.8 prints a harmless warning about C and penalty for C=np.inf; C=1e10 gives the same fit, to three decimals, without it.) The values above are the converged solution. The 200-step NumPy run is still on its way there (its loss is against ).
In PyTorch, F.cross_entropy takes logits and class indices, and does the log-sum-exp inside:
import torch
import torch.nn.functional as F
z = torch.tensor([[1.0, 2.0, 3.0], [1000.0, 0.0, 0.0]])
y = torch.tensor([2, 1])
print(F.cross_entropy(z, y, reduction="none"))tensor([4.0761e-01, 1.0000e+03])Try it
Three cells, NumPy only; each runs in the browser. Cell 1 checks the softmax properties, the two-class case and the batch form. Cell 2 compares the gradient formula with finite differences on the 24-point data set. Cell 3 trains the model and prints the numbers quoted in this lesson. Then change something: set eta to and see what the loss does, or change the seed.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Check your understanding
The logits give the cat the probability . Add to every logit. What is the cat's probability now?
The factor appears in every numerator and in the denominator and cancels, so the probabilities do not change. The cat does not move toward , since the gaps between the logits are the same as before. The relative size of the logits plays no role: the gaps do. A probability can never exceed , so a product with is impossible.
A two-class softmax regression has , and both biases . Which logistic regression gives the same probability for class ?
The probability of class is , and . The sum adds the two weight vectors, which is not what a difference of logits does. The vectors and alone are each only one of the two scores.
The probabilities are and the true class is the third. What is the gradient of the cross-entropy loss with respect to the logits?
The gradient is with , so the third entry is and the others keep their probabilities. The gradient with all signs flipped would push the wrong way: gradient descent subtracts it, so the true logit must have a negative entry. The unchanged vector ignores the label. A vector with zeros for the wrong classes forgets that their logits must be lowered.
In softmax regression with three classes and two features, what is the boundary between class and class ?
The softmax keeps the order of the logits, so class beats class exactly where , and the boundary is where they tie. That equation is linear in , so it is a straight line. The softmax is nonlinear, but the comparison of two logits does not need it. The level is not a boundary when a third class takes some of the probability. The line has no special meaning, since adding a constant to all logits would move it.
The logits are and the true class is the second. Computed from the logits as , what is the loss?
The log-sum-exp is to many decimals, and the true logit is , so the loss is : the model was sure about the wrong class. The value would be the loss if the first class were true. The naive route (softmax, then log) does give NaN, which is why the loss is computed from the logits. The value is the loss of a model with equal probabilities.
Exercises
- Compute the softmax of by hand.
Show answer
The exponentials are and their sum is , so . - Two classes with logits . Find using the sigmoid.
Show answer
. Directly: . - A model gives for , and the true class is the second. Write , and .
Show answer
, and is the same vector. . - Take , , and zero biases. Which class is predicted at , and what is the boundary between classes and ?
Show answer
The logits are , so class is predicted. The boundary between classes and is , that is , a straight line. - Compute the softmax of at and show that it equals the softmax of .
Show answer
Dividing by doubles the logits to . The exponentials are with sum , so . - A classifier takes features and has classes. How many numbers does the model have, and how many of them matter after removing the shift freedom?
Show answer
numbers, and matter.
Next: P3.A9 measures how well a classifier does with the confusion matrix, precision, recall and ROC curves, and P3.A10 asks whether its probabilities can be trusted. P4.8 uses the gradient to start backpropagation through a whole network, P4.6 compares the cross-entropy with other losses, and P10.A5 returns to temperature when a language model picks the next token.