Math for ML, by Hand · part 4 of 4

Why Is Your Loss Function an Expected Value?

Math for ML, by Hand (part 4 of 4): probability, conditioning, expected value, the law of large numbers, entropy, cross-entropy and KL divergence.

Four columns listing twenty topics across four parts; Part 4 is highlighted. Frame 1.
You are in Part 4: reading the output

The number 0.693 has appeared in every part of this series. It was the loss of each user in part 1's model, the starting height of the loss surface in part 3 (twice over), and it will show up here as a cross-entropy. That is not a coincidence. It is ln 2, the cost of a model that answers every question with a coin flip.

This part explains what the model's output p means, why the loss is an average, why averaging over a random minibatch is good enough, and why the log-loss is the same thing as cross-entropy.

The tiny model

One last look at the cast: both users get p = 0.5, and the log-loss is −ln p for the user who clicked and −ln(1 − p) for the user who did not. Read p as P(click | x), the probability of a click given what we know about the user. That reading needs the language of probability.

What a probability promises

A probability is a statement about the long run, not a promise about a single trial.

Bar chart of the number of heads in 10 fair tosses; exactly 5 has probability 0.246. Frame 1.
Toss a fair coin 10 times. How many heads?
Bar chart of the number of heads in 10 fair tosses; exactly 5 has probability 0.246. Frame 2.
Tempting: exactly 5. It is the most likely count, but P(5) = 252/1024 = 0.246
Bar chart of the number of heads in 10 fair tosses; exactly 5 has probability 0.246. Frame 3.
Probability is about the long run: over many sets of 10, the counts spread around 5

Toss a fair coin 10 times. The tempting prediction is exactly 5 heads, and 5 is indeed the single most likely count. Its probability is only 252/1024 = 0.246: of the 1,024 equally likely sequences of heads and tails, 252 have five heads. About three runs in four give some other count.

What P(heads) = 0.5 promises is about many repetitions: over a very large number of tosses, the fraction of heads gets as close to 0.5 as you like. Section 19 makes that precise.

Formally, a probability assigns a number between 0 and 1 to events, which are subsets of the sample space Ω (all possible outcomes). Two rules do the work: the whole space has probability 1, and probabilities of events that cannot happen together add.

By hand
sequences of 10 tosses:        2¹⁰ = 1,024
sequences with exactly 5 heads: C(10, 5) = 252   (brute-force count: 252)
P(exactly 5) = 252 / 1024 = 0.246

Why ML cares. The model's output p = 0.5 is a probability in exactly this sense: among many users who look like x, it predicts half will click. Calibration checks whether that holds on real data.

What it cannot do. One probability on its own ignores what we have observed. Models condition on evidence.

Conditioning and Bayes' theorem

Conditioning on B throws away every outcome outside B and rescales what is left.

A grid of 1,000 dots with 200 spam. Keeping the 160 emails that contain deal leaves 120 spam, so the probability of spam given deal is 0.75; the reverse probability is 0.6. Frame 1.
1,000 emails. 200 of them are spam (orange)
A grid of 1,000 dots with 200 spam. Keeping the 160 emails that contain deal leaves 120 spam, so the probability of spam given deal is 0.75; the reverse probability is 0.6. Frame 2.
Keep only emails containing "deal": 160 remain
A grid of 1,000 dots with 200 spam. Keeping the 160 emails that contain deal leaves 120 spam, so the probability of spam given deal is 0.75; the reverse probability is 0.6. Frame 3.
Of those 160, 120 are spam: P(spam | deal) = 120/160 = 0.75
A grid of 1,000 dots with 200 spam. Keeping the 160 emails that contain deal leaves 120 spam, so the probability of spam given deal is 0.75; the reverse probability is 0.6. Frame 4.
Tempting: swap the bar. P(deal | spam) = 120/200 = 0.6 is a different question

Picture 1,000 emails. 200 are spam. The word "deal" appears in 120 spam emails and in 40 of the 800 legitimate ones. What is the chance an email is spam, given that it contains "deal"?

Keep only the emails that contain the word. 160 remain, and 120 of them are spam: P(spam | deal) = 120/160 = 0.75. That is the whole of conditioning: shrink the world to the evidence, then count.

The tempting slip is to swap the two sides. P(deal | spam) = 120/200 = 0.6 answers a different question, about a different world (only the spam emails). Bayes' theorem converts one into the other using the base rate: 0.6·0.2 / (0.6·0.2 + 0.05·0.8) = 0.75. Stating the problem as counts of emails rather than percentages, as here, is the format Gigerenzer and Hoffrage found makes these answers far easier to get right.

By hand
P(spam) = 200/1000 = 0.2
P(deal | spam) = 120/200 = 0.6        P(deal | ham) = 40/800 = 0.05
P(spam | deal) = 120 / (120 + 40) = 0.75
Bayes:  0.6·0.2 / (0.6·0.2 + 0.05·0.8) = 0.12 / 0.16 = 0.75   ✓

Why ML cares. A classifier's output is a conditional probability, P(click | x). Naive Bayes spam filters use this exact calculation, one word at a time.

What it cannot do. A probability describes one outcome. To score a model we need a single summary of many outcomes and their payoffs.

Expected value and the law of large numbers

The expected value is the long-run average, and the law of large numbers is the guarantee that the average gets there.

Six die faces with payouts; the expected value is −33.33 dollars; the running average over 10,000 simulated rounds settles near it. Frame 1.
A die game: roll 1 or 2, win $300; roll 3 to 6, lose $200
Six die faces with payouts; the expected value is −33.33 dollars; the running average over 10,000 simulated rounds settles near it. Frame 2.
Weight each payout by its probability: 300·⅓ − 200·⅔ = −100/3 ≈ −33.33
Six die faces with payouts; the expected value is −33.33 dollars; the running average over 10,000 simulated rounds settles near it. Frame 3.
Play 10,000 rounds: the running average settles near −33.33 (seed 7)
Six die faces with payouts; the expected value is −33.33 dollars; the running average over 10,000 simulated rounds settles near it. Frame 4.
Tempting: after three losses you are 'due' a win. After 3 losses the win rate was 0.351, about ⅓

A die game: roll 1 or 2 and win $300, roll 3 to 6 and lose $200. Weight each payout by its probability: 300 · 2/6 − 200 · 4/6 = −100/3, about −33.33 per round. The game loses money on average, so you should not play it.

Simulate 10,000 rounds. The running average is −50 after 10 rounds, −55 after 100, −40 after 1,000 and −31 after 10,000, closing in on −33.33. The strong law of large numbers says this happens with probability 1 for independent repeats.

The law is often misread. A player on a losing streak may feel "due" a win. In the simulation, the rounds that came right after three losses in a row (2,853 of them) were won at a rate of 0.351, about the usual 1/3. The average converges because later rounds swamp the early ones, not because the dice correct themselves.

By hand
E[X] = 300·(2/6) + (−200)·(4/6) = 100 − 133.33 = −100/3 ≈ −33.33
running mean (seed 7):  10 → −50,  100 → −55,  1,000 → −40,  10,000 → −31
win rate right after 3 losses: 0.351  (vs 1/3)

Why ML cares. The training loss is an expected value: the average log-loss over the distribution of users. We never see that distribution, only a sample, so the next section asks whether a sample is good enough.

What it cannot do. The expected value gives one average. Training averages gradients over small random batches, and we need to know how noisy that is.

Why minibatches work

A minibatch gradient is a sample average, so it is a fair, noisy estimate of the full gradient.

Histograms of minibatch average gradients for batch sizes 8, 64 and 512 around the full average −0.50; the spread shrinks from 0.355 to 0.044. Frame 1.
Each training example has its own gradient; the full-data gradient is their average
Histograms of minibatch average gradients for batch sizes 8, 64 and 512 around the full average −0.50; the spread shrinks from 0.355 to 0.044. Frame 2.
Stochastic gradient descent averages a random minibatch instead
Histograms of minibatch average gradients for batch sizes 8, 64 and 512 around the full average −0.50; the spread shrinks from 0.355 to 0.044. Frame 3.
Bigger batches, tighter averages: spread 0.355 → 0.124 → 0.044

Our two-user loss is a sum of one term per user, and so is its gradient. On real data there are millions of terms. Stochastic gradient descent averages a random batch of them instead.

Take a toy set of 100,000 per-example gradients with average −0.50. Draw 2,000 random batches of each size and look at the batch averages. All three sizes centre on the full average. Their spread shrinks as the batch grows: 0.355 for batches of 8, 0.124 for 64, 0.044 for 512. Each 8-fold increase cuts the spread to about a third, because the spread of an average falls like 1/√m.

By hand
batch size   spread of the batch average   (full average −0.50)
8            0.355
64           0.124
512          0.044
8× batch  →  spread × 1/√8 ≈ 0.35

Why ML cares. This is why batch size and learning rate are tuned together: a larger batch gives a less noisy gradient and tolerates a larger step.

What it cannot do. Averages tell us how wrong we are on average, but not how to score a predicted distribution against the truth. That is information theory's job.

Entropy counts yes/no questions

Entropy is the average number of yes/no questions a distribution leaves you to ask.

Binary search over 1,024 numbers takes 10 questions; bar charts of a uniform, a peaked and a certain distribution with entropies 2, 1.36 and 0 bits. Frame 1.
Guess a number from 1 to 1,024 with yes/no questions: halve each time, 10 questions
Binary search over 1,024 numbers takes 10 questions; bar charts of a uniform, a peaked and a certain distribution with entropies 2, 1.36 and 0 bits. Frame 2.
Uniform over 4 classes: 2 bits, the most uncertain
Binary search over 1,024 numbers takes 10 questions; bar charts of a uniform, a peaked and a certain distribution with entropies 2, 1.36 and 0 bits. Frame 3.
Peaked (0.7, 0.1, 0.1, 0.1): 1.36 bits. Fewer questions on average
Binary search over 1,024 numbers takes 10 questions; bar charts of a uniform, a peaked and a certain distribution with entropies 2, 1.36 and 0 bits. Frame 4.
Certain (1, 0, 0, 0): 0 bits. Nothing left to ask

I pick a number from 1 to 1,024 and you ask yes/no questions. Halve the range each time and you need log₂ 1024 = 10 questions. That count is the entropy of the uniform distribution: 10 bits.

If I pick unevenly, you can do better on average by asking about the likely answers first. With four classes, a uniform distribution has entropy 2 bits. A peaked one, (0.7, 0.1, 0.1, 0.1), has 1.36 bits; the best question tree for it needs 1.50 questions on average, and no tree can beat the entropy. A certain distribution, (1, 0, 0, 0), has entropy 0: there is nothing to ask.

The uniform distribution has the most entropy, the most uncertainty. A distribution concentrated on one value has none.

By hand
uniform (¼, ¼, ¼, ¼):    −4 · ¼ · log₂ ¼ = 2 bits
peaked (0.7, 0.1, 0.1, 0.1):  −(0.7 log₂ 0.7 + 3 · 0.1 log₂ 0.1) = 1.36 bits
certain (1, 0, 0, 0):     0 bits
binary search over 1,024: 10 questions, the worst case over all 1,024 targets

Why ML cares. The predicted distribution of a classifier has an entropy. Low entropy means a confident prediction, which is useful for active learning and for flagging uncertain inputs.

What it cannot do. Entropy describes one distribution. Training compares two: the truth and the model's prediction.

Cross-entropy and KL divergence

Cross-entropy is the cost of describing the truth P with the model Q; KL is the part of it caused by Q being wrong.

Bar charts of truth and prediction. With a one-hot truth the cross-entropy is 0.693. With P = (0.2, 0.8) it is 0.500 entropy plus 0.193 KL divergence, total 0.693. Frame 1.
Our model: truth 'clicked' (one-hot), prediction (0.5, 0.5). Cross-entropy = −ln 0.5 = 0.693, our loss
Bar charts of truth and prediction. With a one-hot truth the cross-entropy is 0.693. With P = (0.2, 0.8) it is 0.500 entropy plus 0.193 KL divergence, total 0.693. Frame 2.
A softer truth P = (0.2, 0.8) against Q = (0.5, 0.5)
Bar charts of truth and prediction. With a one-hot truth the cross-entropy is 0.693. With P = (0.2, 0.8) it is 0.500 entropy plus 0.193 KL divergence, total 0.693. Frame 3.
Cross-entropy splits: H(P) 0.500 + KL(P‖Q) 0.193 = 0.693
Bar charts of truth and prediction. With a one-hot truth the cross-entropy is 0.693. With P = (0.2, 0.8) it is 0.500 entropy plus 0.193 KL divergence, total 0.693. Frame 4.
Tempting: KL is a distance. But KL(Q‖P) = 0.223 ≠ 0.193

For the user who clicked, the truth is one-hot: probability 1 on "clicked". The model says (0.5, 0.5). The cross-entropy is −1 · ln 0.5 = 0.693, which is the log-loss from part 1. Log-loss and cross-entropy are the same formula; this is where the 0.693 comes from.

Cross-entropy splits in two. Take a softer truth, P = (0.2, 0.8), against Q = (0.5, 0.5). H(P) = 0.500 is the uncertainty already in the truth. KL(P‖Q) = 0.193 is the extra cost of using Q instead of P. Together they make CE = 0.693.

Two consequences. First, a perfect prediction gives cross-entropy H(P), not zero; it reaches zero only when the truth is one-hot, as with ordinary labels. Second, KL is not a distance: KL(Q‖P) = 0.223, not 0.193. It is zero only when the two distributions are equal.

By hand
one-hot truth (0, 1), model (0.5, 0.5):  CE = −ln 0.5 = 0.693  = the log-loss
P = (0.2, 0.8), Q = (0.5, 0.5):
  H(P)     = −(0.2 ln 0.2 + 0.8 ln 0.8) = 0.500
  KL(P‖Q)  = 0.2 ln(0.2/0.5) + 0.8 ln(0.8/0.5) = 0.193
  CE       = 0.500 + 0.193 = 0.693   ✓
  KL(Q‖P)  = 0.223  ≠ 0.193

Why ML cares. Classification losses, label smoothing (a softer P), knowledge distillation (matching a teacher's Q) and the KL term in a variational autoencoder are all this formula.

What it cannot do. Nothing left to bridge. The closing figure maps every box of the tiny model to the part that explains it.

Where this leaves us

The five-box model with forward values, backward gradients and the part of the series that explains each box. Frame 1.
Every box, every number, and the part of the series that explains it

Every box in the tiny model now has a name. The input is a vector (part 1), h = Ax is a linear map (part 2), the score is an inner product, the weights move by gradient descent at a step set by curvature (part 3), and the loss is a cross-entropy averaged over data (part 4).

That is the whole roadmap, worked on one model small enough to check by hand. The same pieces, at much larger sizes, are what a modern network is made of.

Back to the series home