TL;DR
A classifier outputs a probability for each possible class. Cross-entropy loss looks only at the probability given to the true class, takes its negative logarithm, and returns that as the loss. The loss is near zero when the model is confident and right, and it grows without limit as the probability on the right answer approaches zero.
Minimising this loss is the same as making the model's predicted distribution agree with the true labels, so it is the standard loss for classification.
Where you'll see it: in the final layer of image classifiers and language models, where it is applied to the output of a softmax on every token.
Intuition
Rewarding the right answer in proportion to belief
Imagine a weather forecaster who says "70% chance of rain" and it rains. That forecast was good, but not perfect. If they had said 99% and it rained, they would be better still. If they had said 1% and it rained, they were badly wrong. A scoring rule should reward high probability on what actually happened, and punish it hard when the probability on what happened is tiny.
The negative logarithm does exactly this. Probability 1 gives loss 0. Probability 0.5 gives a moderate loss. Probability 0.01 gives a large loss. The loss keeps rising as the probability falls, which means the model is pushed hardest on the examples it most confidently gets wrong.
The plot shows the loss on the true class as a function of the probability the model assigned to it.
- cross-entropy loss -ln(p)
Why a logarithm and not just "1 minus probability"
A simpler score, such as one minus the probability of the true class, is bounded: it can never be worse than 1. Paired with a softmax, its gradient also shrinks toward zero when the model is confidently wrong, so learning stalls exactly where it is needed. The logarithm keeps the penalty growing and the gradient strong. It also turns products of independent probabilities into sums, which is why it appears whenever many predictions are combined.
The math
Definition
For a classifier with classes that outputs probabilities summing to 1, and a true class , the cross-entropy loss is
When the true label is written as a one-hot vector , with for the true class and otherwise, the same loss is .
Here is the number of classes and is the probability the model gives to class . The natural logarithm is used throughout, and the result is measured in nats. Using instead gives bits, which only rescales the loss.
The two forms agree: every term in the sum is zero except the one for the true class, where . The one-hot form is the one that generalises to soft labels, where the target is a distribution rather than a single class.
Cross-entropy as a comparison of distributions
Let be the true distribution (one-hot, or soft) and the model's distribution. The cross-entropy between them is
It is the average surprise of the true labels when the model's probabilities are used to measure surprise. It equals the entropy of the true distribution plus the KL divergence from the true distribution to the model:
For one-hot labels the entropy is zero, so the cross-entropy and the KL divergence are the same thing. Minimising the loss therefore pushes the model's distribution toward the true one. The entropy term does not depend on the model, so it does not change the gradient.
Softmax and the gradient
Classifiers usually produce raw scores , called logits. The Softmax turns them into probabilities:
Substituting this into the loss and differentiating with respect to the logits gives a very simple result. For a one-hot label,
Each logit moves by the gap between predicted and true probability. This is one reason cross-entropy with softmax trains well: the gradient does not vanish when the model is confidently wrong, unlike squared error on probabilities.
Connection to maximum likelihood
If each label is treated as a draw from the model's predicted distribution, the likelihood of a whole dataset is the product of the probabilities of the true classes. Taking the negative logarithm turns that product into the sum of losses, so minimising the average cross-entropy is exactly maximum likelihood for a categorical model. Logistic regression is the two-class case of the same idea.
Worked examples
A model labels a photo as one of three classes: cat, dog, bird. The true class is dog. The model outputs probabilities .
- Probability on the true class (dog): .
- Loss: .
- Now suppose the model is less sure: . Loss: .
- Now suppose it is confidently wrong: . Loss: .
Interpretation: the loss depends only on the probability of the true class. The confidently wrong prediction costs about eight times as much as the one that was right with 70%. The model is pushed hardest toward the dog class when it had put its weight on cat.
Logits for classes cat, dog, bird. The true class is dog, so the one-hot label is .
- Exponentials: , , . Sum .
- Probabilities: .
- Gradient : .
- A gradient descent step subtracts the gradient from each logit. The dog gradient is negative, so the dog logit goes up. The cat and bird gradients are positive, so their logits go down.
Interpretation: the true class's logit is pushed up and every wrong class is pushed down, each in proportion to how much probability it currently holds. Once the dog probability is near 1, the gradient is near zero and training naturally slows.
A language model predicts the next word after "the cat sat on the". Suppose it gives "mat" probability 0.25.
- Loss for this one prediction: .
- Averaged over a corpus, suppose the mean loss is 1.4 nats per token. The geometric-mean probability on the true next token is then .
- Perplexity, defined as raised to the mean cross-entropy, is .
Interpretation: a perplexity of about 4 means the model is, on average, as uncertain as choosing uniformly among four words. Lower cross-entropy means lower perplexity, which is why language models report it.
Tradeoffs and failure modes
| Situation | What goes wrong | Better choice |
|---|---|---|
| Labels are noisy or wrong | On a mislabelled example the loss pushes the model hard toward the wrong label, and the model learns the noise | Label smoothing, or a loss that caps the penalty |
| Classes are very imbalanced | Most examples come from one class, so the average is dominated by it | Class weights, or focal loss |
| Probability is exactly 0 for the true class | is infinite and training produces NaN | Compute from logits with a stable log-softmax, or clip probabilities |
| Only the top prediction matters | Cross-entropy also rewards getting the full distribution right | Accuracy or top-k metrics for reporting, cross-entropy for training |
| Multiple correct labels per example | The one-hot form assumes exactly one correct class | Binary cross-entropy per label |
The most common practical failure is computing softmax and then the logarithm separately. Small probabilities underflow to zero and the loss becomes infinite. Frameworks provide a fused log-softmax on the logits for this reason. Also remember that a low training cross-entropy does not guarantee good held-out performance; check validation loss as well.
History
The quantity at the heart of cross-entropy predates machine learning. Claude Shannon defined entropy in 1948 as the average surprise of a source, and the cross-entropy between two distributions was the natural follow-up: the cost of coding one source using a code designed for another. Solomon Kullback and Richard Leibler introduced the divergence that separates the two terms in 1951.
In statistics, the same loss arrived as the negative log likelihood. Logistic regression, which models two classes with a sigmoid and fits by maximum likelihood, was developed through the middle of the twentieth century and is the two-class form of cross-entropy. Multi-class versions became standard with the softmax, and neural networks trained with it became standard as backpropagation (popularised in the 1980s) and, later, large datasets and GPUs made deep networks practical. Today it is the default loss for classification and for language modelling.
Check yourself
QuestionA model gives the true class probability 0.25. What is its cross-entropy loss?Show answer
The loss is . The negative logarithm of a probability between 0 and 1 is always non-negative, and a probability of 0.25 gives a moderate loss.
QuestionCompute the cross-entropy loss for a three-class model with probabilities when the true class is the third one.Show answer
The probability on the true class is 0.1, so the loss is . Only the probability on the true class enters the one-hot form, so the 0.6 on the wrong class does not appear in the number at all.
QuestionWhy does a classifier trained with cross-entropy and softmax not stall when it is confidently wrong, while squared error on probabilities can?Show answer
With softmax, the gradient with respect to each logit is . If the model is confidently wrong, the true class has a tiny probability, so its gradient is close to , which is large. Squared error on probabilities passes through the softmax derivative, which multiplies by the probabilities again and can make the gradient nearly zero when the model is confident.
QuestionA language model's mean cross-entropy on held-out text is 2.0 nats per token. What is its perplexity?Show answer
Perplexity is . This means the model is on average as uncertain as choosing uniformly among about seven options at each token.
QuestionYour dataset has 99% examples of one class. A model that always predicts that class gets a low average cross-entropy. What is the problem, and what would you change?Show answer
The average loss is dominated by the majority class, so a model can look good by ignoring the rare class, which may be the one you care about. Use class weights so that rare-class errors count more, or a focal loss that down-weights easy majority examples, and evaluate per-class recall as well as the loss.