← All notes
Course chapters
On this page

Lesson 11 · Neural networks

Softmax

How do arbitrary class scores become probabilities? Derive Softmax, explore temperature and keep the calculation numerically stable.

1. What does a classifier's last layer output?

Return to our fruit-guessing machine. This time, start with three possible classes: apple, banana and watermelon. After the hidden layers, the final affine layer produces one score per class. Suppose the scores are:

z=[2.1,  −0.5,  1.8].\mathbf z=[2.1,\;-0.5,\;1.8].

These raw scores are called logits. Apple has the highest score, followed by watermelon and banana. But the scores are not probabilities:

  • 2.12.1 is greater than one, and −0.5-0.5 is negative.
  • Their sum is 3.43.4, rather than one.
  • A logit alone does not tell us the probability assigned to a class.

For mutually exclusive classes, we want a distribution: nonnegative values that add up to one. Lesson 10's cross-entropy compares that distribution with the true label. Practical loss implementations may accept logits directly and perform the conversion internally, but the mathematical probability interpretation is the same.

Pause and think

Why not divide each score by the sum of the scores? Would that always produce valid probabilities?

I've thought about it — show the answerHide answer

Not with arbitrary real scores. In this example, the sum is 3.43.4, so the banana entry becomes −0.5/3.4-0.5/3.4, which is negative. Other inputs can have a zero sum, making division undefined, or produce values outside the interval from zero to one.

Normalising by a sum works for nonnegative weights with a positive total. Raw logits do not satisfy that requirement.

2. Repair the negative values: shift, then normalise?

One idea is to add 0.50.5 to every score so the minimum becomes zero:

[2.1,−0.5,1.8]+0.5=[2.6,0,2.3].[2.1,-0.5,1.8]+0.5=[2.6,0,2.3].

Divide by the new sum, 4.94.9:

[2.64.9,04.9,2.34.9]≈[0.531,0,0.469].\left[\frac{2.6}{4.9},\frac{0}{4.9},\frac{2.3}{4.9}\right] \approx[0.531,0,0.469].

But why shift the minimum to zero? Adding 1.51.5 instead makes the minimum one:

[3.6,1,3.3],[3.67.9,17.9,3.37.9]≈[0.456,0.127,0.418].[3.6,1,3.3],\qquad \left[\frac{3.6}{7.9},\frac{1}{7.9},\frac{3.3}{7.9}\right] \approx[0.456,0.127,0.418].

The choice of offset changes the probabilities. A rule that always subtracts the minimum would also fail when all scores are equal: every shifted score would be zero.

We want a transformation that makes scores positive and gives the same distribution when a common constant is added to every logit. It should depend on relative score differences rather than the arbitrary choice of zero.

This is stronger than preserving the ranking alone. A small gap and a large gap can share the same ranking but should not necessarily produce the same distribution.

3. Exponentiate, then normalise: Softmax

The exponential function maps every finite real number to a positive value:

ex>0.e^x>0.

It is increasing, so it preserves the order of scores. Negative scores become small positive weights rather than negative probabilities.

-3-2-101212468
y=ex>0y=e^x>0
x
Figure 11-1. Exponentiation makes negative scores positive while preserving their ordering. The curve approaches zero towards the left, but never reaches it for a finite real input in exact arithmetic.

Exponentiate our three logits:

e2.1≈8.166,e−0.5≈0.607,e1.8≈6.050.e^{2.1}\approx8.166,\qquad e^{-0.5}\approx0.607,\qquad e^{1.8}\approx6.050.

Their total is approximately 14.82214.822. Divide each exponential by that total. This is Softmax:

pi=softmax⁡(z)i=ezi∑j=1Kezj.p_i=\operatorname{softmax}(\mathbf z)_i =\frac{e^{z_i}}{\sum_{j=1}^{K}e^{z_j}}.
ClassLogitezie^{z_i}Probability
Apple2.18.1660.551
Banana-0.50.6070.041
Watermelon1.86.0500.408
Sum3.414.8221.000
Figure 11-2. From raw scores to exponentials to normalised probabilities. Calculations use full precision; displayed values are rounded.

In exact arithmetic, each probability is positive and the sum is one. With finite precision, very small probabilities may underflow to zero, and rounding can make displayed percentages sum to slightly more or less than 100%.

Why a common shift cancels

Add the same constant cc to every logit:

ezi+c∑jezj+c=eceziec∑jezj=ezi∑jezj.\frac{e^{z_i+c}}{\sum_j e^{z_j+c}} =\frac{e^c e^{z_i}}{e^c\sum_j e^{z_j}} =\frac{e^{z_i}}{\sum_j e^{z_j}}.

The factor cancels. Softmax therefore ignores a common offset, unlike the shift-and-divide approach above.

The ratio of two class probabilities depends on their score difference:

pipj=ezi−zj.\frac{p_i}{p_j}=e^{z_i-z_j}.

Apple's score exceeds watermelon's by 0.30.3, so its probability is about e0.3≈1.35e^{0.3}\approx1.35 times as large. Comparing percentage differences between raw logits would be misleading: shifting every logit changes those percentages while leaving Softmax unchanged.

Watch the four-fruit classifier

Now return to the four classes from Lesson 7. Adjust the features to change the class scores, and watch Softmax convert them into probabilities.

SmallLarge
Less redMore red
SourSweet
DryJuicy
pi=ezi∑jezj,∑ipi=1p_i=\frac{e^{z_i}}{\sum_j e^{z_j}},\qquad\sum_i p_i=1

Most likely fruit: Apple

AppleScore: 2.44 · 35.8%
BananaScore: 2.18 · 27.4%
WatermelonScore: 1.39 · 12.5%
LemonScore: 2.05 · 24.3%

Unrounded probabilities sum to one; displayed percentages may differ slightly due to rounding.

Experiment 11-A. Four scoring units, one probability distribution. Increase size and water content to favour watermelon. The classifier uses illustrative, fixed parameters; changing features changes predictions without training the model.

At a fixed temperature, the highest logit also has the highest probability. Softmax provides a distribution rather than only selecting the largest score. These are model-assigned probabilities, not a guarantee that the model's confidence accurately matches real-world frequencies.

For mutually exclusive classes, the classes compete for a total probability of one. When several labels can independently be true, a separate Sigmoid per label is often a more appropriate output setup.

4. Temperature controls the sharpness

Divide the logits by a positive temperature TT before applying Softmax:

pi(T)=ezi/T∑jezj/T,T>0.p_i(T)=\frac{e^{z_i/T}}{\sum_j e^{z_j/T}},\qquad T>0.

The ratio now becomes:

pi(T)pj(T)=e(zi−zj)/T.\frac{p_i(T)}{p_j(T)}=e^{(z_i-z_j)/T}.
  • Lower temperature makes score gaps larger after scaling, sharpening the distribution.
  • Higher temperature makes those gaps smaller, flattening the distribution.
  • At T=1T=1, we recover ordinary Softmax.

Temperature 0.5

Apple64.3%
Banana0.4%
Watermelon35.3%

Temperature 1

Apple55.1%
Banana4.1%
Watermelon40.8%

Temperature 2

Apple46.9%
Banana12.8%
Watermelon40.3%
Figure 11-3. The same scores at three temperatures. Lower temperature sharpens the distribution; higher temperature flattens it. Temperature does not change which class has the largest score.

For these particular logits, T=0.5T=0.5 gives apple roughly 64%, not nearly 100%. How sharp the result becomes depends on both the temperature and the original score gaps.

pi(T)=ezi/T∑jezj/T,T>0p_i(T)=\frac{e^{z_i/T}}{\sum_j e^{z_j/T}},\qquad T>0
Apple55.1%
Banana4.1%
Watermelon40.8%

Probability sum: 1.000000

Experiment 11-B. Adjust scores and temperature independently. Try giving all three classes the same score: the distribution stays uniform at every positive temperature.

For fixed logits, positive temperature preserves the ranking. If we always choose the largest probability, temperature alone does not change that choice. If we sample from the distribution, changing temperature changes how often lower-scoring alternatives are selected.

As TT grows without bound, the distribution approaches uniform. As TT approaches zero from above, probability concentrates on the largest logit. If several logits tie for the maximum, they share that limiting probability. Equal logits always produce a uniform distribution.

Language models use this idea when sampling the next token: a sharper distribution tends to repeat high-scoring choices, while a flatter one admits more alternatives. Temperature changes the sampling distribution; it does not by itself guarantee correctness, creativity or a particular writing style. A zero-temperature setting is commonly treated as a special decoding choice, since the formula above divides by TT and requires T>0T>0.

Keep the calculation numerically stable

A score of 1,000 causes trouble if we directly calculate e1000e^{1000} in standard floating-point arithmetic. Use the common-shift property to subtract the largest score first:

m=max⁡jzj,pi(T)=e(zi−m)/T∑je(zj−m)/T.m=\max_j z_j,\qquad p_i(T)=\frac{e^{(z_i-m)/T}}{\sum_j e^{(z_j-m)/T}}.

For positive TT, every exponent is nonpositive and at least one is zero. The largest exponential is one, so the calculation avoids exponential overflow. For example, logits [1000,999,998][1000,999,998] become shifted scores [0,−1,−2][0,-1,-2] without changing the distribution.

The same idea appears in the stable log-sum-exp expression:

ln⁡∑jezj=m+ln⁡∑jezj−m.\ln\sum_j e^{z_j} =m+\ln\sum_j e^{z_j-m}.

For a correct class cc at ordinary temperature, cross-entropy can be computed directly from logits as:

L=−zc+ln⁡∑jezj.L=-z_c+\ln\sum_j e^{z_j}.

This avoids taking the logarithm of a tiny, rounded probability. The existing shared Softmax helper used by these experiments already subtracts the maximum score before exponentiating.

5. What you have discovered

Softmax connects class scores to a probability distribution.

  • Logits are arbitrary real scores, not probabilities.
  • Exponentiation makes finite scores positive; normalising the resulting weights makes their sum one.
  • A common offset cancels. Relative score differences determine probability ratios.
  • Temperature changes sharpness while preserving the ranking of fixed logits.
  • Sampling and selecting the maximum are different decisions; temperature affects them differently.
  • Subtracting the maximum avoids exponential overflow and supports stable cross-entropy calculations.

We now have predictions, probabilities and a loss. The next lesson asks how an optimiser uses gradients to update the parameters, and how large each step should be.

Check your understanding

1. Which two steps turn logits into a probability distribution with Softmax?
2. What does a positive temperature T do when Softmax is applied to z/T?