Bring the mental model from Maximum Likelihood; this page will reuse it instead of restarting from zero.
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.

Concept Structure
Cross-Entropy
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Cross-EntropyConceptual Bridge
What should feel connected as you move through this page.
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.
The next edge should feel earned: use the demo prediction here before following KL Divergence (Relative Entropy).
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
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 , but you score it using a model distribution .
The phrase "average surprise" is literal. If the target puts mass on an outcome and the model assigns that outcome low probability, the term 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
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let be a discrete label taking values in . Let be the target distribution and let be the model distribution. Assume , , and . All logarithms here are natural logarithms, so the units are nats.
For supervised classification, read this as a per-input statement. For an input , the target distribution is and the model distribution is . The dataset loss averages over examples. The demo below shows one such example.
The cross-entropy from to is
Equivalently,
The direction matters: supplies the averaging weights, while supplies the probabilities being scored. If and is near zero, the penalty becomes very large. If and , the mathematical loss is infinite. If , that class does not contribute directly to this cross-entropy term.
For a one-hot target , where and all other ,
This is exactly the per-example negative log-likelihood used for multiclass classification and next-token language modeling.
The link to KL divergence is
where
When the target distribution is fixed, is constant with respect to the model. Minimizing cross-entropy over is therefore the same optimization problem as minimizing . Maximum likelihood is the empirical version: the data distribution supplies , and the model is trained to reduce the average assigned to observed data.
For one-hot targets, the minimum possible cross-entropy is . For soft targets, the minimum possible cross-entropy is usually not ; it is , achieved when . In that setting, the KL term is the mismatch and is the irreducible target uncertainty.
For neural networks, the model usually produces logits and probabilities
For the soft-target loss
we can derive the logit gradient directly. Since
and ,
Therefore the gradient with respect to each logit is
This compact gradient is one reason cross-entropy is so useful. Classes where get a negative gradient, so gradient descent increases their logits. Classes where get a positive gradient, so gradient descent lowers them.
This is a gradient with respect to logits, not with respect to probabilities. If were treated as an unconstrained probability vector, then . The formula 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
Code
Keep the implementation aligned with the notation so the algorithm is legible.
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
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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 and model distribution . The amber contribution row shows which target-weighted surprises make up . 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.
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.

Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
Grounds cross-entropy, KL divergence, and maximum-likelihood loss notation for deep learning.
Open sourceClaim 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.
Claims without a substantive review badge still need exact source-support review.
goodfellow-2016-deep-learning
Use equation, code, and demo objects to check whether the source support is operational.
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-06Practice 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.
Before touching the demo, predict one visible change that should happen in Cross-Entropy.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
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.Open the draft below to save one note and next action in this browser.
Cross-Entropy
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
This draft stays locally in this browser for concept:probability/cross-entropy.
- 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
- 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
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.
concept/concept-notebook/probability/cross-entropy
concept:probability/cross-entropy