Cross-entropy
交叉熵
Understand target-weighted log loss, empirical versus population risk, soft labels, stable computation, and the limits of comparisons.
cross-entropyScore predictions against what actually happens
A toy classifier always predicts the same three-category probabilities. In the target population, categories A, B, and C occur with probabilities . Model M reports that same vector. Model N reports . Both choose A when asked for their most likely category, so their top-choice accuracy is the same: one half. Are their probability forecasts equally good?
Cross-entropy distinguishes them. M receives about 1.039721 nats per observation; N receives about 1.262864. N’s greater confidence in A helps on half the observations, but its smaller probabilities for B and C hurt on the other half. These invented distributions make the tradeoff visible without a dataset or training run.
The averaging weights must come from the target population. If N scored itself using its own probabilities, it would mostly consider the outcomes it already expects. That would measure N’s predictive entropy, about 0.639032 nats, rather than its performance on this population. Confidence alone does not answer the evaluation question.
One distribution supplies events, the other supplies log scores
For probability vectors p and q on the same finite set of K aligned categories, define
Here logarithms are natural, so the unit is nats. Divide by to obtain bits. The target p determines how often an event is scored; q determines the negative log probability assigned to it. The order of the arguments matters. Deep Learning, Section 3.13, equation 3.51
A zero target probability contributes zero, including when the corresponding prediction is zero. If but , the cross-entropy is positive infinity. A model has declared an event impossible even though the target can produce it. On a finite alphabet, positive q throughout the support of p makes the sum finite. These conventions avoid treating 0 * log(0) as an ordinary floating-point multiplication.
Adding and subtracting the target’s log probability gives
The KL divergence is nonnegative, so the lowest cross-entropy over all probability vectors q is , attained at q=p. A nondegenerate soft target therefore does not have zero minimum loss. This is a statement about unrestricted probability vectors; a restricted model family might not represent the minimizer. If p is fixed during optimization, minimizing cross-entropy and minimizing this KL have the same objective up to a constant. If p also changes, that omitted entropy is no longer necessarily constant. Deep Learning, equations 3.50–3.51
For a single observed label y, use the one-hot target . The sum reduces to . A soft target, such as , instead supplies an entire distribution over the mutually exclusive labels. It may represent annotation uncertainty or a teacher model’s output; its interpretation comes from how it was constructed. Multiple simultaneously true labels require a different event model, not an unnormalized categorical target. D2L, Sections 4.1.2.1–4.1.2.2
For input-dependent predictions, the population objective and the observed average are different quantities:
For a fixed model and i.i.d. evaluation observations with finite expected loss, the sample average estimates R and obeys a law of large numbers. Fitting the model on those same observations can make training loss optimistic; the fixed-model argument does not establish its generalization. The product likelihood interpretation additionally uses the specified conditional independence model. In the toy setting, the four labels A,A,B,C have empirical frequencies exactly p, so their average loss equals H(p,q). Another sample will generally give different frequencies.
Keep extreme predictions in log space
If real scores z are converted by softmax to q, substitution yields
The derivative follows because and the derivative of the log normalizer is softmax. It holds for fixed soft targets as well as one-hot targets. Finite logits give strictly positive exact probabilities, though a direct floating-point softmax can round tiny probabilities to zero. D2L, equations 4.1.9–4.1.10
This complete program provides separate probability and logit interfaces. The logit version subtracts the largest score before exponentiation and computes the loss directly from shifted scores. Thus it can report a loss of 2000 for a badly predicted label without first forming an underflowed probability. Vector normalization is checked to absolute tolerance ; this permits ordinary rounding, not arbitrary target weights.
import math
def probability_vector(values):
values = tuple(values)
if not values or any(not math.isfinite(v) or not 0 <= v <= 1 for v in values):
raise ValueError("nonempty finite probabilities in [0,1] required")
if not math.isclose(math.fsum(values), 1., rel_tol=0., abs_tol=1e-12):
raise ValueError("probabilities must sum to one")
return values
def cross_entropy(target, prediction):
p, q = probability_vector(target), probability_vector(prediction)
if len(p) != len(q):
raise ValueError("aligned category vectors required")
if any(pi > 0 and qi == 0 for pi, qi in zip(p, q)):
return math.inf
return math.fsum(-pi*math.log(qi) for pi, qi in zip(p, q) if pi > 0)
def cross_entropy_logits(target, logits):
p, z = probability_vector(target), tuple(logits)
if len(p) != len(z) or any(not math.isfinite(v) for v in z):
raise ValueError("one finite logit per category required")
largest = max(z)
shifted = [v-largest for v in z]
if any(not math.isfinite(v) for v in shifted):
raise ValueError("logit spread exceeds the floating-point range")
log_total = math.log(math.fsum(math.exp(v) for v in shifted))
return math.fsum(pi*(log_total-v) for pi, v in zip(p, shifted) if pi > 0)
p, q = [.5,.25,.25], [.8,.1,.1]
assert math.isclose(cross_entropy(p,p), 1.5*math.log(2))
assert math.isclose(cross_entropy(p,q), .5*math.log(12.5))
assert cross_entropy(p,p) < cross_entropy(p,q)
assert cross_entropy([1,0],[1,0]) == 0
assert cross_entropy([0,1],[1,0]) == math.inf
assert cross_entropy_logits([0,1],[1000.,-1000.]) == 2000.
assert math.isclose(cross_entropy_logits(p,[math.log(v) for v in q]),
cross_entropy(p,q))
print("matched:",cross_entropy(p,p),"mismatched:",cross_entropy(p,q))
For K categories, each function uses O(K) scalar work. This implementation copies vectors and stores shifted logits, so auxiliary storage is O(K). The model forward pass and the dataset loop are separate costs. Nonfinite logits and an unrepresentable score spread are rejected; stabilized algebra does not remove the finite range of machine arithmetic.
Framework interfaces differ. PyTorch’s CrossEntropyLoss expects logits, although its name does not say so; targets may be indices or class probabilities. Passing already-normalized probabilities as logits silently defines another prediction. For soft targets, matching tensor shape does not by itself make the entries a valid probability distribution. Check input conventions and reduction settings before comparing losses. PyTorch, input and target contract
A lower loss needs a common comparison
Changing class weights, excluding padding, smoothing labels, or averaging tokens instead of documents changes the objective or its denominator. Compare the same target definition and evaluation population. A rare but costly error can matter greatly to an application while contributing little to an unweighted population average. Report relevant task metrics alongside log loss.
The discrete nonnegative bound does not transfer directly to densities. With p and q defined relative to the same reference measure, replace the sum by an integral. Using ordinary length as the reference measure, written dx, the continuous analogue is when the integral is defined. A uniform distribution on has density 4, so its entropy and matched cross-entropy are . This negative value is valid. Rescaling the coordinate changes density values and these quantities; comparing densities in seconds with densities in milliseconds without conversion changes the score. KL remains a comparison of probability measures when both distributions are transformed consistently. MIT 6.441, Section 1.3
Keep the weights and units visible
- A one-hot target selects a class assigned probability 1/4. What is its loss? Answer: nats, or 2 bits.
- Can a perfect match to p=(1/2,1/4,1/4) achieve zero categorical cross-entropy? Answer: no. Its minimum is nats.
- What is H((1,0),(1,0)), and what is H((0,1),(1,0))? Answer: zero and positive infinity. Skip zero target terms before taking logarithms.
- For p=(1/2,1/2), what happens if a model evaluates itself with weights q=(0.99,0.01)? Answer: it computes H(q), not H(p,q). The values are about 0.056002 and 2.307610 nats respectively, describing confidence and target-weighted prediction loss.
Connect a training objective to the experiment
Cross-entropy links categorical likelihood, probabilistic prediction, and coding. The coding analogy concerns expected ideal log lengths; actual finite prefix codes need integer lengths and can have overhead. It does not mean a single example literally occupies a fractional number of bits in a file.
Language-model evaluation averages conditional token losses, while distillation can compare a teacher’s soft target with a student’s probabilities. Label smoothing deliberately alters the target rather than discovering its true distribution. Across these uses, identify who supplies p, what q conditions on, which terms are averaged, and whether the evaluated examples were used for fitting. Those choices determine what a reported loss can support.
Make a prediction, then check
The soft target is p=(1/2,1/4,1/4), and q matches p exactly. What is the minimum cross-entropy?
Learning objectives
- Distinguish target-weighted cross-entropy, predictive entropy, and population versus empirical loss.
- Derive one-hot/soft-target log loss and logit gradients, with zero-probability and numerical handling.
- Explain how weighting, normalization, reference measures, and train/evaluation sampling affect loss comparisons.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter 3: Probability and Information Theory
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - Dive into Deep Learning — Softmax Regression
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023 - PyTorch 2.8 — CrossEntropyLoss
PyTorch contributors - MIT 6.441 — Chapter 1: Information Measures: Entropy and Divergence
Yury Polyanskiy; Yihong Wu · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.
- Re-derived target weights, the one-hot reduction, entropy/KL identity, and q−p gradient for fixed targets; checked sampling conditions for population versus empirical loss.
- Enumerated three-category sequences of lengths 1–5, checking each empirical loss against exact rational likelihoods and its target-sampling expectation.
- Used 80-digit Decimal calculations for extreme logits and common shifts, finite differences for soft-target gradients, and a finite simplex grid for the soft-target minimum.
- Compared bilingual arguments, examples, four answered exercises, display equations, and code; checked zero probabilities, invalid inputs, and the continuous negative-entropy example.
- The parent reviewed target weighting, population versus empirical risk, nonzero soft-target minimum, shifted extreme logits, assumptions and framework input conventions, and executed independent gradient and Decimal comparisons.
- The parent executed all 30 new checks and all 55 combined probability/inference tests; bilingual code, display equations, six main anchors, citations and four answered exercises were additionally compared.
Source locations checked:
- Deep Learning — Chapter 3: Probability and Information Theory · Section 3.13, equations 3.49–3.51, printed pp.72–73; target-weighted expectation, entropy plus KL, fixed-target optimization, zero-mass convention.
- Dive into Deep Learning — Softmax Regression · Sections 4.1.2.1–4.1.2.2, equations 4.1.6–4.1.10, and 4.1.3.3: conditional-label independence, NLL, one-hot and soft targets, logits gradient, minimum at target. Read actual web lines 478–523.
- PyTorch 2.8 — CrossEntropyLoss · Pinned PyTorch 2.8 documentation, Input/Target definition and reduction/shape sections, lines 71–126: unnormalized logits, indices or class-probability targets, averaging conventions. Stable link redirected to 2.14, so an explicit 2.8 page was separately read and cited.
- MIT 6.441 — Chapter 1: Information Measures: Entropy and Divergence · Section 1.3, Definition 1.5 and warning, PDF p.11/printed p.18: common reference measure, differential entropy may be negative or undefined. Authors verified on MIT course lecture-notes index.
Related topics