Cross-Entropy

How do you grade a model that answers with probabilities instead of a single guess?

The idea

Cross-entropy scores predictions by the negative log probability assigned to the target. In this next-token example, assigning less probability to the correct token raises the loss; assigning zero probability gives infinite loss.

Builds on Maximum Likelihood.

The picture

Cross-entropy is the negative log probability a model gives to an outcome, averaged over outcomes drawn from a target distribution. We use a next-word prediction for The cat sat on the …, where the target is the one true word, and grade the model's probabilities once that word is known. The figure and code show the loss rising as the true word receives less probability. You will need probabilities and logarithms.

Score. The model gives every candidate a score, its logit: the bars in the figure. A logit can be any number, positive or negative; on its own it is not yet a probability.

Share. Softmax turns the scores into shares of one pie: raise ee to each score, then divide by the total. The pie never grows, so any word that gains a share takes it from the others.

Grade. Then the true word arrives, and the model is graded on one number: the share it gave that word. The loss is −log⁡-\log of that share: the falling curve. Give the right word everything and the loss is zero; give it half and the loss is log⁡2≈0.69\log 2 \approx 0.69; give it almost nothing and the loss climbs without limit. A model that is sure and wrong pays far more than one that admits it does not know.

Push. The arrows are what training does about it: which way each score moves to lower the loss, and how hard. Only the right word appears in the loss, yet every bar has an arrow, because every score feeds the total that the right word's share is divided by.

When the target is itself uncertain, because annotators disagree or labels are deliberately softened, the same surprise is averaged over the outcomes, weighted by how likely the target says each one is. That average is the cross-entropy H(p,q)H(p,q); the single right word is the case where the target puts all its weight on one outcome.

Predict first

The model reads The cat sat on the … and gives mat 63%, sofa 23%, roof 10% and moon 3%. The right word is mat. Training nudges every word's score to lower the loss. Before you touch the figure: which wrong word's score is pushed down hardest?

The mathematics

Let XX be a discrete label taking values in {1,…,K}\{1,\dots,K\}. Let pk=Ptarget(X=k)p_k=P_{\mathrm{target}}(X=k) be the target distribution and let qk=Pθ(X=k)q_k=P_{\theta}(X=k) be the model distribution. Assume pk≥0p_k\ge 0, qk>0q_k>0, and ∑kpk=∑kqk=1\sum_k p_k=\sum_k q_k=1. All logarithms here are natural logarithms, so the units are nats.

For supervised classification, read this as a per-input statement. For an input xix_i, the target distribution is pk(i)=Ptarget(Y=k∣xi)p^{(i)}_k=P_{\mathrm{target}}(Y=k\mid x_i) and the model distribution is qk(i)=Pθ(Y=k∣xi)q^{(i)}_k=P_\theta(Y=k\mid x_i). The dataset loss averages H(p(i),q(i))H(p^{(i)},q^{(i)}) over examples.

The cross-entropy from pp to qq is

H(p,q)=−∑k=1Kpklog⁡qk.H(p,q)=-\sum_{k=1}^K p_k \log q_k.

Equivalently,

H(p,q)=EX∼p[−log⁡qX].H(p,q)=\mathbb E_{X\sim p}[-\log q_X].

The direction matters: pp supplies the averaging weights, while qq supplies the probabilities being scored. If pk>0p_k>0 and qkq_k is near zero, the penalty becomes very large. If pk>0p_k>0 and qk=0q_k=0, the mathematical loss is infinite. If pk=0p_k=0, that class does not contribute directly to this cross-entropy term.

For a one-hot target yy, where py=1p_y=1 and all other pk=0p_k=0,

H(p,q)=−log⁡qy.H(p,q)=-\log q_y.

This is exactly the per-example negative log-likelihood used for multiclass classification and next-token language modeling.

The link to KL divergence is

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

where

H(p)=−∑kpklog⁡pk,KL(p∥q)=∑kpklog⁡pkqk.H(p)=-\sum_k p_k\log p_k,\qquad \mathrm{KL}(p\|q)=\sum_k p_k\log\frac{p_k}{q_k}.

Cross-entropy and forward KL share one support rule: both are infinite when some pk>0p_k>0 has qk=0q_k=0. The entropy H(p)H(p) does not involve qq at all and is finite on a finite set of classes. When the target distribution pp is fixed, H(p)H(p) is constant with respect to the model. Minimizing cross-entropy over qθq_\theta is therefore the same optimization problem as minimizing KL(p∥qθ)\mathrm{KL}(p\|q_\theta). Maximum likelihood is the empirical version: the data distribution supplies pp, and the model is trained to reduce the average −log⁡qθ(x)-\log q_\theta(x) assigned to observed data.

For one-hot targets, the cross-entropy can be pushed arbitrarily close to 00, but with every qk>0q_k>0 it never reaches it. For soft targets the floor is H(p)H(p), usually above 00, reached when q=pq=p (and only approached when pp has zeros, since softmax keeps every qk>0q_k>0). In that setting, the KL term is the mismatch and H(p)H(p) is the irreducible target uncertainty.

For neural networks, the model usually produces logits z∈RKz\in\mathbb R^K and probabilities

qk=softmax(z)k=ezk∑jezj.q_k=\mathrm{softmax}(z)_k=\frac{e^{z_k}}{\sum_j e^{z_j}}.

For the soft-target loss

ℓ(z,p)=−∑kpklog⁡(softmax(z)k),\ell(z,p)=-\sum_k p_k\log(\mathrm{softmax}(z)_k),

we can derive the logit gradient directly. Since

log⁡(softmax(z)i)=zi−log⁡∑jezj,\log(\mathrm{softmax}(z)_i)=z_i-\log\sum_j e^{z_j},

and ∑ipi=1\sum_i p_i=1,

ℓ(z,p)=−∑ipizi+log⁡∑jezj.\ell(z,p)=-\sum_i p_i z_i+\log\sum_j e^{z_j}.

Therefore the gradient with respect to each logit is

∂ℓ∂zk=qk−pk.\frac{\partial \ell}{\partial z_k}=q_k-p_k.

Classes where qk<pkq_k<p_k get a negative gradient, so gradient descent increases their logits. Classes where qk>pkq_k>p_k get a positive gradient, so gradient descent lowers them.

This is a gradient with respect to the logits. With respect to the probabilities themselves it would be −pk/qk-p_k/q_k; the tidy q−pq-p appears only after differentiating through the softmax. Its components sum to zero, because softmax can only move probability from one class to another.

The two can point in different directions. With p=(1/2,1/4,1/4)p=(1/2,1/4,1/4) and q=(1/2,3/8,1/8)q=(1/2,3/8,1/8), the probability gradient is −p/q=(−1,−2/3,−2)-p/q=(-1,-2/3,-2): every probability "should" rise, which no distribution can do. The logit gradient is q−p=(0,1/8,−1/8)q-p=(0,1/8,-1/8): raise CC, lower BB, leave AA. Here H(p)=32log⁡2H(p)=\tfrac32\log2, H(p,q)=2log⁡2−14log⁡3H(p,q)=2\log2-\tfrac14\log3 and KL(p∥q)=14log⁡43≈0.072\mathrm{KL}(p\|q)=\tfrac14\log\tfrac43\approx0.072 nats. The reverse cross-entropy H(q,p)=32log⁡2H(q,p)=\tfrac32\log2 differs from H(p,q)H(p,q): the order of the two distributions matters.

Same accuracy, different loss

Two classifiers can both be right on every example and still differ in loss. Take classes (A,B,C)(A,B,C), two examples labelled AA and BB, and two models whose outputs are the rows

QM=[1/21/31/61/83/41/8],QN=[2/31/61/61/41/21/4].Q_M=\begin{bmatrix}1/2&1/3&1/6\\1/8&3/4&1/8\end{bmatrix}, \qquad Q_N=\begin{bmatrix}2/3&1/6&1/6\\1/4&1/2&1/4\end{bmatrix}.

Both put the most probability on the right class each time, so both have accuracy 2/22/2. Treating the two examples as independent, the likelihood of the labels is the product of the probabilities given to them: 12⋅34=38\tfrac12\cdot\tfrac34=\tfrac38 for MM and 23⋅12=13\tfrac23\cdot\tfrac12=\tfrac13 for NN. The mean one-hot cross-entropy is 12log⁡83≈0.490\tfrac12\log\tfrac83\approx0.490 nats for MM and 12log⁡3≈0.549\tfrac12\log3\approx0.549 for NN. Taking logs keeps the order and the minus sign reverses it, so the higher likelihood and the lower cross-entropy pick the same model, MM, whose confidence went to what actually happened. Two examples, of course, say nothing about either model on new data.

Try it

First a worked example, then one to finish, then problems on your own. Check your answer before you look at the solution. Answers typed here are not kept when you leave.

  1. 1 · Worked example

    The figure's numbers, by hand

    Logits z=[2, 1, 0.2, −1]z = [2,\ 1,\ 0.2,\ -1] for mat, sofa, roof, moon. The right word is mat. Find the probabilities, the loss, and the gradient with respect to the logits.

    1. Exponentiate. e2=7.389e^{2} = 7.389, e1=2.718e^{1} = 2.718, e0.2=1.221e^{0.2} = 1.221, e−1=0.368e^{-1} = 0.368; the total is 11.69711.697.

    Say the next step to yourself first.
  2. 2 · Finish it

    When the answer is uncertain

    Same logits, but now the target is soft: annotators said mat 90% of the time and sofa 10%, so p=[0.9, 0.1, 0, 0]p = [0.9,\ 0.1,\ 0,\ 0]. The first steps are done. What is the cross-entropy H(p,q)H(p, q), in nats? Give three decimal places.

    1. Share. q=[0.632, 0.232, 0.104, 0.031]q = [0.632,\ 0.232,\ 0.104,\ 0.031], as before.

    2. Surprise. −log⁡q=[0.459, 1.459, 2.259, 3.459]-\log q = [0.459,\ 1.459,\ 2.259,\ 3.459].

    3. Weight. Roof and moon have target weight 00, so they drop out.

    4. Your turn.

  3. 3 · On your own

    The best single move

    Back to the one-hot target (mat) and the logits [2, 1, 0.2, −1][2,\ 1,\ 0.2,\ -1]. You may make one change. Which one lowers the loss the most?

    Choose one

  4. 4 · Finish it

    Both right, not equally good

    Two classifiers see the same two examples, with classes in the order (A, B, C). The labels are A and then B. Model M outputs (1/2, 1/3, 1/6)(1/2,\ 1/3,\ 1/6) and (1/8, 3/4, 1/8)(1/8,\ 3/4,\ 1/8); model N outputs (2/3, 1/6, 1/6)(2/3,\ 1/6,\ 1/6) and (1/4, 1/2, 1/4)(1/4,\ 1/2,\ 1/4). Both put the most probability on the right class both times, so both have accuracy 2/22/2. What is M's mean cross-entropy over the two examples, in nats? Give three decimal places.

    1. Keep only the right labels. M gave them 1/21/2 and 3/43/4; N gave them 2/32/3 and 1/21/2.

    2. Likelihood of the batch. M: 12×34=38\tfrac12 \times \tfrac34 = \tfrac38. N: 23×12=13\tfrac23 \times \tfrac12 = \tfrac13, which is smaller.

    3. Your turn.

  5. 5 · On your own

    Which logit goes up?

    A soft target p=(1/2, 1/4, 1/4)p = (1/2,\ 1/4,\ 1/4) and a model q=(1/2, 3/8, 1/8)q = (1/2,\ 3/8,\ 1/8). With respect to the probabilities, the gradient of H(p,q)H(p,q) is −p/q=(−1, −2/3, −2)-p/q = (-1,\ -2/3,\ -2): every entry negative. With respect to the logits it is q−pq - p. Taking one gradient-descent step on the logits, which logits go up?

    Choose one

  6. 6 · On your own

    The floor for a soft target

    With the soft target p=[0.9, 0.1, 0, 0]p = [0.9,\ 0.1,\ 0,\ 0], you may choose any logits you like. What is the lowest cross-entropy you can approach, in nats? Give three decimal places.

The code

import numpy as np

def softmax(logits):
    shifted = logits - logits.max()
    exp = np.exp(shifted)
    return exp / exp.sum()

def log_softmax(logits):
    shifted = logits - logits.max()
    return shifted - np.log(np.exp(shifted).sum())

def entropy(p):
    p = np.asarray(p, dtype=float)
    mask = p > 0
    return float(-np.sum(p[mask] * np.log(p[mask])))

def cross_entropy_from_logits(p, logits):
    p = np.asarray(p, dtype=float)
    log_q = log_softmax(logits)
    return float(-np.sum(p * log_q))

def finite_difference_grad(loss_fn, logits, eps=1e-6):
    logits = np.asarray(logits, dtype=float)
    out = np.zeros_like(logits)
    for k in range(logits.size):
        plus = logits.copy()
        minus = logits.copy()
        plus[k] += eps
        minus[k] -= eps
        out[k] = (loss_fn(plus) - loss_fn(minus)) / (2 * eps)
    return out

# Shapes: p, logits, q, and grad_logits are all (K,).
p = np.array([0.70, 0.20, 0.08, 0.02])
logits = np.array([1.2, 0.4, -0.3, -1.1])

log_q = log_softmax(logits)
q = softmax(logits)
ce = cross_entropy_from_logits(p, logits)
h = entropy(p)
kl = ce - h
grad_logits = q - p
numeric_grad = finite_difference_grad(lambda z: cross_entropy_from_logits(p, z), logits)

print("q:", np.round(q, 3))
print("H(p,q):", round(ce, 4))
print("H(p):", round(h, 4))
print("KL(p||q):", round(kl, 4))
print("gradient wrt logits:", np.round(grad_logits, 3))
print("finite-difference grad:", np.round(numeric_grad, 3))
print("gradient check:", np.allclose(grad_logits, numeric_grad, atol=1e-6))

# For a one-hot target y=0, the same formula becomes NLL.
y = 0
one_hot = np.eye(4)[y]
print("one-hot CE:", round(cross_entropy_from_logits(one_hot, logits), 4))
print("-log q_y:", round(float(-log_q[y]), 4))

p is a soft target and q the softmax of the logits; these are different numbers from the figure, so that no target weight is zero. The printout shows H(p,q) splitting into H(p) + KL(p||q), and a finite-difference check confirming that the logit gradient is q - p.

Keep it

  1. You add 3 to every logit. What happens to the cross-entropy, and why?

    Answer from memory, then check

    Nothing. Softmax divides eze^{z} by the total, so a shared e3e^{3} cancels. Only the gaps between logits matter.

  2. With a one-hot target and finite logits, can the loss ever reach exactly 0?

    Answer from memory, then check

    No. eze^{z} is positive for every finite logit, so every wrong word keeps a sliver of probability and the right word stays below 1. The loss always rewards a little more confidence.

  3. Which costs more, 90% on a wrong word or 25% on each of four words? Why?

    Answer from memory, then check

    The confident mistake. It leaves the right word at most 10%, a loss of at least −log⁡0.1≈2.30-\log 0.1 \approx 2.30 nats; honest doubt costs log⁡4≈1.39\log 4 \approx 1.39. The loss has no ceiling as the right word's probability falls.

  4. What is the gradient of cross-entropy with respect to the logits, and what does it say about the rivals?

    Answer from memory, then check

    q−pq - p, the model's probabilities minus the target's. For a one-hot target, each rival is pushed down by exactly the probability it holds, and the pushes sum to zero: the right word goes up as much as all the rivals go down together.

  5. Two classifiers are right on every example. Can their cross-entropies differ?

    Answer from memory, then check

    Yes. Cross-entropy scores the probability each gave to the right answer, not only whether that answer came out on top. The one that was more confident where it was right has the lower loss.

  6. For a soft target pp, why can't the cross-entropy reach 0, and what is the gap above its floor called?

    Answer from memory, then check

    The floor is H(p)H(p), the uncertainty the target itself contains, reached only when q=pq = p. The remainder, H(p,q)−H(p)H(p,q) - H(p), is the KL divergence KL(p∥q)\mathrm{KL}(p\|q).

Recalling an answer from memory makes it last longer than rereading it (Roediger and Karpicke, 2006). Add these 6 cards and they come back tomorrow, then after gaps of 3, 7, 16, 35 and 75 days while you still remember them. They stay in this browser only.

The edge

The loss is exact; what it buys is less settled. Next-token cross-entropy falls smoothly, as a power law, as language models grow in size, data and compute (Kaplan et al., 2020). Later fits add a floor the loss approaches but never crosses (Hoffmann et al., 2022), read as the entropy of text itself: the H(p)H(p) of language, which nobody can measure directly. Shannon (1951) could only bound it for English. Whether a smooth fall in loss means a smooth rise in ability is still argued (Schaeffer et al., 2023). And although the loss is minimised by honest probabilities, large networks trained on it are often overconfident (Guo et al., 2017), so how best to keep a model's confidence honest remains an open question.

Next thoughtEven a perfect model cannot push a soft target's loss to zero. So how much of the loss is the model's own fault, and how do you measure just that part?KL Divergence (Relative Entropy) →
The full instrument: soft targets, four presets, and a prediction about which word dominates the loss

Limits of this page

  • Every number here scores one prediction from logits chosen by hand; in training, the logits are learned and the loss is averaged over many examples.
  • This page covers mutually exclusive classes; multi-label problems use a sigmoid per label and a sum of binary cross-entropies instead.
  • The figure uses a one-hot target only; soft targets appear in the mathematics, the practice and the full instrument.
  • Logarithms are natural, so losses are in nats; divide by ln⁡2\ln 2 for bits.
  • The Python runs on your machine, not in the page.

Sources

  1. Goodfellow, Bengio, and Courville (2016). Deep Learning.

    Grounds cross-entropy, KL divergence, and maximum-likelihood loss notation for deep learning.

  2. Shannon (1948). A Mathematical Theory of Communication.

    Bell System Technical Journal 27, 379–423 and 623–656. Defines entropy, H = −Σ p log p, the average surprise that cross-entropy generalizes to a second distribution.

  3. Cover and Thomas (2006). Elements of Information Theory (2nd ed.).

    Wiley. Chapter 2 develops entropy and relative entropy (KL divergence), from which H(p, q) = H(p) + KL(p‖q) follows.

  4. Kaplan et al. (2020). Scaling Laws for Neural Language Models.

    arXiv preprint. Next-token cross-entropy falls as a power law in model size, data and compute.

  5. Hoffmann et al. (2022). Training Compute-Optimal Large Language Models.

    NeurIPS 2022. Fits the loss with an irreducible term E, which the authors relate to the entropy of natural text.

  6. Shannon (1951). Prediction and Entropy of Printed English.

    Bell System Technical Journal 30, 50–64. Estimates upper and lower bounds on the entropy of English from human next-letter predictions.

  7. Schaeffer, Miranda, and Koyejo (2023). Are Emergent Abilities of Large Language Models a Mirage?

    NeurIPS 2023. Argues that sudden jumps in ability can come from the choice of metric rather than from a sudden change in the model.

  8. Guo et al. (2017). On Calibration of Modern Neural Networks.

    ICML 2017. Modern deep classifiers trained with cross-entropy are often overconfident; temperature scaling is a simple fix.

What the claims rest on

Central claim: Cross-entropy is the target-weighted surprise of a model distribution; in deep learning it is the bridge from likelihood to a differentiable training loss.

Each claim below lists the passages it cites and how far it has been checked against them. These are the site’s own checks, not independent replication.

Claim (checked against the cited passages): Cross-entropy measures target-weighted surprise: the target distribution supplies averaging weights, the model distribution supplies scored probabilities, and for one-hot labels it becomes the negative log probability of the correct class.

Sources: Deep Learning

What the sources support: Goodfellow et al. define cross-entropy as H(P,Q)=H(P)+KL(P||Q) and equivalently as expected negative log probability under the target distribution, tying it to maximum-likelihood training losses.

On this page: the note on Deep Learning, Equation 1, Equation 2, Code example 1, the figure

Caveat: This checks categorical cross-entropy as a probabilistic loss, not multi-label sigmoid BCE, calibration, or the correctness of any particular classifier.

Connections

Builds on Maximum Likelihood.

Leads to KL Divergence (Relative Entropy) and Label Smoothing & Soft Targets.

Cite this page

Continuous Function. “Cross-Entropy.” Revised 2026-10-09. https://continuousfunction.ai/domains/probability/cross-entropy/

BibTeX
@misc{cf-cross-entropy,
  title = {Cross-Entropy},
  author = {{Continuous Function}},
  year = {2026},
  note = {Revised 2026-10-09},
  url = {https://continuousfunction.ai/domains/probability/cross-entropy/}
}