Sub topic 4
Multiclass outputs with softmax and cross-entropy
This chapter covers the output layer and loss function for a multiclass problem, where each example belongs to exactly one of K classes. It assumes you know binary logistic regression and the sigmoid function, and that you can read basic NumPy and scikit-learn code. It also assumes you have seen one-hot encoding and class indices from the previous chapter.
The working model
A multiclass model produces K raw scores per example, called logits. A logit is an unbounded real number, and a higher value means the model favors that class more. Softmax turns the vector of logits into a probability distribution. Cross-entropy then measures how much probability that distribution gave to the true class.
Softmax
For logits z with K entries, softmax gives class k the probability
pk = exp(zk) / sum over j of exp(z_j)
Three properties matter in practice:
- Every pk is positive, and the pk sum to 1. Classes compete: raising one probability lowers the others.
- Softmax is monotonic. The largest logit always gets the largest probability, so argmax over logits equals argmax over probabilities.
- Softmax ignores a constant shift. Adding the same number c to every logit leaves the output unchanged, because exp(c) cancels in the ratio.
The shift property is what makes a numerically safe implementation possible. Subtract the row maximum before exponentiating, so the largest exponent is exp(0) = 1 and nothing overflows.
import numpy as np
from sklearn.metrics import log_loss
def softmax(z):
z = z - z.max(axis=1, keepdims=True) # stability shift, does not change the result
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
logits = np.array([
[2.0, 1.0, -1.0],
[0.5, 2.5, 0.0],
[1000.0, 1001.0, 999.0], # a naive exp() would overflow here
])
y = np.array([0, 1, 1]) # class indices
p = softmax(logits)
print(p.round(3))
print("row sums:", p.sum(axis=1))
# Cross-entropy: average of -log(probability of the true class)
loss = -np.log(p[np.arange(len(y)), y]).mean()
print("cross-entropy:", round(loss, 3))
print("sklearn log_loss:", round(log_loss(y, p, labels=[0, 1, 2]), 3))Both loss values should be about 0.318. The third row would produce inf and nan values without the shift.
Categorical cross-entropy
If the target is one-hot vector t and the prediction is p, the loss for one example is
L = - sum over k of tk * log(pk)
Because t has a single 1, the sum collapses to -log(p_y), where y is the true class. The loss is near 0 when the model gives the true class a probability near 1. It grows without bound as that probability approaches 0. A confident wrong prediction is therefore punished much harder than an uncertain one.
| Target format | Name used by many libraries | What it computes |
|---|---|---|
| One-hot matrix, shape (n, K) | Categorical cross-entropy | -sum(t * log p) per row |
| Integer indices, shape (n,) | Sparse categorical cross-entropy, or `CrossEntropyLoss` in PyTorch | -log p[y] per row |
Both give the same number for the same data. Only the target encoding differs.
Why the gradient is simple
With softmax and cross-entropy combined, the gradient of the loss with respect to the logits is p - t. For each class, it is the predicted probability minus the target. The true class gets a negative gradient, which pushes its logit up. All other classes get a positive gradient, which pushes their logits down, in proportion to how much probability they took. This simple form is the reason the two are almost always used together.
import numpy as np
def softmax(z):
z = z - z.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
z = np.array([[2.0, 1.0, -1.0]])
y = 0
def loss(z):
return -np.log(softmax(z)[0, y])
# Analytic gradient: p - one_hot(y)
analytic = softmax(z).copy()
analytic[0, y] -= 1.0
# Numeric gradient by central differences
eps = 1e-6
numeric = np.zeros_like(z)
for j in range(z.shape[1]):
zp, zm = z.copy(), z.copy()
zp[0, j] += eps
zm[0, j] -= eps
numeric[0, j] = (loss(zp) - loss(zm)) / (2 * eps)
print("analytic:", analytic.round(4))
print("numeric: ", numeric.round(4))The two rows match to four decimals.
Softmax in scikit-learn
LogisticRegression with the default lbfgs solver fits a multinomial model. That means it has one weight vector per class and optimizes the softmax cross-entropy directly. You can confirm that predict_proba is softmax applied to decision_function.
import numpy as np
from scipy.special import softmax
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(max_iter=1000).fit(X, y)
scores = clf.decision_function(X) # logits, shape (150, 3)
proba = clf.predict_proba(X)
print(np.allclose(softmax(scores, axis=1), proba)) # True
print("training log loss:", round(log_loss(y, proba), 3))Log loss is the multiclass cross-entropy averaged over examples. Lower is better, and it scores the probabilities rather than just the final labels.
Temperature and confidence
Dividing logits by a temperature T before softmax changes how sharp the distribution is. With T above 1, probabilities flatten toward uniform. With T below 1, they sharpen toward one-hot. The argmax never changes. This matters because trained models are often overconfident, and fitting a single T on validation data is a common calibration method. Calibration gets its own chapter later in this tutorial.
Common errors
- Applying softmax twice. PyTorch's
nn.CrossEntropyLossexpects raw logits and applies log-softmax internally. Feeding it probabilities gives a loss that trains poorly but raises no error. Check what your library's loss expects. - Computing
log(softmax(z))by hand. A probability can underflow to 0, and the log then becomes-inf. Use a fused function such aslog_softmaxor the library's loss. - Wrong target shape. Sparse losses need class indices from 0 to K-1. One-hot losses need an (n, K) matrix. Mixing them up produces shape errors or, worse, silently wrong values.
- Missing classes in
log_loss. If a class is absent from a validation fold,log_losscannot infer the label set. Passlabels=explicitly, as in the first example. - Using softmax for multilabel data. Softmax forces probabilities to sum to 1, so it cannot say that two labels are both present. Multilabel outputs use independent sigmoids, which the next chapter covers.
- Reading probabilities as certainty. A softmax output of 0.99 means the model's scores strongly favor one class. It does not mean the model is right 99% of the time.
Edge cases
- Two classes. Softmax with two logits is equivalent to a sigmoid on the difference of the logits. Binary logistic regression is the K = 2 special case.
- Redundant parameters. Because of the shift invariance, a multinomial model has one redundant degree of freedom. Regularization (L2 in scikit-learn by default) pins down a unique solution.
- Label smoothing. Replacing the one-hot target with, say, 0.9 on the true class and the remaining 0.1 spread over the others stops logits from growing without bound. It often improves calibration.
- Class imbalance. Plain cross-entropy weights every example equally, so rare classes contribute little. Class weights multiply each example's loss by a factor tied to its class. A later chapter covers this.
Exercise
A model outputs logits [3.0, 3.0, 0.0] for one example whose true class is 2. Without running code, what are the approximate softmax probabilities, and what is the cross-entropy loss? Use exp(3) ≈ 20.09.
Show answer
The exponentials are 20.09, 20.09 and 1, which sum to 41.18. The probabilities are about [0.488, 0.488, 0.024]. The loss is -ln(0.024) ≈ 3.7. The loss is high because the model put almost no probability on the true class.
Exercise
You add 100 to every logit of an example before applying softmax and cross-entropy. What happens to the probabilities, the loss, and the gradient with respect to the logits, and why?
Show answer
All three stay the same. Softmax is invariant to a constant shift because exp(100) cancels from the numerator and denominator. The loss depends only on the probabilities, and the gradient p - t depends only on the probabilities and the target. This invariance is why implementations subtract the maximum logit for numerical stability.