Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Softmax regression

P3.A840 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Most classifiers must choose between more than two classes. Softmax regression is the basic way to do it: one linear score per class, turned into probabilities that add to 1, trained by the cross-entropy loss. Its pieces (logits, softmax, the gradient p − y) are reused almost unchanged by deep networks.

  • The last layer of a neural-network classifier is exactly this model, applied to learned features instead of raw ones. Backpropagation starts from the gradient p − y that this lesson derives. (P4.8: Backpropagation: step by step with numbers)
  • A language model chooses the next token with a softmax over its whole vocabulary, and the temperature that divides the logits sets how adventurous the choice is. (P10.A5: Decoding strategies, coming soon)
  • Attention turns a row of scores into weights that add to 1 with a softmax, and scaling the scores controls how sharp the weights are. (P7.4: Scaled dot-product attention, coming soon)
  • A softmax output of 0.9 is not guaranteed to be right nine times in ten. Checking that is calibration. (P3.A10: Calibration and class imbalance)

Before this: Logistic regression, Cross-entropy, Matrix calculus for ML

After this lesson you can

  • Compute the logits z = Wx + b, the softmax probabilities and the predicted class for a small example by hand
  • Explain why adding the same number to every logit changes nothing, show that two classes reduce to logistic regression, and say why one class can serve as the reference
  • Show that the boundary between two classes is a straight line (or flat surface), and read the decision regions of a trained model
  • Derive the gradient p − y of the cross-entropy loss with respect to the logits, extend it to W and b, check it with finite differences, and train a model with gradient descent

A photo goes into a model, and three scores come out: 22 for cat, 11 for dog and 0.10.1 for bird. Scores are not yet probabilities. They can be negative, they do not add to 11, and nobody can say what "22" means. One short formula turns them into (0.659, 0.242, 0.099)(0.659,\,0.242,\,0.099): positive numbers that add to 11, 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 KK classes, give every class its own weight vector and bias. For an input x\mathbf{x} with dd features, the score of class kk is

zk=wk⋅x+bk.z_k=\mathbf{w}_k\cdot\mathbf{x}+b_k .

Stack the KK weight vectors as the rows of a matrix W\mathbf{W} of shape (K,d)(K,d) and the biases into a vector b\mathbf{b}, and all scores are computed together:

z=Wx+b.\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}.

The vector z\mathbf{z} has KK entries and is called the logits. The model has K(d+1)K(d+1) numbers to learn. A tiny example with made-up weights, d=2d=2 features and K=3K=3 classes (cat, dog, bird):

W=(10010.050),x=(21)\mathbf{W}=\begin{pmatrix}1&0\\0&1\\0.05&0\end{pmatrix},\quad \mathbf{x}=\begin{pmatrix}2\\1\end{pmatrix}

With all three biases equal to 00:

z=Wx+b=(210.1).\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}=\begin{pmatrix}2\\1\\0.1\end{pmatrix}.

The cat row scores 1⋅2+0⋅1=21\cdot2+0\cdot1=2, the dog row 0⋅2+1⋅1=10\cdot2+1\cdot1=1, and the bird row 0.05⋅2+0=0.10.05\cdot2+0=0.1. These are the scores from the start of the lesson.

Why not give the classes the numbers 1,2,31,2,3 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 11 at the true class and 00 elsewhere) treats every class alike.

Softmax: scores to probabilities

The softmax exponentiates every logit and divides by the sum:

pk=softmax(z)k=ezk∑m=1Kezm.p_k=\mathrm{softmax}(\mathbf{z})_k=\frac{\mathrm{e}^{z_k}}{\sum_{m=1}^{K}\mathrm{e}^{z_m}} .

(A note on names. P1.E3 called the model’s probabilities q\mathbf{q} and the truth p\mathbf{p}. From here on p\mathbf{p} is the model’s output and y\mathbf{y} is the one-hot truth, the names used in P1.C7 and P1.C11.)

For z=(2,1,0.1)\mathbf{z}=(2,1,0.1) the exponentials are e2=7.389\mathrm{e}^{2}=7.389, e1=2.718\mathrm{e}^{1}=2.718 and e0.1=1.105\mathrm{e}^{0.1}=1.105, and their sum is 11.2111.21. Dividing gives

p=(0.659, 0.242, 0.099).\mathbf{p}=(0.659,\ 0.242,\ 0.099).

Four properties, each easy to check:

  • Positive. An exponential is never 00 or negative, so every probability is above 00. (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. ex\mathrm{e}^{x} grows with xx, so the largest logit has the largest probability. The predicted class is therefore arg⁡max⁡kzk\arg\max_k z_k, and the softmax is not needed just to predict.
  • Logit differences are log-odds. The ratio of two probabilities is pk/pm=ezk−zmp_k/p_m=\mathrm{e}^{z_k-z_m}, so zk−zm=ln⁡(pk/pm)z_k-z_m=\ln(p_k/p_m). Here the cat is e1=2.718\mathrm{e}^{1}=2.718 times as probable as the dog, because their logits differ by 11. For two classes z1−z2z_1-z_2 is exactly the log-odds that logistic regression models, which is where the name logits comes from.

Logit sliders to probability bars

Class A 0.6590
Class B 0.2424
Class C 0.0986
True class:
logits z + c: 2.0, 1.0, 0.1 probabilities p: 0.6590, 0.2424, 0.0986 sum of p: 1.0000 largest: class A loss −ln ptrue = LSE − ztrue: 0.4170 gradient p − y: −0.3410, 0.2424, 0.0986

Computed the stable way: the largest scaled logit is subtracted before the exponential, so even a shift of 1000 gives no overflow. Move c and the probabilities, loss and gradient do not change (the readout of z + c does). T = 1 is the plain softmax.

Logit sliders to probability bars. Drag the logits of 3 or 4 classes: the bars show the softmax probabilities, which always add to 1. Pick the true class to see the cross-entropy loss (LSE minus the true logit) and the gradient p minus y, which is orange. The shift slider adds c to every logit and nothing changes; the temperature slider divides the logits by T.

Try this. Start from the preset (2,1,0.1)(2,1,0.1) and check the three bars against the numbers above. Raise one logit and watch the other bars shrink (they must, because the total is 11). Pick the true class (A) to read the loss 0.41700.4170 and the gradient (−0.341, 0.242, 0.099)(-0.341,\,0.242,\,0.099) (the widget shows more digits). Drag the shift slider to +1000+1000 and see that nothing moves and nothing breaks.

Only differences matter

Add the same number cc to every logit. Each numerator gets a factor ec\mathrm{e}^{c} and so does the denominator, and the factor cancels:

ezk+c∑mezm+c=ec ezkec∑mezm=pk.\frac{\mathrm{e}^{z_k+c}}{\sum_m\mathrm{e}^{z_m+c}}=\frac{\mathrm{e}^{c}\,\mathrm{e}^{z_k}}{\mathrm{e}^{c}\sum_m\mathrm{e}^{z_m}}=p_k .

So (2,1,0.1)(2,1,0.1) and (12,11,10.1)(12,11,10.1) 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 22 turns (2,1,0.1)(2,1,0.1) into (4,2,0.2)(4,2,0.2) and the probabilities into (0.864, 0.117, 0.019)(0.864,\,0.117,\,0.019): same order, much more confident. Dividing by 22 gives (0.502, 0.304, 0.194)(0.502,\,0.304,\,0.194): much less confident. The gaps matter, not the level.

A batch of examples. With NN examples as the rows of X\mathbf{X} (shape (N,d)(N,d)), the logits are the matrix Z=XW⊤+b\mathbf{Z}=\mathbf{X}\mathbf{W}^\top+\mathbf{b} of shape (N,K)(N,K), 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 (N,1)(N,1) results broadcast back across the KK columns (P1.B14). The first code cell below does this.

Two classes: back to logistic regression

With K=2K=2 the softmax of the first class is

p1=ez1ez1+ez2=11+e−(z1−z2)=σ(z1−z2),\begin{aligned} p_1&=\frac{\mathrm{e}^{z_1}}{\mathrm{e}^{z_1}+\mathrm{e}^{z_2}}\\ &=\frac{1}{1+\mathrm{e}^{-(z_1-z_2)}}\\ &=\sigma(z_1-z_2), \end{aligned}

the sigmoid of the difference of the logits (P1.A5). Check with z=(2,0.5)\mathbf{z}=(2,0.5): p1=0.8176=σ(1.5)p_1=0.8176=\sigma(1.5). And

z1−z2=(w1−w2)⋅x+(b1−b2),z_1-z_2=(\mathbf{w}_1-\mathbf{w}_2)\cdot\mathbf{x}+(b_1-b_2),

so softmax regression with two classes is logistic regression (P3.A7) with weight vector w=w1−w2\mathbf{w}=\mathbf{w}_1-\mathbf{w}_2 and bias b=b1−b2b=b_1-b_2.

The next part is the one idea in this lesson that surprises most people: KK weight vectors are one too many.

This shows something general. Many different (W,b)(\mathbf{W},\mathbf{b}) give the identical model: add the same vector v\mathbf{v} to every wk\mathbf{w}_k and the same number cc to every bkb_k, and every logit grows by v⋅x+c\mathbf{v}\cdot\mathbf{x}+c, which is a shift that changes nothing. The model is over-parameterized: of the K(d+1)K(d+1) numbers, only (K−1)(d+1)(K-1)(d+1) matter. Two ways out:

  • Pick a reference class. Set wK=0\mathbf{w}_K=\mathbf{0} and bK=0b_K=0. Then pk=ezk/(1+∑m<Kezm)p_k=\mathrm{e}^{z_k}/(1+\sum_{m<K}\mathrm{e}^{z_m}), and for K=2K=2 this is exactly the logistic regression formula. Statistics texts usually use this form (the multinomial logit model).
  • Keep all KK 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 (−2.08,−2.04)(-2.08,-2.04), (2.27,−1.13)(2.27,-1.13) and (0,0)(0,0), and the biases (−1.67,−1.46,0)(-1.67,-1.46,0). Its probabilities equal the original ones to 10−1510^{-15}.

Decision regions

The prediction is y^=arg⁡max⁡kzk\hat{y}=\arg\max_k z_k. (If two logits tie exactly, NumPy’s argmax returns the first; exact ties are rare with real-valued features.) Class kk beats class mm where zk>zmz_k>z_m, and the boundary is where they tie:

(wk−wm)⋅x+(bk−bm)=0.(\mathbf{w}_k-\mathbf{w}_m)\cdot\mathbf{x}+(b_k-b_m)=0 .

That is a straight line in 2-D (a flat plane in 3-D, a hyperplane in general), with normal vector wk−wm\mathbf{w}_k-\mathbf{w}_m. 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 kk is where it beats every other class, which is the intersection of K−1K-1 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 z1=z2z_1=z_2 and z1=z3z_1=z_3 then z2=z3z_2=z_3. 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.

Three classes, linear boundaries

x₁x₂
● Class A■ Class B▲ Class C
logits z: −1.21, 0.72, 0.49 probabilities p: 0.0753, 0.5164, 0.4083 predicted class (largest logit): B

Shading shows the predicted class, and the color is stronger where the model is more sure. Where two regions meet, their logits are equal and the two probabilities tie. Tap the map or use the sliders to move the query point. The model is the one trained in the lesson (200 steps of gradient descent on the 24 made-up points).

Decision regions of the trained 3-class softmax model on the 24 made-up training points (circles: class A, squares: class B, triangles: class C). The boundaries are straight lines. Move the query point with the sliders or by tapping the map, and read its logits and probabilities. Near a boundary two probabilities are close.

For this model the boundaries are −4.35x1−0.91x2−0.20=0-4.35x_1-0.91x_2-0.20=0 between A and B, −2.08x1−2.04x2−1.67=0-2.08x_1-2.04x_2-1.67=0 between A and C, and 2.27x1−1.13x2−1.46=02.27x_1-1.13x_2-1.46=0 between B and C. They meet at the point (0.16,−0.98)(0.16,-0.98), where all three probabilities are 13\tfrac13.

The loss: cross-entropy from the logits

For one example whose true class is cc, the model should give pcp_c 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):

L=−ln⁡pc=−∑kykln⁡pk.L=-\ln p_c=-\sum_{k}y_k\ln p_k .

For p=(0.659,0.242,0.099)\mathbf{p}=(0.659,0.242,0.099) and the cat as the true class, L=−ln⁡0.659=0.4170L=-\ln0.659=0.4170. Substituting the softmax and simplifying (P1.E3, P1.G2) gives the form that software actually computes:

L=LSE(z)−zc,LSE(z)=ln⁡∑mezm.\begin{aligned} L&=\mathrm{LSE}(\mathbf{z})-z_c,\\ \mathrm{LSE}(\mathbf{z})&=\ln\sum_m\mathrm{e}^{z_m}. \end{aligned}

For z=(1,2,3)\mathbf{z}=(1,2,3) with the third class true, p=(0.0900,0.2447,0.6652)\mathbf{p}=(0.0900,0.2447,0.6652) and L=0.4076L=0.4076 nats. For z=(1000,0,0)\mathbf{z}=(1000,0,0) the naive softmax gives NaN, but LSE=1000\mathrm{LSE}=1000 and the loss is 00 if the first class is true and 10001000 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 NN examples the training loss is the average, L=1N∑n=1NLn\mathcal{L}=\frac1N\sum_{n=1}^{N}L_n. For a model that knows nothing (W=0\mathbf{W}=\mathbf{0}, all probabilities 1K\tfrac1K) it is ln⁡K\ln K: ln⁡3=1.0986\ln3=1.0986 for three classes.

The gradient: p minus y

Gradient descent (P1.F3) needs the gradient of LL. 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):

∂L∂z=p−y.\frac{\partial L}{\partial \mathbf{z}}=\mathbf{p}-\mathbf{y}.

For the cat example, p−y=(0.659−1, 0.242, 0.099)=(−0.341, 0.2424, 0.0986)\mathbf{p}-\mathbf{y}=(0.659-1,\ 0.242,\ 0.099)=(-0.341,\ 0.2424,\ 0.0986). 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 00, and the vector is 0\mathbf{0} only when p=y\mathbf{p}=\mathbf{y}.

Go deeper Why the gradient is p minus y

Write L=LSE(z)−zcL=\mathrm{LSE}(\mathbf{z})-z_c. The derivative of −zc-z_c with respect to zkz_k is −1-1 if k=ck=c and 00 otherwise, which is −yk-y_k. The derivative of LSE\mathrm{LSE} with respect to zkz_k is, by the chain rule on the logarithm, ezk/∑mezm=pk\mathrm{e}^{z_k}/\sum_m\mathrm{e}^{z_m}=p_k. Adding the two gives pk−ykp_k-y_k.

Because z=Wx+b\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}, the chain rule continues: zkz_k depends on WkjW_{kj} only through WkjxjW_{kj}x_j, so ∂zk/∂Wkj=xj\partial z_k/\partial W_{kj}=x_j, and ∂zk/∂bk=1\partial z_k/\partial b_k=1. Hence

∂L∂Wkj=(pk−yk) xj,∂L∂bk=pk−yk.\begin{aligned} \frac{\partial L}{\partial W_{kj}}&=(p_k-y_k)\,x_j,\\ \frac{\partial L}{\partial b_k}&=p_k-y_k . \end{aligned}

Stacking these entries gives matrices and vectors: for one example, ∇WL=(p−y) x⊤\nabla_{\mathbf{W}}L=(\mathbf{p}-\mathbf{y})\,\mathbf{x}^\top (an outer product, shape (K,d)(K,d), the same shape as W\mathbf{W}) and ∇bL=p−y\nabla_{\mathbf{b}}L=\mathbf{p}-\mathbf{y}. For the cat example with x=(2,1)\mathbf{x}=(2,1):

∇WL=(−0.682−0.3410.4850.2420.1970.099).\nabla_{\mathbf{W}}L=\begin{pmatrix}-0.682&-0.341\\0.485&0.242\\0.197&0.099\end{pmatrix}.

For a data set, stack the probabilities and one-hot labels into P\mathbf{P} and Y\mathbf{Y} (both (N,K)(N,K)) and average:

∇WL=1N(P−Y)⊤X,∇bL=1N∑n(pn−yn).\begin{aligned} \nabla_{\mathbf{W}}\mathcal{L}&=\frac1N(\mathbf{P}-\mathbf{Y})^\top\mathbf{X},\\ \nabla_{\mathbf{b}}\mathcal{L}&=\frac1N\sum_n(\mathbf{p}_n-\mathbf{y}_n). \end{aligned}

The first has shape (K,d)(K,d), like W\mathbf{W}.

One gradient step. With learning rate η=0.5\eta=0.5 (P1.F3), the update is W←W−η ∇WL\mathbf{W}\leftarrow\mathbf{W}-\eta\,\nabla_{\mathbf{W}}L and b←b−η ∇bL\mathbf{b}\leftarrow\mathbf{b}-\eta\,\nabla_{\mathbf{b}}L. On the cat example, the weight rows become (1.341,0.171)(1.341,0.171), (−0.242,0.879)(-0.242,0.879) and (−0.049,−0.049)(-0.049,-0.049) and the biases (0.171,−0.121,−0.049)(0.171,-0.121,-0.049). The new logits for the same input are (3.023,0.273,−0.196)(3.023,0.273,-0.196), the new probabilities (0.906,0.058,0.036)(0.906,0.058,0.036), and the loss falls from 0.41700.4170 to 0.09890.0989.

Check a gradient numerically. A formula this neat is easy to get wrong by a transpose or a missing 1N\frac1N. The second code cell nudges every entry of W\mathbf{W} and b\mathbf{b} by ±10−6\pm10^{-6} 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 10−1010^{-10}.

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 W=0\mathbf{W}=\mathbf{0} and b=0\mathbf{b}=\mathbf{0} and uses full-batch gradient descent with η=0.5\eta=0.5.

At the start every probability is 13\tfrac13, the loss is ln⁡3=1.0986\ln3=1.0986, and the gradient for W\mathbf{W} is

∇WL=(0.5780.372−0.6350.2310.057−0.603).\nabla_{\mathbf{W}}\mathcal{L}=\begin{pmatrix}0.578&0.372\\-0.635&0.231\\0.057&-0.603\end{pmatrix}.

The step moves wA\mathbf{w}_A in the direction (−0.58,−0.37)(-0.58,-0.37) (by half that, since η=0.5\eta=0.5), toward the lower left where the class-A points are, and wB\mathbf{w}_B toward the right. The results of the run:

  • Step 11: loss 0.62720.6272, accuracy 2121 of 2424 (0.8750.875).
  • Step 1010: loss 0.35450.3545.
  • Step 5050: loss 0.29930.2993, accuracy 2222 of 2424 (0.9170.917).
  • Step 200200: loss 0.27510.2751, accuracy 0.9170.917.

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 0.26950.2695. The two points that stay wrong are one class-A point near the upper left, at (−2.5,2.7)(-2.5,2.7), which sits among class C, and one class-C point at (−1.1,−0.2)(-1.1,-0.2), in the middle of the picture, where the model gives class A 0.730.73 and the true class 0.260.26.

After 200 steps the weight vectors are (−2.14,−0.98)(-2.14,-0.98), (2.21,−0.07)(2.21,-0.07) and (−0.06,1.05)(-0.06,1.05), and the biases are (−0.62,−0.42,1.04)(-0.62,-0.42,1.04). The three weight vectors add up to 0\mathbf{0}, and so do the three biases. That is not a coincidence: the gradient columns add to 00 (since ∑k(pk−yk)=0\sum_k(p_k-y_k)=0), 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 LSE(z)−zc\mathrm{LSE}(\mathbf{z})-z_c is a convex function of z\mathbf{z} (the log-sum-exp is convex, P1.F2), and z\mathbf{z} is a linear function of (W,b)(\mathbf{W},\mathbf{b}), 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 (d+1d+1 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 (W,b)(\mathbf{W},\mathbf{b}) gives every training point a true-class logit strictly larger than every other logit. Multiply the parameters by a factor t>1t>1: every gap grows by tt, so every pcp_c rises and the loss falls. It keeps falling as tt grows and approaches 00 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 00 and 11 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 T>0T>0, the temperature: softmax(z/T)\mathrm{softmax}(\mathbf{z}/T). For z=(2,1,0)\mathbf{z}=(2,1,0):

TTProbabilities
0.50.50.867, 0.117, 0.0160.867,\ 0.117,\ 0.016
110.665, 0.245, 0.0900.665,\ 0.245,\ 0.090
220.506, 0.307, 0.1860.506,\ 0.307,\ 0.186
1001000.337, 0.333, 0.3300.337,\ 0.333,\ 0.330

A low TT sharpens the distribution toward 11 for the largest logit; a high TT flattens it toward 1K\tfrac1K. The order never changes (for T>0T>0), so the predicted class does not either. Dividing by TT is the same as scaling the logits by 1/T1/T, as in the section “Only differences matter”. Language models use TT 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 KK classes is one-vs-rest: train KK separate binary logistic regressions (P3.A7), the kk-th answering “class kk or not?”, and predict the class whose model gives the highest score. It reuses binary tools, but the KK models are trained independently, and their outputs need not add to 11. On the 24 points, a nearly unregularized one-vs-rest fit gives the scores (0.035,0.043,0.244)(0.035,0.043,0.244) at the origin (sum 0.320.32) and (0.001,0.973,0.081)(0.001,0.973,0.081) at (2,−1)(2,-1) (sum 1.061.06). Normalizing them afterwards gives probabilities, but they are not what any loss trained.

Softmax regression is one model: the KK 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 pcp_c toward 11, which rewards ever larger logit gaps. Label smoothing replaces the one-hot target by (1−ε)y+ε/K(1-\varepsilon)\mathbf{y}+\varepsilon/K. For K=3K=3 and ε=0.1\varepsilon=0.1, (1,0,0)(1,0,0) becomes (0.933,0.033,0.033)(0.933,0.033,0.033), and the gradient is still p\mathbf{p} minus the target.

Calibration (P3.A10). Whether a softmax output of 0.90.9 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: z=Wx+b\mathbf{z}=\mathbf{W}\mathbf{x}+\mathbf{b}, p=softmax(z)\mathbf{p}=\mathrm{softmax}(\mathbf{z}), pk=ezk/∑mezmp_k=\mathrm{e}^{z_k}/\sum_m\mathrm{e}^{z_m}.

Loss: L=−∑kykln⁡pk=LSE(z)−y⊤zL=-\sum_ky_k\ln p_k=\mathrm{LSE}(\mathbf{z})-\mathbf{y}^\top\mathbf{z}.

Gradients: ∂L/∂z=p−y\partial L/\partial\mathbf{z}=\mathbf{p}-\mathbf{y}, ∇WL=(p−y)x⊤\nabla_{\mathbf{W}}L=(\mathbf{p}-\mathbf{y})\mathbf{x}^\top, ∇bL=p−y\nabla_{\mathbf{b}}L=\mathbf{p}-\mathbf{y}. For a batch, ∇WL=1N(P−Y)⊤X\nabla_{\mathbf{W}}\mathcal{L}=\frac1N(\mathbf{P}-\mathbf{Y})^\top\mathbf{X}.

Invariances: softmax(z+c1)=softmax(z)\mathrm{softmax}(\mathbf{z}+c\mathbf{1})=\mathrm{softmax}(\mathbf{z}); K=2K=2 gives p1=σ(z1−z2)p_1=\sigma(z_1-z_2); boundary between classes kk and mm: (wk−wm)⋅x+bk−bm=0(\mathbf{w}_k-\mathbf{w}_m)\cdot\mathbf{x}+b_k-b_m=0.

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 0.8750.875 (21 of 24), against 0.9170.917 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 0.27510.2751 against 0.26950.2695).

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 55 and see what the loss does, or change the seed.

Try it: softmax properties, two classes, a batch

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: check the gradient with finite differences

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: train softmax regression on 24 points

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Check your understanding

  1. The logits (2,1,0.1)(2,1,0.1) give the cat the probability 0.6590.659. Add 100100 to every logit. What is the cat's probability now?

  2. A two-class softmax regression has w1=(3,0)\mathbf{w}_1=(3,0), w2=(1,2)\mathbf{w}_2=(1,2) and both biases 00. Which logistic regression gives the same probability for class 11?

  3. The probabilities are p=(0.2,0.5,0.3)\mathbf{p}=(0.2,0.5,0.3) and the true class is the third. What is the gradient of the cross-entropy loss with respect to the logits?

  4. In softmax regression with three classes and two features, what is the boundary between class 11 and class 22?

  5. The logits are (1000,0,0)(1000,0,0) and the true class is the second. Computed from the logits as LSE(z)−zc\mathrm{LSE}(\mathbf{z})-z_c, what is the loss?

Exercises

  1. Compute the softmax of (0,0,ln⁡2)(0,0,\ln2) by hand.
    Show answerThe exponentials are 1,1,21,1,2 and their sum is 44, so p=(0.25,0.25,0.5)\mathbf{p}=(0.25,0.25,0.5).
  2. Two classes with logits (1,−1)(1,-1). Find p1p_1 using the sigmoid.
    Show answerp1=σ(1−(−1))=σ(2)=0.8808p_1=\sigma(1-(-1))=\sigma(2)=0.8808. Directly: e1/(e1+e−1)=2.718/3.086=0.8808\mathrm{e}^{1}/(\mathrm{e}^{1}+\mathrm{e}^{-1})=2.718/3.086=0.8808.
  3. A model gives p=(0.1,0.7,0.2)\mathbf{p}=(0.1,0.7,0.2) for x=(2,−1)\mathbf{x}=(2,-1), and the true class is the second. Write ∂L/∂z\partial L/\partial\mathbf{z}, ∇WL\nabla_{\mathbf{W}}L and ∇bL\nabla_{\mathbf{b}}L.
    Show answerp−y=(0.1,−0.3,0.2)\mathbf{p}-\mathbf{y}=(0.1,-0.3,0.2), and ∇bL\nabla_{\mathbf{b}}L is the same vector. ∇WL=(p−y)x⊤=(0.2−0.1−0.60.30.4−0.2)\nabla_{\mathbf{W}}L=(\mathbf{p}-\mathbf{y})\mathbf{x}^\top=\begin{pmatrix}0.2&-0.1\\-0.6&0.3\\0.4&-0.2\end{pmatrix}.
  4. Take w1=(1,0)\mathbf{w}_1=(1,0), w2=(0,1)\mathbf{w}_2=(0,1), w3=(−1,−1)\mathbf{w}_3=(-1,-1) and zero biases. Which class is predicted at (1,2)(1,2), and what is the boundary between classes 11 and 22?
    Show answerThe logits are (1,2,−3)(1,2,-3), so class 22 is predicted. The boundary between classes 11 and 22 is z1=z2z_1=z_2, that is x1=x2x_1=x_2, a straight line.
  5. Compute the softmax of (2,1,0)(2,1,0) at T=0.5T=0.5 and show that it equals the softmax of (4,2,0)(4,2,0).
    Show answerDividing by 0.50.5 doubles the logits to (4,2,0)(4,2,0). The exponentials are 54.60, 7.389, 154.60,\ 7.389,\ 1 with sum 62.9962.99, so p=(0.867,0.117,0.016)\mathbf{p}=(0.867,0.117,0.016).
  6. A classifier takes d=784d=784 features and has K=10K=10 classes. How many numbers does the model have, and how many of them matter after removing the shift freedom?
    Show answerK(d+1)=10×785=7850K(d+1)=10\times785=7850 numbers, and (K−1)(d+1)=9×785=7065(K-1)(d+1)=9\times785=7065 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 p−y\mathbf{p}-\mathbf{y} 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.

Key takeaways

  • Softmax regression gives each of the K classes its own weight vector and bias: the logits are z = Wx + b, with W of shape (K, d). Softmax exponentiates every logit and divides by the sum of the exponentials, so the probabilities are positive, add to 1 and keep the order of the logits.
  • Only the differences between logits matter: adding the same number to every logit changes nothing, and the difference of two logits is the log of the ratio of their probabilities. So K weight vectors are one too many: fixing one class as the reference (its weights set to zero) loses nothing, and with K = 2 the model is logistic regression with weight w₁ − w₂.
  • The prediction is the class with the largest logit. The boundary between two classes is where their logits tie, which is a linear equation in x: a straight line in 2-D. The decision regions are convex pieces cut by straight lines.
  • The loss for the true class is the negative log of its probability, which equals LSE(z) minus the true class's logit, computed from the logits. For z = (1, 2, 3) and the third class true it is 0.4076; for z = (1000, 0, 0) it is 0 or 1000, never NaN.
  • The gradient of the loss with respect to the logits is p − y (y is the one-hot label). With respect to the weights it is (p − y)xᵀ, and averaged over a data set (1/N)(P − Y)ᵀX. Gradient descent with these formulas trained the 24-point toy model from loss 1.0986 (= ln 3) to 0.2751 in 200 steps.
  • Dividing the logits by a temperature T before the softmax keeps the order but changes the confidence. One-vs-rest builds K separate binary models whose scores need not add to 1; softmax regression is one model with a single coupled loss.
Found a mistake? Tell us