Overview
A classifier produces one score per class. Cross-entropy turns the scores into probabilities with softmax and then looks at one number: the probability assigned to the right class. The loss is the negative log of that number. A probability of 1 costs nothing, a probability of one half costs about 0.69, and a probability near zero costs a great deal. Minimising it is the same as maximising the likelihood of the training labels. Its gradient on the scores is simply the predicted probabilities minus the true one-hot vector.
A short history
Cross-entropy was defined in Claude Shannon's 1948 information theory. Minimising it against one-hot labels is the same as maximum likelihood for a categorical model, the method behind multinomial logistic regression. Neural networks adopted it for classification once softmax outputs came into use, because unlike squared error its gradient does not vanish when the model is confidently wrong.
How it works
- Take the logits, shape (N, C), and the target class index for each row.
- Compute the log-softmax of each row, which is the log-probability of every class, in a way that cannot overflow.
- Pick out the log-probability of the target class and negate it. That is the loss for the row.
- Skip rows whose target equals
ignore_index: they get zero loss and zero gradient. - Reduce with
reduction. The mean divides by the number of rows that were not ignored. - In
backward, each counted row's gradient is its softmax probabilities with 1 subtracted at the target class.
Watch out for
- The loss expects raw logits. Passing probabilities or log-probabilities applies softmax twice and trains a blurred, underconfident model without any error.
- A single confidently wrong prediction can dominate the batch, because the loss is unbounded as the true-class probability approaches zero. Mislabelled data causes exactly this.
- With imbalanced classes the frequent classes dominate the mean. The template has no class weights, so rebalance the data or use focal loss.
- The loss can only reach zero with infinite logits. A model trained to very low loss becomes overconfident, which label smoothing is designed to limit.
Use cases
When to use it
Any classification task with exactly one correct class per example: image classes, next-token prediction, intent detection. Use ignore_index to mask padding in sequences.
In industry
- Language models
- Large language models are trained with cross-entropy between the predicted distribution over the vocabulary and the token that actually came next.
- Image classification
- Classifiers trained on labelled photo collections such as ImageNet minimise cross-entropy over the set of categories.
- Customer support
- Intent classifiers that route a message to one of a fixed set of queues are trained with cross-entropy on labelled past messages.
Choosing it: what must hold
- Exactly one correct class per example, from a fixed set of classes.
- A model that outputs one raw score per class, with the softmax applied inside the loss.
- Labels that are mostly correct, since the loss punishes confident disagreement with the label heavily.
When to choose something else
| If | Use instead |
|---|---|
| Several labels can be true for one example | Binary cross-entropy on each label |
| The model becomes overconfident or the labels are noisy | Label-smoothed cross-entropy |
| A few classes are rare and the easy majority dominates training | Focal loss |
| There are millions of classes | Sampled softmax |
Math foundations
Probabilities from logits
Softmax turns the row of scores into a distribution over the classes.
The loss for one example
The negative log-probability of the true class . The second form, a log-sum-exp minus the true score, is what is computed so that no probability is ever rounded to zero.
Why it is called cross-entropy
The cross-entropy between a target distribution and the prediction . With a one-hot only the true class survives in the sum, which gives .
The mean over counted rows
is the set of rows whose target is not
ignore_index. Ignored rows do not dilute the average.Gradient with respect to the logits
Predicted minus target. The true class is pushed up by and every other class is pushed down by its own probability. The entries sum to zero.
Symbols
- the logit (raw score) for class c
- the predicted probability of class c
- the index of the true class
- the number of classes
- the target probability of class c (1 for the true class, 0 otherwise)
- the loss for one example
- the reduced loss
- the set of rows not ignored
- 1 when c is the true class, otherwise 0
Worked by hand
One example with logits and true class 0. Softmax gives .
The loss is 0.4076 and the gradient entries sum to zero. Had the true class been the lowest scored one, the loss would be 2.4076, exactly 2 higher, the gap between the two logits.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import CrossEntropy
from config import CrossEntropyConfig
loss = CrossEntropy(CrossEntropyConfig())
logits = np.array([[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]]) # (N=2, C=3)
target = np.array([0, 1]) # correct class per row
print(loss.forward(logits, target)) # 0.3185
print(loss.backward(logits, target)) # (softmax - one_hot) / 2Read the implementation (67 lines)
"""Softmax cross-entropy for multi-class classification: loss = -log(softmax(logits)[target]).
NumPy only. `forward` returns the loss, `backward` its gradient with respect to the logits.
"""
from __future__ import annotations
import numpy as np
try:
from .config import CrossEntropyConfig
except ImportError: # run from the template's own folder
from config import CrossEntropyConfig
def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
"""log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
shifted = z - z.max(axis=axis, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))
def _check(logits, target) -> tuple[np.ndarray, np.ndarray]:
"""Logits as a float array (N, C) and class indices as an int array (N,). Raises ValueError otherwise."""
logits, target = np.asarray(logits, dtype=float), np.asarray(target)
if logits.ndim != 2 or target.shape != (logits.shape[0],):
raise ValueError(f"expected logits (N, C) and target (N,), got {logits.shape} and {target.shape}")
return logits, target.astype(int)
class CrossEntropy:
"""Negative log-probability of the correct class under softmax(logits)."""
def __init__(self, config: CrossEntropyConfig | None = None) -> None:
self.config = config or CrossEntropyConfig()
def _valid(self, logits: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Mask of the rows that count, and the targets with ignored rows pointed at class 0 so indexing works."""
valid = target != self.config.ignore_index
safe = np.where(valid, target, 0)
if safe.min(initial=0) < 0 or safe.max(initial=0) >= logits.shape[1]:
raise ValueError(f"target classes must lie in [0, {logits.shape[1]})")
return valid, safe
def forward(self, logits: np.ndarray, target: np.ndarray):
"""logits: (N, C) raw scores. target: (N,) class indices. Returns a float, or (N,) for "none"."""
logits, target = _check(logits, target)
valid, safe = self._valid(logits, target)
per_row = -_log_softmax(logits)[np.arange(len(safe)), safe] * valid
if self.config.reduction == "none":
return per_row
total = float(per_row.sum())
return total / max(int(valid.sum()), 1) if self.config.reduction == "mean" else total
def backward(self, logits: np.ndarray, target: np.ndarray) -> np.ndarray:
"""Gradient of the reduced loss with respect to the logits, shape (N, C).
Per row it is softmax(logits) - one_hot(target), zero for ignored rows, divided by the number of
counted rows for "mean". For "none" the per-row gradient is returned unscaled.
"""
logits, target = _check(logits, target)
valid, safe = self._valid(logits, target)
grad = np.exp(_log_softmax(logits))
grad[np.arange(len(safe)), safe] -= 1.0
grad *= valid[:, None]
if self.config.reduction == "mean":
grad /= max(int(valid.sum()), 1)
return grad
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build CrossEntropy(CrossEntropyConfig()) and call forward and backward on two rows of logits with targets 0 and 2. Then set the second target to -100 and confirm its gradient row is zero and the mean is taken over one row. Finally compare the loss of all-zero logits with .
Check on learning
- At the start of training a 1000-class model has a loss of about 6.9. Is that a good sign, a bad sign, or neither?
A way to think about it
Compute . A model that knows nothing and spreads probability evenly has exactly this loss, so it is a useful check that the initialisation is sane.
- The gradient on the logits is predicted minus target. What does that imply about examples the model already classifies with probability 0.999?
A way to think about it
Their gradient is close to zero. Training effort flows to the examples that are still wrong or uncertain. Consider what happens if some of those are mislabelled.
- Validation accuracy keeps rising while validation loss also rises. How can both be true?
A way to think about it
Accuracy looks only at the top class. The loss also measures confidence. A few wrong answers given with growing certainty can outweigh many small gains.
- Why is padding handled with
ignore_indexinstead of giving padded positions a real class?A way to think about it
Count how many positions in a padded batch are padding. If they contributed, the model would be rewarded for predicting something trivial and the mean would be diluted.
- Adding the same constant to every logit of a row leaves the loss unchanged. What does that mean for the gradient?
A way to think about it
If moving along the all-ones direction changes nothing, the gradient has no component along it. Check this against the formula.