1.3.19 · D2Probability & Statistics

Visual walkthrough — Cross-entropy concept

2,682 words12 min readBack to topic

This page builds cross-entropy from nothing. No probability formula is assumed. We start with the single question "how surprised should I feel?" and walk, one picture at a time, until we reach the loss function that trains almost every classifier.

Two conventions fixed up front, used everywhere below.

  • Which logarithm? Throughout this page means the natural logarithm — the one written , whose base is the number . We pick it because it is the log built into calculus and gradient-based training. With the natural log, surprise is measured in a unit called the nat (short for "natural unit of information"). Had we used base- logarithms instead, the same quantities would come out in bits; the shapes and conclusions are identical, only the number-per-unit changes.
  • Which outcome space? We assume a finite discrete set of possible outcomes — a fixed short list like — so that every "" below is an ordinary finite sum that is guaranteed to make sense. If outcomes were continuous (a real number that could be anything), the sum would become an integral, , and would be probability densities rather than probabilities; every intuition on this page carries over unchanged, we just replace "sum over a list" with "area under a curve."

Everything else is drawn from the two players in the game:

  • a true distribution — what reality actually does,
  • a predicted distribution — what our model guesses reality does.

We will earn every symbol before we use it.


Step 1 — Surprise is a number

WHAT. Before any formula, we agree on one idea: some events shock us, some don't. If I tell you "the sun rose this morning," you shrug. If I tell you "it snowed in the desert," you gasp. Surprise is just how big that gasp is, turned into a number.

Let a probability be written — a number between and telling how likely the model thought an event was. We are going to build a machine that takes in this and hands back a surprise-number. Let us give that machine a name: write for "the surprise you feel when an event the model rated actually happens." Right now is just a blank box — we have not decided its formula yet, only its name. This step is about deciding what rules the box must obey.

WHY. We want to measure how good a prediction is. The only honest measure is: when the truth is revealed, how shocked were we? A great predictor is rarely shocked; a bad one is shocked constantly.

We demand three things of the blank box :

  • If the model was certain it would happen (), surprise must be zero — no shock.
  • If the model thought it was impossible () but it happened, surprise must be enormous.
  • Surprises from two independent events must add: seeing two independent shocks is one shock plus the other.

PICTURE. In the figure below, the horizontal axis is the model's probability (running from on the left to on the right) and the vertical axis is the surprise in nats. The curve is high on the left (rare event = shocking), slides down to touch zero on the right (certain event = no shock) — exactly the shape our three demands force.

Figure — Cross-entropy concept

Step 2 — The logarithm is the only surprise that adds

WHAT. We now fill in the blank box from Step 1 with its forced formula. The surprise of an event the model gave probability is:

WHY the logarithm and not, say, ? Because of the additivity demand (together with the continuity assumption stated in Step 1). Independent probabilities multiply: two independent events with probabilities and happen together with probability . We wanted their surprises to add. The only continuous function turning " inside" into " outside" is the logarithm:

A rule like fails this instantly (), so it cannot be surprise.

WHY the minus sign? A probability is at most , and of a number is . Surprise should be positive, so we flip the sign with . The figure shows climbing to infinity as and touching zero exactly at — the two anchors we demanded in Step 1.

PICTURE.

Figure — Cross-entropy concept

Step 3 — Average surprise over the true distribution

WHAT. One event gives one surprise. But reality throws many events at us over time. We want the average surprise per event across a whole day of forecasts.

Now the second player enters. Reality has its own probabilities: write for how often outcome actually happens, where ranges over our fixed finite list of outcomes. Averaging means: weight each outcome's surprise by how often reality serves it up.

WHY weight by and not ? Because reality — not our model — decides how frequently each outcome shows up. If red truly appears 70% of the time, then 70% of our surprises are red-surprises. We feel the surprise our model assigns, but we feel it as often as reality dictates. That split — feel , weighted by — is the entire heart of cross-entropy.

PICTURE. The bar chart shows outcomes on the x-axis. Each bar's height is the true frequency ; each bar's color intensity is the surprise . Cross-entropy is the total shaded area — frequency times surprise, summed.

Figure — Cross-entropy concept

Step 4 — The best possible score: entropy

WHAT. What is the lowest score you could ever get? It happens when your model is perfect: everywhere. Then cross-entropy becomes surprise measured against the true frequencies:

This is the Shannon Entropy of reality — the irreducible surprise built into the world, again in nats.

WHY does a floor exist? Even a perfect forecaster is surprised sometimes, because reality is genuinely random. If a fair coin is 50/50, no forecast removes the shock of not knowing the next flip. That leftover shock is — the best score physics allows.

PICTURE. Two curves over "how good is the model": cross-entropy is a valley whose lowest point sits exactly at the horizontal line , reached only when .

Figure — Cross-entropy concept

Step 5 — The gap above the floor is KL divergence

WHAT. Cross-entropy is the floor plus a penalty for being wrong. Subtract the floor to isolate the penalty:

Rearranged, the star equation:

  • — fixed; reality's own randomness. Nothing you do changes it.
  • — the KL Divergence; the extra surprise you pay purely for guessing wrong. Zero only when , positive otherwise.

WHY the two forms agree. Writing the divergence with the ratio inside and a leading minus is the same as , because flipping a fraction inside a log flips the sign: . Splitting that log, , and summing gives exactly — which is how the box equation is born.

WHY this matters for training. When you train a model you can only move . Since is a constant, minimizing is exactly minimizing — dragging your guess toward the truth. This is also why minimizing cross-entropy equals Maximum Likelihood Estimation.

PICTURE. A stacked bar: a fixed grey block on the bottom, a shrinking colored block on top. Training melts away the top block; the bottom never moves.

Figure — Cross-entropy concept

Step 6 — The degenerate case: one-hot labels

WHAT. In classification, reality is usually certain: the image is a cat. Then is one-hot — a single at the true class, everywhere else, e.g. .

Plug it into the sum. Every term with dies (zero times anything is zero). Only the true class survives:

WHY it collapses. With a one-hot truth, only one outcome ever happens, so we only ever feel the surprise attached to that one outcome. The whole sum reduces to the single log of the probability our model gave the right answer.

WHY the entropy floor vanishes too. For a one-hot , : certain reality has zero built-in randomness. So here exactly — cross-entropy is the KL divergence.

PICTURE. The bar chart from Step 3, but now all bars except one have height . Only the true-class bar contributes; its shaded area is the whole loss.

Figure — Cross-entropy concept

Step 7 — Edge cases: zeros, certainty, and the asymmetry

WHAT. Three corners must be shown so you never hit an unshown scenario.

  1. Model says impossible, but it happens (): . Loss is unbounded. This is why real code clamps away from (e.g. adds a tiny ).
  2. A truly impossible outcome (): its term , dropping out — even if is tiny. Reality never serves it, so we never feel its surprise. (We define by the limit.)
  3. Asymmetry (): swapping the players asks a different question. weights surprise by reality; weights by the model. Different weights, different number.

WHY show these. A learner who only saw the tidy case will divide by zero in code or wrongly swap and . The infinity in corner 1 is not a bug — it is cross-entropy screaming "you ruled out the truth."

PICTURE. Left panel: the wall rocketing to infinity as . Right panel: two side-by-side bars showing and have different heights for the same pair.

Figure — Cross-entropy concept

The one-picture summary

Everything on one canvas: reality's frequencies (bar heights) meet the model's surprise (curve). Their weighted total is , which splits cleanly into the immovable floor plus the shrinkable gap that training drives to zero.

Figure — Cross-entropy concept
Recall Feynman retelling of the whole walkthrough

Picture a bag of colored balls. Reality decides the mix — say 70% red, 30% blue; that mix is . Before each draw you shout your bet: "80% red!"; that bet is .

When a ball appears, your shock is (natural log) of the chance you gave that color. Guess a color's chance near zero and it shows up? You gasp huge. Guess it near one and it shows up? You barely blink. We use because two separate shocks should just add up, and only turns "chances multiply" into "shocks add."

Play all day and average your shock, but weigh each color by how often the bag (reality ) actually gives it. That weighted-average shock is cross-entropy , and its unit is the nat.

The lowest score you could ever hit is when your bets exactly match the bag — but even then you're surprised a little, because the bag is genuinely random. That leftover shock is the entropy , a floor you can't dig under. Whatever surprise you pay above that floor is pure waste from betting wrong — that's the KL divergence. Since the floor never moves, "get better at guessing" literally means "melt the KL waste to zero," which is exactly what training a classifier does.


Quick self-check

Below, "" is the natural log; work each one by hand so the numbers are never magic.

Coin: reality heads, model heads. Compute .
nats.
Its entropy floor .
nats.
The wasted bits .
nats.
Why does one-hot collapse the sum?
Every term dies, leaving only .
Why is (not ) the surprise rule?
Only makes independent surprises add.