Probability

Cross-Entropy

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.

status: publishedimportance: criticaldifficulty 3/5math: undergraduateread: 16mlive demo
Editorial probability illustration comparing two categorical distributions with mismatch ribbons.

Concept Structure

Cross-Entropy

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

1prerequisites
2next concepts
2related links

Learning map

Cross-Entropy
BeforeMaximum LikelihoodNow4/4 sections readyTryManipulate one control and predict the visible change.NextKL Divergence (Relative Entropy)

Object flow

4/4 sections readyAsk about thisResearch room
ConceptCross-EntropyProbability
1 source attachedLocal snapshot ready
concept:probability/cross-entropy

Conceptual Bridge

What should feel connected as you move through this page.

Carry inMaximum Likelihood

Bring the mental model from Maximum Likelihood; this page will reuse it instead of restarting from zero.

Work hereCross-Entropy

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.

Carry outKL Divergence (Relative Entropy)

The next edge should feel earned: use the demo prediction here before following KL Divergence (Relative Entropy).

Test the linkManipulate one control and predict the visible change.Then continue to KL Divergence (Relative Entropy)
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

A classifier gives many probabilities, but the training example usually gives one complaint: the right answer was not probable enough. How should that complaint become a number the optimizer can lower?

Cross-entropy is the standard answer. It measures the average surprise you feel when data is drawn from a target distribution pp, but you score it using a model distribution qq.

The phrase "average surprise" is literal. If the target puts mass on an outcome and the model assigns that outcome low probability, the term logq(x)-\log q(x) becomes large. If the target says an outcome never matters, that outcome contributes nothing to the loss for this example.

For one-hot labels, cross-entropy is just the negative log probability of the correct class. For soft labels, label smoothing, or distillation targets, it becomes a weighted average over all classes. That is why it sits between maximum likelihood, KL divergence, and gradient descent: it turns probabilistic fit into a scalar loss whose gradient says which logits should move.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

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 pk0p_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=kxi)p^{(i)}_k=P_{\mathrm{target}}(Y=k\mid x_i) and the model distribution is qk(i)=Pθ(Y=kxi)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 demo below shows one such example.

The cross-entropy from pp to qq is

H(p,q)=k=1Kpklogqk.H(p,q)=-\sum_{k=1}^K p_k \log q_k.

Equivalently,

H(p,q)=EXp[logqX].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)=logqy.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(pq),H(p,q)=H(p)+\mathrm{KL}(p\|q),

where

H(p)=kpklogpk,KL(pq)=kpklogpkqk.H(p)=-\sum_k p_k\log p_k,\qquad \mathrm{KL}(p\|q)=\sum_k p_k\log\frac{p_k}{q_k}.

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(pqθ)\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 logqθ(x)-\log q_\theta(x) assigned to observed data.

For one-hot targets, the minimum possible cross-entropy is 00. For soft targets, the minimum possible cross-entropy is usually not 00; it is H(p)H(p), achieved when q=pq=p. 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 zRKz\in\mathbb R^K and probabilities

qk=softmax(z)k=ezkjezj.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)=zilogjezj,\log(\mathrm{softmax}(z)_i)=z_i-\log\sum_j e^{z_j},

and ipi=1\sum_i p_i=1,

(z,p)=ipizi+logjezj.\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=qkpk.\frac{\partial \ell}{\partial z_k}=q_k-p_k.

This compact gradient is one reason cross-entropy is so useful. 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 logits, not with respect to probabilities. If qq were treated as an unconstrained probability vector, then H(p,q)/qk=pk/qk\partial H(p,q)/\partial q_k=-p_k/q_k. The formula qpq-p appears after the loss is differentiated through the softmax. Its components sum to zero, reflecting that softmax logits redistribute probability mass across classes.

This page is about categorical cross-entropy for mutually exclusive classes. Multi-label problems usually use sigmoid outputs and a sum of binary cross-entropies instead.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
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))

The code mirrors the math: p is the target distribution, q is the softmax model distribution, H(p,q) decomposes into H(p) + KL(p||q), and the finite-difference check confirms that the logit gradient is q - p.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the presets to compare a matched soft target, a diffuse one-hot model, an overconfident wrong model, and a soft-target mismatch. Then move the logit sliders.

The paired bars show the target distribution pp and model distribution qq. The amber contribution row shows which target-weighted surprises make up H(p,q)H(p,q). Those contribution bars are relative within the current example. The gradient row shows the signal backpropagation sends into the logits: negative values mean "raise this logit"; positive values mean "lower this logit."

Live Concept Demo

Explore Cross-Entropy

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Cross-Entropy should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

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.

Prediction open01 / Intuition
Editorial probability illustration comparing two categorical distributions with mismatch ribbons.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Cross-Entropy should make visible.

Visual Inquiry

Make the image answer a mathematical question

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.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Cross-Entropy easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

book · 2016Deep LearningGoodfellow, Bengio, and Courville

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

Open source

Claim Review

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.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources1 reference

goodfellow-2016-deep-learning

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedCross-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.Claim metadata: source checked

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.

Sources: Deep LearningThis checks categorical cross-entropy as a probabilistic loss, not multi-label sigmoid BCE, calibration, or the correctness of any particular classifier.A bounded review summary is present; still check caveats and exact source scope.

Checked Goodfellow et al. chapters 3.13 and 5.5: chapter 3 defines entropy as an expectation under P and KL(P||Q) as an expectation under P of log P minus log Q. Chapter 5 derives MLE as minimizing -E_data log p_model, says minimizing KL from empirical data to the model is exactly minimizing cross-entropy, and names softmax negative log-likelihood as cross-entropy.

Reviewer: codex+oracle; reviewed 2026-05-06

Practice Loop

Try the idea before it explains itself

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.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Cross-Entropy.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptCross-EntropyProbability

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptProbability

Cross-Entropy

Anchored question

What is the smallest example that makes Cross-Entropy click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:probability/cross-entropy.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: goodfellow-2016-deep-learning
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Cross-Entropy Object key: concept:probability/cross-entropy Context: Probability Anchor id: concept/concept-notebook/probability/cross-entropy Open question: What is the smallest example that makes Cross-Entropy click without losing the math? Evidence to inspect: - Source ids to inspect: goodfellow-2016-deep-learning - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/probability/cross-entropy concept:probability/cross-entropy