A photo shows a cat. Your model says cat, dog, fox. How wrong is that? Another model says cat. How much worse is it? To train a model you need one number that answers these questions, and it must be lower exactly when the probabilities are better. That number is the cross-entropy.
P1.E1 gave every outcome a surprise, . P1.E2 averaged the surprise over a source and called it entropy. This lesson changes one thing: the outcomes still come from the real world, but the surprise is measured with the probabilities of a model. That single change gives the loss used to train classifiers and language models.
Two distributions, one average
Call the real distribution of outcomes and the model’s probabilities . In a classification problem is the label and is the model’s output. Entropy averages the surprise using the same twice: it decides how often happens and how surprising is. Cross-entropy separates the two jobs. Outcomes happen with the probabilities , but the surprise is measured with :
The notation means that is drawn from . Put and the formula becomes the entropy of P1.E2, so entropy is the cross-entropy of a distribution with itself.
The convention of P1.E2 carries over. A class with never happens, so it adds to the sum, even if is also .
An example with three classes. Let the true probabilities be , the distribution used in P1.D3 and P1.E2. A model predicts . Its surprises are , and bits. Weight each by how often the class really happens:
In nats this is . For comparison, three other models of the same source:
- The perfect model gives the entropy, bits (P1.E2).
- The model above gives bits, which is more.
- A uniform guess gives bits, which is more than the entropy.
Better probabilities, lower cross-entropy. The next sections say exactly why.
Cross-entropy as a code length
P1.E2 showed that entropy is the shortest average length of a lossless code. Cross-entropy answers: what if the code is built for the wrong distribution?
A code built for gives a class with model probability a code word of about bits, short for classes the model expects and long for classes it finds unlikely. For the model above the lengths are , and bits, which is the code of P1.E2. Now send data that really come from . The average length is bits per symbol: exactly the cross-entropy. With ideal code lengths of bits (they need not be whole numbers), a code built for the true would average bits, the entropy. Here a real code with whole-number lengths cannot do better than for either, so the -bit gap is the idealized price; a real code built for stays within bit of the entropy (P1.E2). Either way, the cross-entropy is the cost of believing when the truth is , in bits per symbol.
Here the model’s probabilities are powers of , so the lengths are whole numbers. In general is not a whole number, a real code rounds up, and the cross-entropy is the length in the idealized, fractional sense. The meaning is the same: a model that predicts well is a model that compresses well, which is why language modelling and compression are so close.
Play with it
Choose a true distribution (pink bars) and a model (blue bars) and watch the loss. Drag the blue bars, or switch to logits and let a softmax make . The row under the charts shows each class’s share of the cross-entropy, and the orange row shows the gradient that the loss would send back to the logits.
What to try:
- The lesson example. Press “Lesson example”: , , extra , and swapped .
- Match. Press “Matches p”: the cross-entropy equals the entropy and the extra is . No other does better, and you can try: drag a bar away from and the loss only rises.
- One-hot. Choose “One-hot” for and press “Uniform guess” with : the loss is bits, the surprise of the true class A, which has . Now drag the A bar: the loss is always , so it is bit at and bits at . Only is in the loss. The other bars matter only because they share what A leaves.
- Confident and wrong. With “One-hot” chosen, press “Confident and wrong”: the true class gets and the loss is about bits ( nats). The gradient row shows a large push on the logit of the true class.
- A zero. Press “Zero on a true class”: the loss reads .
- Soft targets. Choose “Smoothed” and press “Matches p”: the loss is not , it is the entropy of the target. Then move any blue bar away from its pink bar: the loss rises.
- Swap. Press “Swap p and q” on the lesson example and compare with .
What cross-entropy cannot be
It is never below the entropy. For every and ,
with equality exactly when . This is Gibbs’ inequality. It says the best possible model of a source is the true distribution, and any other model costs more. A short proof is in the box below.
The extra is a named quantity. The gap between the cross-entropy and the entropy is the cost of using instead of :
The second term is the KL divergence, defined in full in P1.E4, where its properties are studied. For now it is just “the extra”: bits in our example, and always at least . This split explains how training works. The entropy belongs to the data, and no choice of model changes it. So the part training can reduce is the extra, and minimizing the cross-entropy over the model is the same as minimizing the KL divergence.
It is not symmetric. Swapping the roles changes the answer. With and :
In the outcomes are drawn from and surprise is measured with , a different question, so a different number. That is why cross-entropy is not a distance between and . In a loss the order is fixed: the label is the first argument and the model is the second, because the model’s probabilities are the ones inside the logarithm.
It can be infinite. If the model says for something that happens with , the surprise is and so is . Take and a model that rules out the third class: . In the other direction, bits is finite, because has no zeros. In , the order used in a loss, a zero in is harmless and a zero in is deadly. In exact arithmetic a softmax output is never , but it can be tiny, and in floating point a very tiny value can even underflow to exactly (which is why frameworks compute with log-probabilities). A tiny on the true class gives a huge loss, as the widget showed.
Go deeper Why the cross-entropy is never below the entropy
Use natural logs (the base does not matter for the inequality). Let be the set of classes with ; the sums below run over . Call the gap . Then
The inequality holds for every , with equality only at (the same fact as in the proof in P1.D10). Apply it with :
The last step holds because the over those classes add up to at most . Both steps are equalities only if for every . So with equality exactly when . If some with the gap is and the inequality holds anyway.
The classification loss
Now take to be a label. A one-hot label puts all of its probability on the true class : and every other . Every term of with vanishes, and what is left is
The cross-entropy loss of one example is the surprise of the true class (P1.E1). A one-hot label has entropy , so the extra equals the whole loss. In P1.D3 a classifier gave and the first class was true: the loss is nats, which is bits. Only the probability the model gave the true class is in the number. The other probabilities matter only because all of them must add up to : to raise the model must lower the rest.
With examples, the loss reported during training is the average,
where is the probability that example gave to its true class. This is exactly the average negative log-likelihood of P1.D10. So minimizing the cross-entropy loss is maximum likelihood for a categorical model, and the two names describe one computation.
Two classes: binary cross-entropy. With a label the true distribution is and the model’s is , where is the predicted probability that (a sigmoid output, P1.A5). The formula becomes
These are the numbers of P1.D3. A spam model says . If the email is spam () the truth had probability and the loss is . If it is not spam () the truth had probability and the loss is . For labels and predictions the truth gets , and , the losses are , and , and their average is nats.
From logits to the loss
A network does not output probabilities directly. It outputs a score per class, called a logit, and a softmax turns them into probabilities (P1.C7, P3.A8):
For the probabilities are . If the third class is true, the loss is nats, or bits.
The stable form. Taking the log of the softmax gives , so
The term is the log-sum-exp of the logits. Software computes the loss this way instead of forming and then taking its log, and it subtracts the largest logit inside the exponentials first (P1.G2). The reason is range. For the exponential overflows ordinary floating-point numbers, so the naive softmax returns nan. The log-sum-exp form gives a loss of if the first class is true and if the second class is true, with no overflow. The loss is also never computed as the log of an underflowed .
The gradient with respect to the logits is . For a one-hot target this is the probabilities minus the one-hot vector, the result of P1.C7 and P1.C11. For with the third class true:
Read it as a push on each logit. The true class has a negative entry, so gradient descent raises its logit. Every wrong class has a positive entry equal to its own probability, so it is lowered, the likelier ones more. The entries add to , and the whole vector is only when . The size of the push is simply how wrong the probabilities are. The orange row in the widget is this vector for any you choose (the derivation is in the box below).
Go deeper Where the gradient q minus p comes from
For any target whose entries add to , the loss from logits is
The first part used . The derivative of the first term with respect to is . The derivative of the log-sum-exp is (the chain rule on , P1.C3). So . Notice that the result holds for soft targets as well as one-hot ones, which is why label smoothing and distillation need no new gradient code.
Why this loss and not squared error
Squared error is a fine loss for predicting a number, and it is the negative log-likelihood of a Gaussian (P1.D10). For probabilities there are three reasons to prefer cross-entropy.
It is the likelihood of the right model. For a label that is one of classes the natural model is categorical, and its negative log-likelihood is the cross-entropy. Squared error corresponds to a Gaussian noise model, which does not fit a class label.
It rewards honest probabilities. Suppose an email is spam with probability and you must report one probability . The expected binary cross-entropy, in nats, is for , for , for , for and for . The lowest value is at the true probability. This is Gibbs’ inequality again: the extra nats at is the KL divergence. So a model trained on cross-entropy is pushed toward probabilities that match the frequencies of the outcomes. That does not guarantee well-calibrated probabilities in practice, because networks can overfit and become overconfident (P3.A10).
Its gradient does not vanish when the model is confidently wrong. Take a sigmoid output and a label . For the cross-entropy loss the derivative with respect to the logit is . For half the squared error, , the chain rule adds the slope of the sigmoid and the derivative becomes . When the model is confidently wrong, is near , and the extra factor is near as well.
| Logit | Cross-entropy gradient | Squared-error gradient | |
|---|---|---|---|
The label is in every row, so the rows from top to bottom go from very wrong to fairly right. At the cross-entropy gradient is about times the squared-error one. Squared error learns slowest exactly where the model is most wrong, and among the rows above it learns fastest at (over all its push is largest at ). Cross-entropy pushes hardest when the model is most wrong, and its gradient shrinks as the prediction gets right. The losses differ in the same way: half the squared error never exceeds , while has no upper limit. The same argument applies to a softmax output.
Soft targets and the floor of the loss
A target does not have to be one-hot. Label smoothing (P4.17) replaces a one-hot label by times the one-hot vector plus on every class, so the model is not asked to give the true class probability . Distillation (P10.F2) trains a small student on the probabilities of a larger teacher, usually softened with a temperature and often combined with the ordinary hard-label loss; those probabilities are soft targets too. Both minimize with a that has several nonzero entries, and the formula and the gradient stay the same.
For soft targets the lowest possible loss is not . By Gibbs’ inequality it is , reached only when . Take and , so with entropy bits ( nats). Three models:
- gives bits, the minimum.
- A flatter gives bits.
- A sharper, more confident gives bits.
So with a smoothed target an overconfident model is penalized, which is the point of smoothing. The same fact explains a common worry. If identical inputs come with labels that are one class and another, the best possible loss on them is the entropy nats ( bits), not . A training loss that stops above is not by itself a sign of a bug: the floor is the entropy of the labels (and a one-hot label with a deterministic answer does have a floor of ).
Units, frameworks and language models
Nats, and the loss at the start. Deep-learning frameworks use the natural logarithm, so reported losses are in nats. To convert to bits divide by : the nats above is bits. A model that has learned nothing and gives every class probability has loss : for and for . When training starts, a loss near is a useful sanity check.
PyTorch. The function torch.nn.CrossEntropyLoss takes the raw logits and the class indices, applies a log-softmax internally and by default returns the mean over the examples in the batch. Do not apply a softmax first, because it would be applied twice. Recent versions also accept class probabilities as targets (soft labels) and a label-smoothing option; check the documentation of your version. For two classes with one logit per example, torch.nn.BCEWithLogitsLoss takes the logit and combines the sigmoid with the binary cross-entropy in one stable step.
Language models. A language model scores each next token as a classification over its vocabulary, so pretraining (P10.A1) minimizes the cross-entropy of the next token, averaged over all tokens. The result is reported in nats per token (or bits per token). For three tokens that the model gave probabilities , and , the average loss is nats ( bits), and its exponential, , is the perplexity: the model is as unsure as a fair choice among tokens. P1.E5 covers perplexity in full.
Go deeper The loss over a whole data set
For a data set the true distribution is the empirical one: the fraction of the examples that have each label. The average loss is then (for each fixed input, or for a model that ignores the input) the cross-entropy of the model relative to the data, and in the large-sample limit it approaches for the true source (the Go-deeper box in P1.D10). The entropy of the source does not depend on the parameters , so the parameters that minimize the average loss are the ones that minimize the KL divergence, and they are the maximum-likelihood parameters. For a deterministic labelling, and the loss can in principle go to .
Try it
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first block prints for , for ( nats), an extra of , for the swapped cross-entropy and for the uniform model. The second shows inf for and for the swapped one. The third prints the probabilities , the loss nats and the gradient . The fourth shows nan for the naive softmax, and the stable loss is or . The fifth reproduces the table above, and the last two give , , , a perplexity of and the uniform-guess losses and . Try it yourself: make equal to in the first block and confirm that the extra is .
Intuition, math and code at a glance
Intuition
Cross-entropy is how surprised a model is, on average, by what really happens. The truth decides which outcomes occur, and the model decides how surprising each one is. If the model’s probabilities match reality the surprise is as small as it can be, the entropy. Any mismatch adds to it. For a label that is certain, the loss is just the surprise at the true class: give it probability near and the loss is near , give it near and the loss is huge. It is also the average number of bits you pay when you compress data with a code built for the wrong distribution; the part above the entropy is the extra.
Math
For a one-hot label and logits :
Facts to remember:
- the first argument is the truth and the second is the model, and
- if where
- binary cross-entropy is
- over examples the loss is the average negative log-likelihood (P1.D10)
- a uniform guess among classes has loss nats, and the perplexity is
Code
Cross-entropy from logits with NumPy, using the stable form. In PyTorch, the function cross_entropy of torch.nn.functional does the same for a batch of logits with shape and integer class targets of shape .
import numpy as np
def cross_entropy_from_logits(z, c):
m = np.max(z)
lse = m + np.log(np.exp(z - m).sum()) # log-sum-exp
return lse - z[c] # loss in nats
print(cross_entropy_from_logits(np.array([1.0, 2.0, 3.0]), 2)) # about 0.4076Common mistakes
Check your understanding
The true distribution is and a model predicts . What is the cross-entropy ?
Outcomes come from and surprise is measured with : bits. The value bits is the entropy of , which is what a perfect model would score. The value bits is the entropy of , which averages 's surprise with 's own weights. The value bits is , with the roles swapped.
A classifier gives the true class of an example probability , and the label is one-hot. What is the cross-entropy loss in nats?
For a one-hot label the loss is the surprise of the true class, nats ( bits). The value is the probability itself, not its surprise. The value is , the surprise of the probability of being wrong. The value is one minus the probability, which is not a log loss.
Which statement about is correct?
This is Gibbs' inequality: the best model of a source is the source itself, and anything else costs more. The two orders give different numbers in general ( against bits in the lesson example). When the cross-entropy is the entropy , which is only if is certain. A zero in where is positive makes the surprise infinite, and so the cross-entropy.
A sigmoid classifier outputs for an example whose label is (a logit of ). The gradient of the cross-entropy with respect to the logit is . What is the gradient of half the squared error, , with respect to the same logit?
The squared error adds the slope of the sigmoid, so the gradient is , about times smaller than the cross-entropy gradient. The value is the cross-entropy gradient itself. The value is the squared-error gradient at a logit of , where the model is at . The value is the derivative of the cross-entropy with respect to , not with respect to the logit.
A model is trained to match the smoothed target with cross-entropy. What is the lowest loss any model can reach?
The lowest cross-entropy is , reached when , and for this target bits. A loss of is possible only for a certain (one-hot) target. The value bits is , the surprise of the top class alone, which ignores the other classes that carry probability in the target. The value bits is the loss of a uniform guess over four classes.
Exercises
- A fair coin has and a model says . Find and in bits.
Show answer
bits. bit, because gives both outcomes surprise bit. They differ, so cross-entropy is not symmetric. Note that is larger than the entropy of the fair coin, bit. - Logits give . If the first class is true, find the loss in nats and the gradient with respect to the logits.
Show answer
The loss is nats. The gradient is . The wrong classes with the largest probability are pushed down hardest, and the entries add to . - Labels and predicted probabilities of class of . Find the average binary cross-entropy in nats.
Show answer
The truth gets . The losses are , adding to , and the average is nats. - Logits and the second class is true. Find the loss with the stable formula.
Show answer
, and subtracting gives nats. The naive softmax would overflow, because is too large for ordinary floating point. - A classifier with classes outputs the same probability for every class. What is its loss on any example, in nats and in bits?
Show answer
Each probability is , so the loss is nats, which is bits. - The smoothing of P1.E2 with and gives the target . What is the lowest cross-entropy against it, in bits and nats?
Show answer
The entropy of the target, bits (P1.E2), which is nats. It is reached only when the model outputs exactly this target. - An email is spam with probability . Find the expected binary cross-entropy in nats of reporting and of reporting , and the difference.
Show answer
Reporting : . Reporting : . The difference nats is the extra cost of the wrong report, the KL divergence . - A language model has an average loss of nats per token. Express this in bits per token and find the perplexity.
Show answer
bits per token. The perplexity is , and also : the same number in either unit.
Next: P1.E4 studies the extra cost on its own: why it is never negative, why it is not symmetric, and what its two directions mean when you fit a model. P1.E5 covers mutual information and perplexity. P3.A7 and P3.A8 train logistic and softmax regression by minimizing the cross-entropy, and P4.6 compares it with the other loss functions.