Overview
A classifier produces one score per class. Softmax converts those scores into a probability for each class. It exponentiates every score, which makes them all positive and widens the gaps between them, and then divides by the total so the results sum to 1. Only differences between scores matter: adding the same number to every score changes nothing. The temperature divides the scores first. A high temperature evens the probabilities out and a low one concentrates them on the top score.
A short history
The formula is the Boltzmann distribution of statistical physics from the 1860s, and it appeared in choice theory through R. Duncan Luce's 1959 work. Statisticians used it in multinomial logistic regression. John Bridle gave it the name softmax around 1989 when he proposed it as the output layer of neural network classifiers, so that outputs could be read as probabilities and trained by maximum likelihood.
How it works
- Take a vector of scores along the chosen
axisand divide each by the temperature . - Subtract the largest score from all of them. The result is unchanged, and the largest exponent becomes , so nothing overflows.
- Exponentiate each shifted score.
- Divide each by the sum of all of them. The outputs are positive and sum to 1.
- In
backward, combine the upstream gradient with the outputs as , which avoids building the full Jacobian.
Watch out for
- Exponentiating raw scores overflows for values in the hundreds. Always shift by the maximum first, as the template does.
- The outputs depend on each other. Raising one score lowers every other probability, so the derivative is a full matrix, not one number per element.
- Taking the log of softmax outputs loses precision when a probability rounds to zero. Losses should use log-softmax on the scores directly.
- A high probability is not a calibrated confidence. Softmax will assign nearly all the mass to some class even for inputs unlike anything seen in training.
- Applying it along the wrong
axisnormalises across the batch instead of across classes, and nothing raises an error.
Use cases
When to use it
The last step of a multi-class classifier, attention weights in transformers, and anywhere a set of scores must become a distribution over exclusive choices.
In industry
- Language models
- A language model applies softmax over its whole vocabulary at each step to get a probability for every possible next token.
- Image classification
- Classifiers that sort a photo into one of many categories end in a softmax, and the largest probability gives the predicted label.
- Attention in transformers
- Attention layers apply softmax to similarity scores so that the weights each position places on the others are positive and sum to 1.
Choosing it: what must hold
- Classes that are mutually exclusive: exactly one is correct for each example.
- A loss that works from the raw scores, such as cross-entropy, for numerical stability.
- A number of classes small enough to score all of them on every training step.
When to choose something else
| If | Use instead |
|---|---|
| Several labels can be true at once | Sigmoid on each output with binary cross-entropy |
| There are millions of classes or items | Sampled softmax |
| You only need the top class at inference, not probabilities | Take the largest raw score and skip the softmax |
Math foundations
The function
Each score is exponentiated and divided by the total. Every is positive and they sum to 1.
Only differences matter
A constant added to every score cancels between numerator and denominator. Choosing gives the stable form the template computes.
The Jacobian
Raising score raises its own probability (the case ) and lowers every other one. In matrix form it is , which
jacobianreturns.Backpropagation without the matrix
Multiplying the transposed Jacobian by the upstream gradient simplifies to this. It costs operations instead of . The entries always sum to zero.
With cross-entropy the gradient collapses
For the loss with true class , the gradient on the scores is predicted minus target. This is why softmax and cross-entropy are implemented as one unit.
Symbols
- the score (logit) for class i
- the output probability for class i
- the number of classes along the axis
- the temperature,
temperaturein the config, default 1 - 1 when i equals j, otherwise 0
- the vector of ones; with a bracket, the indicator that is 1 when the condition holds
- the gradient of the loss with respect to the outputs,
grad_output - the dot product of g and s
- the loss being minimised
- the index of the true class
Worked by hand
Compute the softmax of the scores with . Use and .
The probabilities are 0.6652, 0.2447 and 0.0900, which sum to 1 up to rounding. Each one-point gap in score is a factor of in probability.
Visual example
Loading the example.
Try this
- Raise one score: the others lose share even though they did not change.
- Lower the temperature and the largest score takes almost everything.
Code sample
import numpy as np
from impl import Softmax
from config import SoftmaxConfig
act = Softmax(SoftmaxConfig(axis=-1, temperature=1.0))
logits = np.array([[2.0, 1.0, 0.1]])
p = act.forward(logits) # [[0.659, 0.2424, 0.0986]], each row sums to 1
dx = act.backward(logits, np.array([[1.0, 0.0, 0.0]])) # gradient of p[0, 0] with respect to the logitsRead the implementation (47 lines)
"""Softmax: f(x)_i = exp(x_i / T) / sum_j exp(x_j / T) along one axis.
NumPy only. `forward` computes the probabilities, `backward` the gradient with respect to the input given the
gradient with respect to the output, and `jacobian` the full matrix of partial derivatives for one vector.
"""
from __future__ import annotations
import numpy as np
try:
from .config import SoftmaxConfig
except ImportError: # run from the template's own folder
from config import SoftmaxConfig
class Softmax:
"""Maps scores to probabilities that are positive and sum to 1 along `axis`."""
def __init__(self, config: SoftmaxConfig | None = None) -> None:
self.config = config or SoftmaxConfig()
def forward(self, x: np.ndarray) -> np.ndarray:
"""Softmax of x along the configured axis. x: any shape with at least one axis. Returns the same shape."""
x = np.asarray(x, dtype=float) / self.config.temperature
shifted = x - x.max(axis=self.config.axis, keepdims=True) # the largest exponent is exp(0) = 1
e = np.exp(shifted)
return e / e.sum(axis=self.config.axis, keepdims=True)
def backward(self, x: np.ndarray, grad_output: np.ndarray) -> np.ndarray:
"""Gradient of a scalar loss with respect to x, given `grad_output` = d loss / d softmax(x).
x, grad_output: same shape. Returns that shape. Uses J^T g = s * (g - sum(g * s)) / T, which avoids
building the Jacobian.
"""
s = self.forward(x)
g = np.asarray(grad_output, dtype=float)
inner = (g * s).sum(axis=self.config.axis, keepdims=True)
return s * (g - inner) / self.config.temperature
def jacobian(self, x: np.ndarray) -> np.ndarray:
"""Matrix J[i, j] = d f_i / d x_j for one score vector. x: (n,). Returns (n, n)."""
x = np.asarray(x, dtype=float)
if x.ndim != 1:
raise ValueError(f"jacobian takes one vector of shape (n,), got shape {x.shape}")
s = Softmax(SoftmaxConfig(axis=-1, temperature=self.config.temperature)).forward(x)
return (np.diag(s) - np.outer(s, s)) / self.config.temperature
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-softmax
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build Softmax(SoftmaxConfig(axis=-1, temperature=1.0)) and run forward on the scores 2, 1, 0 and on 1002, 1001, 1000. Confirm both give the same output. Then check that backward with a random grad_output equals jacobian(x).T @ grad_output.
Check on learning
- Adding 1000 to every score leaves the output unchanged. What does that say about how many free numbers a softmax over classes really has?
A way to think about it
One direction in score space has no effect. Count the dimensions that remain, and relate that to probabilities having to sum to 1.
- With scores , predict what happens to the three probabilities at and at before computing them.
A way to think about it
Dividing by scales the gaps between scores. Large gaps push toward one-hot, small gaps toward uniform. Then verify with the template.
- The entries of the gradient with respect to the scores always sum to zero. Why must that be true?
A way to think about it
Use the shift invariance. If moving all scores together cannot change the loss, the directional derivative along the all-ones vector is zero.
- A model outputs 0.99 for one class on an image of random noise. Is the model 99 percent sure? What does softmax guarantee and what does it not?
A way to think about it
Softmax guarantees the outputs sum to 1, nothing more. It has no way to say none of the above, and a large score gap can arise far from the training data.
- Why does subtracting the maximum before exponentiating fix overflow but not change the answer?
A way to think about it
After the shift the largest exponent is exactly 0 and the rest are negative. Underflow to zero in a small term is harmless, overflow to infinity is not.