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.

published · difficulty 3/5 · 16 min read

Reading map and next steps

Intuition

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

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

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 −log⁡q(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.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Math

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

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

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 demo below shows one such example.

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

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

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 q−pq-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.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Code

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

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
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.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Interactive Demo

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

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

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 inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: KL Divergence (Relative Entropy)

Choose what to inspect in Cross-Entropy. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

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 while you predict; inputs and target entropy H(p)H(p) also remain visible. Choose a token, then select Reveal surprise to inspect the amber loss contributions and the logit gradients. Before reveal, their marks and solved values are withheld, not zero. The amber contribution row shows which target-weighted surprises make up H(p,q)H(p,q). Contribution heights and gradient lengths use separate relative scales within the current example, not absolute sizes to compare across presets or edits. The gradient row shows the signal backpropagation sends into the logits: negative values mean "raise this logit"; positive values mean "lower this logit."

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Cross-Entropy

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

BeforeMaximum LikelihoodNow4/4 sections readyTryManipulate one control and predict the visible change.NextKL Divergence (Relative Entropy)
Object contextProbability
ConceptLearner lens

Cross-Entropy

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

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
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).

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptCross-EntropyProbability

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.

Demo notes 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 readyDemo notes 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.

Object - ConceptCross-EntropyQuestion

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

concept:probability/cross-entropy
Boundary

sources: goodfellow-2016-deep-learning

Check

Open the closest source note before trusting the local explanation.

Evidence

1 selected-object source shown first; 1 reference total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · book · 2016Deep LearningGoodfellow, Bengio, and Courville
Located CF editorial boundary

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

Used here as

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

Caveat

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

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.

Object - ConceptCross-EntropyQuestion

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

concept:probability/cross-entropy
Boundary

sources: goodfellow-2016-deep-learning

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 1 reference and 3 local witnesses are available for inspection.

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.
Used here as

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.

Local witness
Equation 1
H(p,q)=−∑k=1Kpklog⁡qk.H(p,q)=-\sum_{k=1}^K p_k \log q_k.
Equation 2
H(p,q)=EX∼p[−log⁡qX].H(p,q)=\mathbb E_{X\sim p}[-\log q_X].
Caveat

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

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. 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 · Cross-Entropy

Try the idea in your own words

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.

Concept · Current object

Cross-Entropy

Source boundary: sources: goodfellow-2016-deep-learning

Object context and links

Probability

concept:probability/cross-entropy
Choose a task

Explain the mechanism

For Cross-Entropy: What is the smallest example that makes Cross-Entropy click without losing the math? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Local to this page session. Not saved after leaving or reloading.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer does not erase help history. Outside help cannot be verified here.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    This draft and any AI response do not establish mastery. Try a different case later without help; this page has not measured that learning.

    Grounded object roomClose
    Selected object routeAsk from this object; carry one invariant back.sources: goodfellow-2016-deep-learning
    1. ObjectConceptCross-Entropy
    2. PredictBefore revealCross-Entropy prediction
    3. WitnessCompare codeCross-Entropy code witness 1
    4. RoomAsk groundedChecking local snapshot
    ConceptCross-EntropyProbability
    Code witness comparisonCross-Entropy code witness 1shifted = logits - logits.max()Prediction before revealCross-Entropy predictionManipulate one control and predict the visible change.
    Grounded room questionWhat is the smallest example that makes Cross-Entropy click without losing the math?Checking local snapshot

    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?

    Source boundaryInspect source ids: goodfellow-2016-deep-learningStable content-object key attached
    Role lenses for this object

    These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

    Learner evidence requestAsk what would make "Cross-Entropy" feel predictable rather than familiar.
    Assumption

    Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic.

    Source-checking summary

    Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

    Proposed experiment

    Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

    Next action

    The learner can state the mechanism in their own words

    Evidence4 checks
    PredictionChecking carried observation
    ActionReady for one action
    AILearner handoff ready
    Open source object
    01PredictionChecking browser-local route memory
    02EvidenceChecking for a carried observation
    03BoundaryInspect source ids: goodfellow-2016-deep-learning
    04Next moveSave one next action
    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
    Object-attached 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 Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Cross-Entropy" feel predictable rather than familiar." | assumption: Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: goodfellow-2016-deep-learning" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. 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. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Cross-Entropy" feel predictable rather than familiar. - Assumption to keep visible: Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

    concept/concept-notebook/probability/cross-entropy concept:probability/cross-entropy