Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsInformation Theory

Cross-entropy

P1.E335 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Cross-entropy is the number that scores a predicted probability distribution against what really happened, and it is the loss that almost every classifier and language model is trained to minimize.

  • Logistic regression and softmax regression are trained by minimizing the cross-entropy between the labels and the predicted probabilities, and so is nearly every classification network. (P3.A8: Softmax regression, coming soon)
  • A language model is pretrained by minimizing the average cross-entropy of the next token, reported as nats per token. (P10.A1: What is a Large Language Model?, coming soon)
  • Distillation trains a small student to match a teacher's probabilities by minimizing the cross-entropy to them, and label smoothing trains against a softened target. (P10.F2: Distillation and small models, coming soon)
  • The exponential of the average cross-entropy per token is the perplexity, the standard way to compare language models. (P1.E5: Mutual information and perplexity, coming soon)

Before this: Information and surprise, Entropy, Maximum Likelihood Estimation

After this lesson you can

  • Define the cross-entropy H(p,q)=−∑xp(x)log⁡q(x)H(p,q)=-\sum_x p(x)\log q(x) as the average surprise of outcomes drawn from the true distribution pp when each is measured with the model's probability qq, compute it for three classes, and read it as the average code length of a code built for qq
  • State and use the facts H(p,q)≥H(p)H(p,q)\ge H(p) with equality exactly when q=pq=p, H(p,q)=H(p)+H(p,q)=H(p)+ the extra cost of using qq (the KL divergence, P1.E4), that H(p,q)≠H(q,p)H(p,q)\ne H(q,p) in general, and that H(p,q)H(p,q) is infinite if qq gives probability 00 to something that can happen
  • Explain why the classification loss is the surprise of the true class, −log⁡qtrue-\log q_{\text{true}}, averaged over the examples, how it appears as binary cross-entropy and as softmax followed by cross-entropy, why its gradient with respect to the logits is q−p\mathbf{q}-\mathbf{p}, and why it trains a confident wrong prediction much faster than squared error
  • Handle practical details: computing the loss stably from logits, nats versus bits, the loss of a uniform guess (ln⁡K\ln K), soft targets from label smoothing and distillation whose lowest loss is the entropy of the target rather than 00, and the link to perplexity

A photo shows a cat. Your model says 70%70\% cat, 20%20\% dog, 10%10\% fox. How wrong is that? Another model says 5%5\% 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, −log⁡p-\log p. 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 pp and the model’s probabilities qq. In a classification problem pp is the label and qq is the model’s output. Entropy averages the surprise −log⁡p(x)-\log p(x) using the same pp twice: it decides how often xx happens and how surprising xx is. Cross-entropy separates the two jobs. Outcomes happen with the probabilities pp, but the surprise is measured with qq:

H(p,q)=Ex∼p[−log⁡q(x)]=−∑xp(x)log⁡q(x).\begin{aligned} H(p,q)&=\mathbb{E}_{x\sim p}\bigl[-\log q(x)\bigr]\\ &=-\sum_x p(x)\log q(x). \end{aligned}

The notation x∼px\sim p means that xx is drawn from pp. Put q=pq=p and the formula becomes the entropy H(p)H(p) of P1.E2, so entropy is the cross-entropy of a distribution with itself.

The convention of P1.E2 carries over. A class with p(x)=0p(x)=0 never happens, so it adds 00 to the sum, even if q(x)q(x) is also 00.

An example with three classes. Let the true probabilities be p=(0.7, 0.2, 0.1)p=(0.7,\,0.2,\,0.1), the distribution used in P1.D3 and P1.E2. A model predicts q=(0.5, 0.25, 0.25)q=(0.5,\,0.25,\,0.25). Its surprises are −log⁡20.5=1-\log_2 0.5=1, −log⁡20.25=2-\log_2 0.25=2 and −log⁡20.25=2-\log_2 0.25=2 bits. Weight each by how often the class really happens:

H(p,q)=0.7×1+0.2×2+0.1×2=0.7+0.4+0.2=1.3 bits.\begin{aligned} H(p,q)&=0.7\times1+0.2\times2+0.1\times2\\ &=0.7+0.4+0.2=1.3\text{ bits}. \end{aligned}

In nats this is 1.3×ln⁡2=0.9011.3\times\ln2=0.901. For comparison, three other models of the same source:

  • The perfect model q=pq=p gives the entropy, H(p)=1.157H(p)=1.157 bits (P1.E2).
  • The model above gives 1.3001.300 bits, which is 0.1430.143 more.
  • A uniform guess q=(13,13,13)q=(\frac13,\frac13,\frac13) gives log⁡23=1.585\log_2 3=1.585 bits, which is 0.4280.428 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 qq gives a class with model probability qq a code word of about −log⁡2q-\log_2 q bits, short for classes the model expects and long for classes it finds unlikely. For the model above the lengths are 11, 22 and 22 bits, which is the code 0, 10, 110,\,10,\,11 of P1.E2. Now send data that really come from pp. The average length is 0.7×1+0.2×2+0.1×2=1.30.7\times1+0.2\times2+0.1\times2=1.3 bits per symbol: exactly the cross-entropy. With ideal code lengths of −log⁡2p(x)-\log_2 p(x) bits (they need not be whole numbers), a code built for the true pp would average 1.1571.157 bits, the entropy. Here a real code with whole-number lengths cannot do better than 0, 10, 110,\,10,\,11 for pp either, so the 0.1430.143-bit gap is the idealized price; a real code built for pp stays within 11 bit of the entropy (P1.E2). Either way, the cross-entropy is the cost of believing qq when the truth is pp, in bits per symbol.

Here the model’s probabilities are powers of 12\frac12, so the lengths are whole numbers. In general −log⁡2q-\log_2 q 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 pp (pink bars) and a model qq (blue bars) and watch the loss. Drag the blue bars, or switch to logits and let a softmax make qq. The row under the charts shows each class’s share of the cross-entropy, and the orange row shows the gradient q−p\mathbf{q}-\mathbf{p} that the loss would send back to the logits.

True distribution p, predicted distribution q, and the loss

True p:
Model q:
True distribution p (fixed; “Swap” exchanges it with q)
00.510.7A0.2B0.1C
Model q (probabilities; they always add up to 1)
00.510.5A0.25B0.25C
Each class’s share of the cross-entropy, −p log₂ q, in bits (they add up to H(p, q); ∞ means p is above 0 and q is 0)
0.70.40.2
Gradient of the loss with respect to the logits, q − p (the model is pushed to lower the classes with a positive entry)
−0.20.050.15
entropy H(p) = 1.157 bits (0.802 nats)
cross-entropy H(p, q) = 1.3 bits (0.901 nats)
extra H(p, q) − H(p) = 0.143 bits (0.0993 nats)
swapped roles, H(q, p) = 1.668 bits

H(p, q) = 1.3 bits is above the entropy H(p) = 1.157 bits by 0.143 bits. That extra is the KL divergence (P1.E4). Moving q toward p lowers the cross-entropy; no q goes below H(p).

Drag on the q chart (it snaps to 0.01), or Tab to a bar and use the arrow keys (0.01), Page Up and Page Down (0.1), Home (0) and End (1). “Edit logits” changes q through a softmax instead. Values are rounded for display.

Cross-entropy of a model q against a true distribution p over K classes. The pink bars are the true probabilities p, chosen from three presets (one-hot, smoothed and soft) or set by the swap button. The blue bars are the model's probabilities q, which you can drag or set through logits and a softmax. Under the bars are each class's share of the cross-entropy, minus p times log base 2 of q, which add up to the cross-entropy H of p and q, and the gradient q minus p of the loss with respect to the logits. Readouts show the entropy of p, the cross-entropy, the extra over the entropy, and the cross-entropy with the roles of p and q swapped, in bits and nats. A probability of 0 for a class that can happen gives an infinite loss.

What to try:

  • The lesson example. Press “Lesson example”: H(p)=1.157H(p)=1.157, H(p,q)=1.3H(p,q)=1.3, extra 0.1430.143, and swapped 1.6681.668.
  • Match. Press “Matches p”: the cross-entropy equals the entropy and the extra is 00. No other qq does better, and you can try: drag a bar away from pp and the loss only rises.
  • One-hot. Choose “One-hot” for pp and press “Uniform guess” with K=3K=3: the loss is log⁡23=1.585\log_2 3=1.585 bits, the surprise of the true class A, which has q=13q=\frac13. Now drag the A bar: the loss is always −log⁡2qA-\log_2 q_A, so it is 11 bit at 0.50.5 and 22 bits at 0.250.25. Only qAq_A 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 0.0010.001 and the loss is about 9.979.97 bits (6.916.91 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 ∞\infty.
  • Soft targets. Choose “Smoothed” and press “Matches p”: the loss is not 00, 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 H(p,q)H(p,q) with H(q,p)H(q,p).

What cross-entropy cannot be

It is never below the entropy. For every pp and qq,

H(p,q)≥H(p),H(p,q)\ge H(p),

with equality exactly when q=pq=p. 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 qq instead of pp:

H(p,q)=H(p)+KL(p ∥ q).H(p,q)=H(p)+\mathrm{KL}(p\,\|\,q).

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”: 0.1430.143 bits in our example, and always at least 00. This split explains how training works. The entropy H(p)H(p) 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 p=(0.7,0.2,0.1)p=(0.7,0.2,0.1) and q=(0.5,0.25,0.25)q=(0.5,0.25,0.25):

H(p,q)=1.300 bitsH(q,p)=1.668 bits.\begin{aligned} H(p,q)&=1.300\text{ bits}\\ H(q,p)&=1.668\text{ bits}. \end{aligned}

In H(q,p)H(q,p) the outcomes are drawn from qq and surprise is measured with pp, a different question, so a different number. That is why cross-entropy is not a distance between pp and qq. 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 q(x)=0q(x)=0 for something that happens with p(x)>0p(x)>0, the surprise is −log⁡0=∞-\log 0=\infty and so is H(p,q)H(p,q). Take p=(0.7,0.2,0.1)p=(0.7,0.2,0.1) and a model q=(0.5,0.5,0)q=(0.5,0.5,0) that rules out the third class: H(p,q)=∞H(p,q)=\infty. In the other direction, H(q,p)=1.418H(q,p)=1.418 bits is finite, because pp has no zeros. In H(p,q)H(p,q), the order used in a loss, a zero in pp is harmless and a zero in qq is deadly. In exact arithmetic a softmax output is never 00, but it can be tiny, and in floating point a very tiny value can even underflow to exactly 00 (which is why frameworks compute with log-probabilities). A tiny qq 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 SS be the set of classes with p(x)>0p(x)>0; the sums below run over SS. Call the gap D=H(p,q)−H(p)D=H(p,q)-H(p). Then

D=∑Spln⁡pq=−∑Spln⁡qp.\begin{aligned} D&=\sum_S p\ln\frac{p}{q}\\ &=-\sum_S p\ln\frac{q}{p}. \end{aligned}

The inequality ln⁡u≤u−1\ln u\le u-1 holds for every u>0u>0, with equality only at u=1u=1 (the same fact as in the proof in P1.D10). Apply it with u=q(x)/p(x)u=q(x)/p(x):

D≥−∑Sp(qp−1)=1−∑Sq ≥ 0.\begin{aligned} D&\ge-\sum_S p\Bigl(\frac{q}{p}-1\Bigr)\\ &=1-\sum_S q\ \ge\ 0. \end{aligned}

The last step holds because the qq over those classes add up to at most 11. Both steps are equalities only if q(x)=p(x)q(x)=p(x) for every xx. So H(p,q)≥H(p)H(p,q)\ge H(p) with equality exactly when q=pq=p. If some q(x)=0q(x)=0 with p(x)>0p(x)>0 the gap is ∞\infty and the inequality holds anyway.

The classification loss

Now take pp to be a label. A one-hot label puts all of its probability on the true class cc: yc=1y_c=1 and every other yi=0y_i=0. Every term of −∑iyilog⁡qi-\sum_i y_i\log q_i with yi=0y_i=0 vanishes, and what is left is

H(y,q)=−log⁡qc.H(\mathbf y,\mathbf q)=-\log q_c.

The cross-entropy loss of one example is the surprise of the true class (P1.E1). A one-hot label has entropy 00, so the extra equals the whole loss. In P1.D3 a classifier gave (0.7,0.2,0.1)(0.7,0.2,0.1) and the first class was true: the loss is −ln⁡0.7=0.3567-\ln0.7=0.3567 nats, which is 0.51460.5146 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 11: to raise qcq_c the model must lower the rest.

With NN examples, the loss reported during training is the average,

L=1N∑n=1N−ln⁡qcn(n),\mathcal{L}=\frac1N\sum_{n=1}^{N}-\ln q_{c_n}^{(n)},

where qcn(n)q^{(n)}_{c_n} is the probability that example nn 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 y∈{0,1}y\in\{0,1\} the true distribution is (y, 1−y)(y,\,1-y) and the model’s is (q, 1−q)(q,\,1-q), where qq is the predicted probability that y=1y=1 (a sigmoid output, P1.A5). The formula becomes

−[ yln⁡q+(1−y)ln⁡(1−q) ].-\bigl[\,y\ln q+(1-y)\ln(1-q)\,\bigr].

These are the numbers of P1.D3. A spam model says q=0.8q=0.8. If the email is spam (y=1y=1) the truth had probability 0.80.8 and the loss is −ln⁡0.8=0.2231-\ln0.8=0.2231. If it is not spam (y=0y=0) the truth had probability 0.20.2 and the loss is −ln⁡0.2=1.6094-\ln0.2=1.6094. For labels (1,0,1)(1,0,1) and predictions (0.8,0.3,0.6)(0.8,0.3,0.6) the truth gets 0.80.8, 0.70.7 and 0.60.6, the losses are 0.22310.2231, 0.35670.3567 and 0.51080.5108, and their average is 0.36350.3635 nats.

From logits to the loss

A network does not output probabilities directly. It outputs a score ziz_i per class, called a logit, and a softmax turns them into probabilities (P1.C7, P3.A8):

qi=ezi∑jezj.q_i=\frac{\mathrm{e}^{z_i}}{\sum_j\mathrm{e}^{z_j}}.

For z=(1,2,3)\mathbf z=(1,2,3) the probabilities are q=(0.0900, 0.2447, 0.6652)\mathbf q=(0.0900,\,0.2447,\,0.6652). If the third class is true, the loss is −ln⁡0.6652=0.4076-\ln0.6652=0.4076 nats, or 0.5880.588 bits.

The stable form. Taking the log of the softmax gives ln⁡qc=zc−ln⁡∑jezj\ln q_c=z_c-\ln\sum_j\mathrm{e}^{z_j}, so

L=−ln⁡qc=ln⁡∑jezj−zc.L=-\ln q_c=\ln\sum_j\mathrm{e}^{z_j}-z_c.

The term ln⁡∑jezj\ln\sum_j\mathrm{e}^{z_j} is the log-sum-exp of the logits. Software computes the loss this way instead of forming qcq_c and then taking its log, and it subtracts the largest logit inside the exponentials first (P1.G2). The reason is range. For z=(1000,0,0)\mathbf z=(1000,0,0) the exponential e1000\mathrm{e}^{1000} overflows ordinary floating-point numbers, so the naive softmax returns nan. The log-sum-exp form gives a loss of 00 if the first class is true and 10001000 if the second class is true, with no overflow. The loss −ln⁡qc-\ln q_c is also never computed as the log of an underflowed 00.

The gradient with respect to the logits is q−p\mathbf{q}-\mathbf{p}. For a one-hot target this is the probabilities minus the one-hot vector, the result of P1.C7 and P1.C11. For z=(1,2,3)\mathbf z=(1,2,3) with the third class true:

∇zL=(0.0900, 0.2447, −0.3348).\nabla_{\mathbf z}L=(0.0900,\ 0.2447,\ -0.3348).

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 00, and the whole vector is 0\mathbf 0 only when q=p\mathbf q=\mathbf p. The size of the push is simply how wrong the probabilities are. The orange row in the widget is this vector for any pp you choose (the derivation is in the box below).

Go deeper Where the gradient q minus p comes from

For any target p\mathbf p whose entries add to 11, the loss from logits is

L=−∑ipiln⁡qi=−∑ipizi+ln⁡∑jezj.\begin{aligned} L&=-\sum_i p_i\ln q_i\\ &=-\sum_i p_i z_i+\ln\sum_j\mathrm{e}^{z_j}. \end{aligned}

The first part used ∑ipi=1\sum_i p_i=1. The derivative of the first term with respect to ziz_i is −pi-p_i. The derivative of the log-sum-exp is ezi/∑jezj=qi\mathrm{e}^{z_i}/\sum_j\mathrm{e}^{z_j}=q_i (the chain rule on ln⁡\ln, P1.C3). So ∂L/∂zi=qi−pi\partial L/\partial z_i=q_i-p_i. 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 KK 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 0.80.8 and you must report one probability rr. The expected binary cross-entropy, in nats, is 0.6930.693 for r=0.5r=0.5, 0.5260.526 for r=0.7r=0.7, 0.5000.500 for r=0.8r=0.8, 0.5450.545 for r=0.9r=0.9 and 0.9290.929 for r=0.99r=0.99. The lowest value is at the true probability. This is Gibbs’ inequality again: the extra 0.5448−0.5004=0.04440.5448-0.5004=0.0444 nats at r=0.9r=0.9 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 q=σ(z)q=\sigma(z) and a label y=1y=1. For the cross-entropy loss the derivative with respect to the logit is q−yq-y. For half the squared error, 12(q−y)2\frac12(q-y)^2, the chain rule adds the slope of the sigmoid and the derivative becomes (q−y) q (1−q)(q-y)\,q\,(1-q). When the model is confidently wrong, qq is near 00, and the extra factor q(1−q)q(1-q) is near 00 as well.

Logit zzqqCross-entropy gradientSquared-error gradient
−4-40.0180.018−0.982-0.982−0.0173-0.0173
−2-20.1190.119−0.881-0.881−0.0925-0.0925
000.50.5−0.5-0.5−0.125-0.125
220.8810.881−0.119-0.119−0.0125-0.0125

The label is 11 in every row, so the rows from top to bottom go from very wrong to fairly right. At z=−4z=-4 the cross-entropy gradient is about 5757 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 q=0.5q=0.5 (over all qq its push is largest at q=1/3q=1/3). 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 0.50.5, while −ln⁡q-\ln q 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 (1−ε)(1-\varepsilon) times the one-hot vector plus ε/K\varepsilon/K on every class, so the model is not asked to give the true class probability 11. 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 H(p,q)H(p,q) with a pp that has several nonzero entries, and the formula and the gradient q−p\mathbf q-\mathbf p stay the same.

For soft targets the lowest possible loss is not 00. By Gibbs’ inequality it is H(p)H(p), reached only when q=pq=p. Take K=4K=4 and ε=0.2\varepsilon=0.2, so p=(0.85, 0.05, 0.05, 0.05)p=(0.85,\,0.05,\,0.05,\,0.05) with entropy 0.8480.848 bits (0.5880.588 nats). Three models:

  • q=pq=p gives 0.8480.848 bits, the minimum.
  • A flatter q=(0.7,0.1,0.1,0.1)q=(0.7,0.1,0.1,0.1) gives 0.9360.936 bits.
  • A sharper, more confident q=(0.97,0.01,0.01,0.01)q=(0.97,0.01,0.01,0.01) gives 1.0341.034 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 80%80\% one class and 20%20\% another, the best possible loss on them is the entropy H(0.8)=0.500H(0.8)=0.500 nats (0.7220.722 bits), not 00. A training loss that stops above 00 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 00).

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 ln⁡2\ln2: the 0.40760.4076 nats above is 0.5880.588 bits. A model that has learned nothing and gives every class probability 1K\frac1K has loss ln⁡K\ln K: 2.3032.303 for K=10K=10 and 6.9086.908 for K=1000K=1000. When training starts, a loss near ln⁡K\ln K 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 0.50.5, 0.250.25 and 0.1250.125, the average loss is 1.3861.386 nats (22 bits), and its exponential, e1.386=4\mathrm{e}^{1.386}=4, is the perplexity: the model is as unsure as a fair choice among 44 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 p^(x)\hat p(x) of the examples that have each label. The average loss 1N∑n−ln⁡qcn(n)\frac1N\sum_n -\ln q^{(n)}_{c_n} 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 H(p)+KL(p ∥ qθ)H(p)+\mathrm{KL}(p\,\|\,q_{\boldsymbol\theta}) for the true source pp (the Go-deeper box in P1.D10). The entropy of the source does not depend on the parameters θ\boldsymbol\theta, 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, H(p)=0H(p)=0 and the loss can in principle go to 00.

Try it

Try it: cross-entropy, the stable form, gradients and soft targets

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first block prints 1.15681.1568 for H(p)H(p), 1.31.3 for H(p,q)H(p,q) (0.90110.9011 nats), an extra of 0.14320.1432, 1.66831.6683 for the swapped cross-entropy and 1.5851.585 for the uniform model. The second shows inf for H(p,q0)H(p,q_0) and 1.41831.4183 for the swapped one. The third prints the probabilities (0.09, 0.2447, 0.6652)(0.09,\,0.2447,\,0.6652), the loss 0.40760.4076 nats and the gradient (0.09, 0.2447, −0.3348)(0.09,\,0.2447,\,-0.3348). The fourth shows nan for the naive softmax, and the stable loss is 00 or 10001000. The fifth reproduces the table above, and the last two give 0.8480.848, 1.0341.034, 0.9360.936, a perplexity of 44 and the uniform-guess losses 2.3032.303 and 6.9086.908. Try it yourself: make qq equal to pp in the first block and confirm that the extra is 00.

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 11 and the loss is near 00, give it near 00 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

H(p,q)=−∑xp(x)log⁡q(x)=H(p)+KL(p ∥ q)H(p,q)≥H(p)\begin{aligned} H(p,q)&=-\sum_x p(x)\log q(x)\\ &=H(p)+\mathrm{KL}(p\,\|\,q)\\ H(p,q)&\ge H(p) \end{aligned}

For a one-hot label and logits z\mathbf z:

L=−ln⁡qc=ln⁡∑jezj−zc∇zL=q−y\begin{aligned} L&=-\ln q_c\\ &=\ln\sum_j\mathrm{e}^{z_j}-z_c\\ \nabla_{\mathbf z}L&=\mathbf q-\mathbf y \end{aligned}

Facts to remember:

  • the first argument is the truth and the second is the model, and H(p,q)≠H(q,p)H(p,q)\ne H(q,p)
  • H(p,q)=∞H(p,q)=\infty if q(x)=0q(x)=0 where p(x)>0p(x)>0
  • binary cross-entropy is −[yln⁡q+(1−y)ln⁡(1−q)]-[y\ln q+(1-y)\ln(1-q)]
  • over NN examples the loss is the average negative log-likelihood (P1.D10)
  • a uniform guess among KK classes has loss ln⁡K\ln K nats, and the perplexity is eaverage loss\mathrm{e}^{\text{average loss}}

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 (N,K)(N,K) and integer class targets of shape (N)(N).

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.4076

Common mistakes

Check your understanding

  1. The true distribution is p=(0.7, 0.2, 0.1)p=(0.7,\,0.2,\,0.1) and a model predicts q=(0.5, 0.25, 0.25)q=(0.5,\,0.25,\,0.25). What is the cross-entropy H(p,q)H(p,q)?

  2. A classifier gives the true class of an example probability 0.250.25, and the label is one-hot. What is the cross-entropy loss in nats?

  3. Which statement about H(p,q)H(p,q) is correct?

  4. A sigmoid classifier outputs q=0.018q=0.018 for an example whose label is 11 (a logit of −4-4). The gradient of the cross-entropy with respect to the logit is q−y=−0.982q-y=-0.982. What is the gradient of half the squared error, 12(q−y)2\frac12(q-y)^2, with respect to the same logit?

  5. A model is trained to match the smoothed target p=(0.85, 0.05, 0.05, 0.05)p=(0.85,\,0.05,\,0.05,\,0.05) with cross-entropy. What is the lowest loss any model can reach?

Exercises

  1. A fair coin has p=(0.5,0.5)p=(0.5,0.5) and a model says q=(0.9,0.1)q=(0.9,0.1). Find H(p,q)H(p,q) and H(q,p)H(q,p) in bits.
    Show answerH(p,q)=0.5×0.152+0.5×3.322=1.737H(p,q)=0.5\times0.152+0.5\times3.322=1.737 bits. H(q,p)=0.9×1+0.1×1=1H(q,p)=0.9\times1+0.1\times1=1 bit, because pp gives both outcomes surprise 11 bit. They differ, so cross-entropy is not symmetric. Note that H(p,q)H(p,q) is larger than the entropy of the fair coin, 11 bit.
  2. Logits (1,2,3)(1,2,3) give q=(0.0900,0.2447,0.6652)\mathbf q=(0.0900,0.2447,0.6652). If the first class is true, find the loss in nats and the gradient with respect to the logits.
    Show answerThe loss is −ln⁡0.0900=2.408-\ln0.0900=2.408 nats. The gradient is q−y=(0.0900−1, 0.2447, 0.6652)=(−0.9100, 0.2447, 0.6652)\mathbf q-\mathbf y=(0.0900-1,\ 0.2447,\ 0.6652)=(-0.9100,\ 0.2447,\ 0.6652). The wrong classes with the largest probability are pushed down hardest, and the entries add to 00.
  3. Labels (1,1,0,0)(1,1,0,0) and predicted probabilities of class 11 of (0.9,0.6,0.2,0.5)(0.9,0.6,0.2,0.5). Find the average binary cross-entropy in nats.
    Show answerThe truth gets 0.9, 0.6, 0.8, 0.50.9,\ 0.6,\ 0.8,\ 0.5. The losses are 0.1054, 0.5108, 0.2231, 0.69310.1054,\ 0.5108,\ 0.2231,\ 0.6931, adding to 1.53251.5325, and the average is 0.3830.383 nats.
  4. Logits (1000,998)(1000,998) and the second class is true. Find the loss with the stable formula.
    Show answerln⁡∑jezj=1000+ln⁡(1+e−2)=1000.1269\ln\sum_j\mathrm{e}^{z_j}=1000+\ln(1+\mathrm{e}^{-2})=1000.1269, and subtracting zc=998z_c=998 gives 2.1272.127 nats. The naive softmax would overflow, because e1000\mathrm{e}^{1000} is too large for ordinary floating point.
  5. A classifier with 100100 classes outputs the same probability for every class. What is its loss on any example, in nats and in bits?
    Show answerEach probability is 0.010.01, so the loss is ln⁡100=4.605\ln100=4.605 nats, which is log⁡2100=6.644\log_2100=6.644 bits.
  6. The smoothing of P1.E2 with K=10K=10 and ε=0.1\varepsilon=0.1 gives the target (0.91,0.01,…,0.01)(0.91,0.01,\dots,0.01). What is the lowest cross-entropy against it, in bits and nats?
    Show answerThe entropy of the target, 0.7220.722 bits (P1.E2), which is 0.722×ln⁡2=0.5000.722\times\ln2=0.500 nats. It is reached only when the model outputs exactly this target.
  7. An email is spam with probability 0.80.8. Find the expected binary cross-entropy in nats of reporting 0.80.8 and of reporting 0.90.9, and the difference.
    Show answerReporting 0.80.8: −(0.8ln⁡0.8+0.2ln⁡0.2)=0.5004-(0.8\ln0.8+0.2\ln0.2)=0.5004. Reporting 0.90.9: −(0.8ln⁡0.9+0.2ln⁡0.1)=0.5448-(0.8\ln0.9+0.2\ln0.1)=0.5448. The difference 0.04440.0444 nats is the extra cost of the wrong report, the KL divergence 0.8ln⁡0.80.9+0.2ln⁡0.20.10.8\ln\frac{0.8}{0.9}+0.2\ln\frac{0.2}{0.1}.
  8. A language model has an average loss of 2.02.0 nats per token. Express this in bits per token and find the perplexity.
    Show answer2.0/ln⁡2=2.8852.0/\ln2=2.885 bits per token. The perplexity is e2=7.389\mathrm{e}^{2}=7.389, and also 22.885=7.3892^{2.885}=7.389: the same number in either unit.

Next: P1.E4 studies the extra cost KL(p ∥ q)\mathrm{KL}(p\,\|\,q) 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.

Key takeaways

  • The cross-entropy of a model qq relative to the true distribution pp is H(p,q)=−∑xp(x)log⁡q(x)=Ex∼p[−log⁡q(x)]H(p,q)=-\sum_x p(x)\log q(x)=\mathbb{E}_{x\sim p}[-\log q(x)]: the average surprise of outcomes drawn from pp, measured with the model's probabilities. Equivalently, it is the average length of a code built for qq when the data really come from pp. Classes with p=0p=0 add 00.
  • Gibbs' inequality: H(p,q)≥H(p)H(p,q)\ge H(p), with equality exactly when q=pq=p. The gap is the cost of using the wrong model, H(p,q)=H(p)+KL(p ∥ q)H(p,q)=H(p)+\mathrm{KL}(p\,\|\,q) (P1.E4). For p=(0.7,0.2,0.1)p=(0.7,0.2,0.1) and q=(0.5,0.25,0.25)q=(0.5,0.25,0.25): H(p)=1.157H(p)=1.157, H(p,q)=1.300H(p,q)=1.300 and the extra is 0.1430.143 bits. Cross-entropy is not symmetric: H(q,p)=1.668H(q,p)=1.668. It is infinite if q(x)=0q(x)=0 where p(x)>0p(x)>0.
  • For a one-hot label the cross-entropy is the surprise of the true class, −log⁡qtrue-\log q_{\text{true}}. Averaged over NN examples it is the negative log-likelihood (P1.D10), so minimizing it is maximum likelihood. With two classes it is binary cross-entropy: −[yln⁡q+(1−y)ln⁡(1−q)]-[y\ln q+(1-y)\ln(1-q)] gives 0.22310.2231, 0.35670.3567 and 0.51080.5108 for three examples, average 0.36350.3635 nats.
  • Softmax followed by cross-entropy is computed from the logits as log⁡∑jezj−ztrue\log\sum_j\mathrm{e}^{z_j}-z_{\text{true}}, which stays finite where the naive formula overflows. Its gradient with respect to the logits is q−p\mathbf{q}-\mathbf{p} (P1.C7): for z=(1,2,3)\mathbf z=(1,2,3) and the third class true it is (0.0900, 0.2447, −0.3348)(0.0900,\,0.2447,\,-0.3348).
  • Cross-entropy is the classification loss because it is the negative log-likelihood, because the expected loss is lowest when the model reports the true probabilities, and because its gradient does not shrink when a sigmoid or softmax output is confidently wrong: at q=0.018q=0.018 for a true label of 11 the gradient is −0.982-0.982 against −0.0173-0.0173 for squared error.
  • Frameworks report the loss in nats, averaged over examples (or tokens). A uniform guess among KK classes scores ln⁡K\ln K. Soft targets (label smoothing, distillation) have a lowest possible loss equal to the target's entropy, not 00. The exponential of a language model's average loss is the perplexity (P1.E5).
Found a mistake? Tell us