Statistics Intuition — A Feel for Numbers
"Every number on a dashboard is answering some question. The skill is knowing which question — and whether it's the one you asked."
01 · The hookSix Numbers Walk Into a Meeting
A feel for numbers, before any formula. What an average hides, why the middle is usually more honest than the mean, and why a test that is 99% accurate can still be wrong most of the time it fires.
"Monday's metrics review had six tiles on the screen, and we made six decisions. Tile 1: average support first-reply time is 28 minutes — we promised 10, so we pulled two engineers onto support duty.
Tile 2: prompt v2 scored five points higher than v1 on the eval — we shipped v2. Tile 3: the fraud filter is 99.2% accurate — we cut the manual-review team. Tile 4: a flagged payment means fraud — we started auto-freezing on every flag.
Tile 5: the churn model gives these 400 accounts a 90% risk — we sent all 400 an expensive win-back discount. Tile 6: customers who use the new dashboard churn half as much — we made the dashboard mandatory.
By Friday, all six decisions had gone wrong. And here is the uncomfortable part: nobody lied. Every one of those numbers was computed correctly."
Here are the six tiles as the room saw them, with the decision each one triggered. Every section of this chapter comes back to one of these tiles: which number, which decision, and what it cost.
- Tile 1, the average. Ten tickets, nine answered in 3 to 6 minutes and one that sat overnight for 241 minutes. The mean of those ten is 28. The decision, two engineers moved to support, was made for a customer who does not exist. Section 03 shows which summary should have been on the tile.
- Tile 2, the eval win. Two prompts, one run each on 20 examples, five points apart. The same prompt scored twice can differ by ten. Section 04 gives that wobble a name and a size.
- Tile 3, the accuracy. Fraud is 8 payments in 1,000, so a filter that never fires is also 99.2% accurate. The review team was cut on a number that a do-nothing model can match. Section 06 replaces it with four boxes.
- Tile 4, the alarm. The filter catches 85% of fraud, which the room heard as "a flag is 85% likely to be fraud". Counting payments in section 07 gives 26%: three frozen cards in four belonged to honest customers.
- Tile 5, the confidence. A model's 90% is a promise that nine in ten will churn. Section 08 checks the promise and finds the model's 90% is really about 73%, so roughly 100 of the 400 discounts were spent on customers who were staying.
- Tile 6, the cause. Dashboard users really do churn less. Section 09 shows a third thing, engagement, driving both the dashboard use and the staying, so mandating the dashboard changes nothing.
Six correct numbers, six wrong decisions. That is the puzzle this chapter exists to solve.
Each tile failed for a different reason, and each reason is one core statistical idea — the six ideas an AI engineer leans on daily, whether they are reading an eval score, a latency chart, a fraud metric, or a churn prediction.
This chapter walks through the six lies one at a time.
For each one you will see the everyday version first (support tickets, weather forecasts, ice cream), then the exact same trap wearing work clothes (evals, fraud models, churn scores), and then the short piece of code that catches it.
By the end, the six tiles become six reflexes — six questions you ask automatically before believing any number.
You have been doing statistics for years without the vocabulary. A flaky test that passes on re-run? That is sampling noise — the same code producing different measurements. The reason your team alerts on p95 latency instead of average latency?
That is a heavy-tailed distribution. Tuning an alert threshold so it catches real incidents without paging you at 3 a.m. for nothing? That is the precision–recall trade-off. Retry with jitter? Deliberate randomness.
This chapter is not new machinery — it is names, sharp edges, and a decision guide for machinery you already operate.
02 · The big ideaEvery Measurement Is Truth Plus Luck
Monday's six tiles are still on the screen, and by Friday every decision under them had gone wrong: two engineers moved to support, a prompt shipped, a review team cut, cards frozen, 400 discounts sent, a dashboard made mandatory. The SaaSify data team now has to explain how six correctly computed numbers produced six bad calls. Before taking the tiles one at a time, we need the single idea all six failures share: every measured number is the truth plus some luck. This section names that idea. The six lies that follow are six different ways of failing to separate the two.
Here is the one sentence the whole subject hangs on: every number you measure is the true thing you care about, plus some amount of luck — and statistics is the craft of telling the two apart. "Luck" here is not mysticism.
It is the ordinary fact that you measured these ten tickets and not ten others, this week of traffic and not next week's, these 20 eval examples and not a different 20.
Change the accident of which data you happened to catch, and the number changes — even when the underlying truth has not moved at all.
- The truth. The dashed line at 75% is the prompt's real quality, the number you would get with unlimited examples. Nothing about the prompt changes between the six runs, so this line never moves.
- The luck. Each dashed segment is the gap between the truth and one measured score. Run 2 happened to draw 20 harder examples and scored 60, fifteen points under the truth. Run 3 drew easier ones and scored 85. Change which 20 examples you happen to catch and the number changes.
- The spread. From one prompt, six honest scores between 60 and 85. Tile 2 compared two prompts, one run each, five points apart. Against a spread this wide, five points is inside the luck.
Once you see numbers this way, the six lies become six specific failures to separate truth from luck. The average lied because one extreme value polluted it. The eval win lied because the luck part was bigger than the difference being claimed.
The accuracy lied because it answered an easier question than the one being asked. The alarm lied because rare things stay rare even after an alarm fires. The 90% lied because the model's confidence was not attached to reality.
And the dashboard lied because two numbers moved together without either causing the other. Different failures — one root skill.
Ask which question the number answers.
Ask how much it wobbles.
Count the base rate before you believe the alarm.
Check the promise before you trust the 90%.
Hunt the third thing before you call it a cause.
Which question: the mean and the median in Fig. 1b.1b answer different questions about the same ten tickets. Wobbles: the ±10 bars in Fig. 1b.1c that swallow a 5-point gap. Base rate: the 1,000 dots in Fig. 1b.4b, where 20 false alarms outnumber 7 real catches. The promise: the buckets in Fig. 1b.5b, where "88%" happened 73% of the time. The third thing: the top of the triangle in Fig. 1b.6b, driving both numbers at once.
Now the same six lies a second time, concretely. Each row names the tile as the Monday meeting saw it, the script in this chapter that catches it, and the number that should have been on the screen instead. If a lie feels abstract when you reach it, come back to its row here.
| Tile | In the naive version (what the dashboard showed) | In the production version (this chapter's tool) | What flows out |
|---|---|---|---|
| 1 · The average | "average first-reply time: 28 min", a bare np.mean | middles.py: mean, median and p90 printed side by side | A typical-customer number and a worst-case number, read together |
| 2 · The eval win | "v2 scored five points higher", one run of each prompt | Module 01's eval_variance.py, re-run: the wobble of a 20-example score | A verdict: the gap is inside the noise, or bigger than it |
| 3 · The accuracy | "99.2% accurate", one number for the whole model | four_boxes.py: the do-nothing dummy first, then TP, FP, FN, TN, precision and recall | Two numbers: can the alarms be trusted, and how much fraud is caught |
| 4 · The alarm | "a flag means fraud", so freeze on every flag | The frequency tree in Fig. 1b.4, then Bayes' rule with the base rate, recall and false-alarm rate | P(fraud | flag) = 26%, the number the analyst actually faces |
| 5 · The 90% | "90% churn risk", taken at face value for 400 accounts | calibration_check.py: reliability buckets and a Brier score | Honest probabilities, or a repair job before they touch money |
| 6 · The cause | "dashboard users churn half as much", so make it mandatory | correlation_trap.py: correlate, control for the third thing, then randomize | A candidate cause and the experiment that would settle it |
| The decision | Gut feel, one tile at a time | expected_value.py: probability × cost, swept across pessimistic and optimistic assumptions | A dollar figure that survives being wrong about the inputs |
Reading a clear explanation feels like learning, but the feeling is misleading: recognizing an idea on the page and retrieving it from memory a day later are different muscles, and reading only trains the first one. This is true for every reader, not a personal flaw.
So this chapter is built for the second muscle. Every concept ends with a 📌 Pin this box — a single sentence worth keeping. Every few sections there is a 30-second recall box that asks you to answer from memory before opening the reveal.
Do them honestly — say the answer out loud or write it down, then check. Getting it wrong and correcting yourself is the single most effective thing that can happen; it beats ten smooth re-reads.
Then come back to the cheat sheet tomorrow, and again in a week. That schedule, not willpower, is what makes the ideas stick.
One housekeeping table before we start. This chapter uses only a handful of symbols, and every one of them is listed here with its spoken name. You do not need to memorize this — glance back whenever a squiggle interrupts your reading.
| Symbol | How to say it | What it means in plain words |
|---|---|---|
| x̄ | "x-bar" | The average of the values you measured. The stroke on top always means "average of". |
| μ | "mu" | The true average you would get with unlimited data — the thing x̄ (x-bar) is estimating. |
| σ, s | "sigma", "s" | The standard deviation — the typical distance of one value from the average. σ (sigma) is the true one; s is your data's estimate of it. |
| σ², s² | "sigma-squared" | The variance — the standard deviation multiplied by itself. Same information, in squared units. |
| n | "n" | How many measurements you have. Almost every trap in this chapter shrinks as n grows. |
| P(A) | "probability of A" | How often A happens, as a number from 0 (never) to 1 (always). |
| P(A|B) | "probability of A given B" | How often A happens among only the cases where B is true. The vertical bar | reads "given", and it is the most important punctuation mark in this chapter. |
| r | "r" (correlation) | How tightly two quantities move together, from −1 (perfect see-saw) through 0 (unrelated) to +1 (perfect lockstep). |
| E[X] | "expected value of X" | The long-run average of an uncertain quantity: each possible outcome multiplied by its probability, then added up. |
| Σ | "sigma" (capital) — "sum of" | Add up everything that follows. A for-loop written in Greek. |
| √ | "square root" | Appears wherever noise gets averaged down — the reason 4× the data buys only 2× the precision. |
| ≈ | "approximately equal to" | Close enough for the decision at hand. |
03 · Lie 1"The Average Reply Time Is 28 Minutes"
Tile 1 said the average first-reply time was 28 minutes against a promise of 10, and two engineers were pulled onto support duty on the strength of it. The team needs to know what those ten tickets actually looked like, and whether 28 describes any of them. This section takes the word "average" apart. The mean, the median and the percentile answer three different questions, and the dashboard picked the wrong one for the question the room was asking.
Start with the everyday version. Your team answered ten support tickets today. Nine were answered in three to six minutes. One ticket arrived just before everyone went home and sat until morning — 241 minutes.
Now compute the average: add all ten numbers, divide by ten, and you get 28 minutes. The dashboard dutifully reports "average first-reply time: 28 minutes", management panics, and two engineers get pulled onto support duty.
But walk through what actually happened to the customers: nine out of ten got an answer within six minutes — excellent service — and one person had a genuinely bad experience. "28 minutes" describes nobody. Not one of the ten customers experienced anything like 28 minutes.
The problem is that the word "average" quietly chose one specific summary — the mean, which is the total shared out equally — and the mean has a known weakness: every value pulls on it in proportion to its size, so one extreme value can drag it far from anything typical.
There are two other ways to summarize the middle of a pile of numbers, and each answers a different question. The median is the value in the middle when you sort the pile — half the values sit below it, half above.
It answers "what is typical?", and it barely notices extreme values, because they are just one entry at the end of the sorted list.
The mode is simply the most common value — useful mostly for categories ("the most common support topic is billing"), and you will rarely compute it for measurements. The skill is not knowing the definitions.
The skill is hearing the word "average" and immediately asking: which question is this number answering — "shared out equally" or "typical"?
"My dashboard already shows the average. It is computed correctly, from all the data. How is a correct number a lie?"
— a platform engineer with a Grafana board full of means
The number is not the lie. The caption is. "Average reply time" is read by every human in the room as "what a customer typically waits", and the mean does not answer that question. It answers "total waiting time, shared out equally across tickets". Those two questions have the same answer only when the data has no long tail, and Fig. 1b.1 just below shows what one does: the median (marker 1) stays with the crowd while the mean (marker 2) is dragged toward the 241-minute ticket (marker 3). Support tickets, latencies and token counts always have a tail like that.
So the fix is not to delete the mean. Keep it for anything that turns into a total: mean handling time times ticket volume is the staffing bill, and no median can give you that. Put the median next to it for "typical", and a p90 or p95 next to that for "how bad it gets".
The honest downside of the median: it hides the tail completely. A median of 4.5 minutes says nothing about the ticket that sat overnight (marker 3 in Fig. 1b.1 below), and that ticket was a real customer. Percentiles have a cost too. A p99 computed on fifty requests is one request, so percentiles need volume before they mean anything.
- The median, 4.5 minutes. Sort the ten tickets and take the middle. Nine of them sit between 3 and 6 minutes, so the middle sits there too, under the tallest part of the pile. This is the number that describes a typical customer.
- The mean, 28 minutes. Add all ten and divide by ten. The one 241-minute ticket adds as much to the total as fifty ordinary ones, so the mean is dragged far to the right of the crowd, to a value no customer experienced.
- The overnight ticket, 241 minutes. One entry out of ten. The median treats it as just the last item in a sorted list; the mean treats it as 241 minutes of waiting to be shared out across everyone.
A distribution shaped like Fig. 1b.1 — bunched up on one side with a long thin tail on the other — is called skewed. Skewed data is not rare or exotic. It is the default shape of almost everything an AI engineer measures: response latencies, token counts, revenue per customer, session lengths, file sizes. In all of these, the mean sits above the median, because the tail only ever pulls in one direction. You met the fix in Module 01: percentiles, which answer "what did the unlucky ones experience?" — p90 is the value that 90% of cases beat. Mean, median, and percentiles are not competitors; they are three different questions. Here is all three asked of the same ten tickets:
You have not been taught any of the numpy calls below yet. That is on purpose. Guess first, then check. Every line in this table is explained in the step-by-step list that follows it, and the paragraph after the terminal output reads the results line by line.
Step-by-step: what middles.py does, in plain English
- Write down the ten reply times as a plain Python list — nine ordinary tickets between 3 and 6 minutes, plus the 241-minute overnight ticket.
np.meanadds all ten values and divides by ten — the "shared out equally" summary.np.mediansorts the ten values and takes the middle of the sorted list (with an even count, the average of the two middle values) — the "typical customer" summary.np.percentile(..., 90)finds the value that 90% of tickets beat — the "unlucky 1-in-10" summary.- Print all three next to the maximum, each labeled with the question it answers.
- Then delete just the one overnight ticket, recompute mean and median, and print them again — so you can see which summary was hostage to a single value and which one barely moved.
# pip install numpy
"""One slow ticket poisons the average -- mean vs median vs percentile."""
import numpy as np
# First-reply times for 10 support tickets, in minutes.
# Nine ordinary tickets... and one that sat overnight.
reply_minutes = [4, 5, 3, 6, 4, 5, 4, 3, 5, 241]
mean = np.mean(reply_minutes)
median = np.median(reply_minutes)
p90 = np.percentile(reply_minutes, 90)
print(f"mean {mean:6.1f} min <- what the dashboard reported")
print(f"median {median:6.1f} min <- what a typical customer experienced")
print(f"p90 {p90:6.1f} min <- what the unlucky 1-in-10 experienced")
print(f"max {max(reply_minutes):6d} min <- the ticket that sat overnight")
# Now delete the single outlier and watch which numbers move.
without_outlier = reply_minutes[:-1]
print(f"\nwithout the one slow ticket:")
print(f"mean {np.mean(without_outlier):6.1f} min <- moved by a factor of 6")
print(f"median {np.median(without_outlier):6.1f} min <- barely noticed")
mean 28.0 min <- what the dashboard reported
median 4.5 min <- what a typical customer experienced
p90 29.5 min <- what the unlucky 1-in-10 experienced
max 241 min <- the ticket that sat overnight
without the one slow ticket:
mean 4.3 min <- moved by a factor of 6
median 4.0 min <- barely noticed
Read the output slowly, because the whole lesson is in the contrast. With the overnight ticket included, the mean says 28 minutes and the median says 4.5 — they disagree by a factor of six about the same ten numbers, because they are answering different questions. Then the last two lines run the tape again with the single extreme ticket removed: the mean collapses from 28.0 to 4.3, while the median moves from 4.5 to 4.0. One value out of ten owned the mean. That single extreme value is called an outlier — a point that sits far away from the rest — and "the mean is hostage to outliers" is a sentence you will use for the rest of your career. It is why Module 02 reports median cart value, why Module 16 puts median handling time in client contracts, and why every latency promise you will ever sign is written in percentiles.
- The crowd. Nine tickets between 3 and 6 minutes, drawn as stacked dots: two at 3, three at 4, three at 5, one at 6. The median of all ten is 4.5, halfway between the fifth and sixth values in the sorted list, and it sits right under the tallest stack.
- The mean is the balance point. Imagine the number line as a plank and each ticket as a weight. The mean is where you would put the fulcrum to make it balance. Nine weights near 4 on one side and one weight at 241 on the other balance at 28.0, out where no ticket sits. The p90 at 29.5 says the unluckiest ticket in ten waited about half an hour.
- The median barely moves. Remove the 241 and recompute. The median drops from 4.5 to 4.0, because taking the last item off a sorted list shifts the middle by half a step. The mean collapses from 28.0 to 4.3, a factor of six, because it was carrying that one weight.
- The outlier. The overnight ticket, 241 minutes, on its own broken piece of axis because it is too far out to draw to scale. One value in ten owned the mean, and "the mean is hostage to outliers" is the sentence to keep.
The mean answers "shared out equally". The median answers "what's typical". Percentiles answer "how bad is it for the unlucky". When someone says "average", ask which question they needed answered — and glance at the gap between mean and median, because a big gap means a long tail is hiding somewhere (in Fig. 1b.1b the mean at marker 2 sits at 28 while the median sits at 4.5, and marker 4 is the reason).
04 · Lie 2"Prompt v2 Scored Five Points Higher"
Tile 2 said prompt v2 scored 78% against v1's 73%, and v2 shipped that afternoon. Nobody asked how much a 20-example eval score moves when nothing changes at all. Module 01's eval_variance.py showed the same prompt scoring anywhere from 50% to 90% on re-runs, so the team needs a number for that day-to-day wobble before it can say whether five points means anything. That number is the standard deviation, and this section builds it from a café.
The everyday version of this lie is one you have lived. A café near your office serves coffee you rate 8 out of 10 on most days. Some days it is a 6, some days a 9 — same beans, same machine, different tiny accidents.
One Tuesday a colleague tries a new café, gets a 9, and declares it better than your café. You instinctively know the verdict is worthless — one visit tells you almost nothing, because every café has good days and bad days.
To compare cafés you would need several visits to each, and the difference between them would have to be bigger than their day-to-day moodiness. Congratulations: that instinct is the entire concept. Statistics just gives the moodiness a number.
That number is the standard deviation — written σ (sigma) for the true value, or s for the estimate you compute from data. It is the typical distance of one measurement from the average.
Your café averages 8 with a standard deviation of about 1: an ordinary day lands within a point of 8, a two-point miss is unusual, a three-point miss is rare.
That is genuinely how to read it — most values land within one standard deviation of the average, and almost all land within two or three. (You will also meet the variance, written σ² ("sigma-squared") or s², which is just the standard deviation multiplied by itself. The math prefers variance internally because squared quantities add up neatly; humans read standard deviations because they live in the same units as the data. Same information, two outfits.)
Now put the eval tile from the Monday meeting next to the café. Prompt v2 scored 78% on the eval; v1 scored 73%.
Five points sounds decisive — until you ask the café question: how moody is this measurement? You saw the answer in Module 01's eval_variance.py: on a 20-example eval, one unchanging model — same true quality, nothing changing between runs — can honestly score anywhere from 50% to 90% depending on which examples land in the set.
The day-to-day moodiness of a 20-example eval is around ±10 points. The claimed difference was 5 points. The gap between the prompts is smaller than one good or bad day, which means the tile said nothing at all.
Shipping v2 on that evidence was the colleague declaring a café war after one cup.
- The days. Ten ratings: one 6, two 7s, four 8s, two 9s, one 10. Same beans, same machine, different tiny accidents. The mean is 8.0, and no single day is "the" rating.
- One standard deviation. s = 1.15 is the typical distance of one day from the mean. The bracket runs from 8 − 1.15 to 8 + 1.15, and 8 of the 10 days fall inside it. That is how to read a standard deviation: most values within one of it, almost all within two or three.
- Two wobbly scores. v1 scored 73 and v2 scored 78, but each score could honestly have come out ten points either way on a different 20 examples. Draw that wobble as a bar and the two bars overlap from 68 to 83. Both scores are consistent with the two prompts being identical.
- The z-score. Divide the gap by the wobble: 5 ÷ 10 = 0.5. The claimed difference is half of one ordinary good-or-bad day. A z-score near 0 is an ordinary day; 2 is notable; 3 is a discovery or a bug. Tile 2 shipped on a 0.5.
This is also the moment to name a small tool you will meet constantly: comparing a gap to the typical wobble has a name, the z-score — "how many standard deviations away from the average is this value?" A z-score near 0 is an ordinary day.
A z-score of 2 is notable. A z-score of 3 or more is either a discovery or a bug.
When Module 02 "standardizes" features before training — subtract the average, divide by the standard deviation — it is converting every feature into z-scores so that "unusually large" means the same thing for a $4,000 cart and a 40-item cart.
And the whole hypothesis-testing machinery from Module 01 is this same move: the z-statistic there was literally the observed lift divided by the typical size of a lucky wobble. One idea, three costumes: express everything in units of its own moodiness.
Two practical rules fall out. First: never compare two scores without knowing the wobble of each — for evals, that means the confidence intervals you learned in Module 01, or simply a much bigger eval set.
Second: the wobble shrinks by the square root √ of the sample size n — four times the data buys only half the noise — so precision is bought in bulk, never retail.
- n = 20. Tile 2's eval. A score can honestly land anywhere in a 20-point-wide bar, so a 5-point gap between two such scores is noise.
- Four times the data, half the wobble. Go from 20 to 80 examples and the bar shrinks from ±10 to ±5, not to ±2.5. That is the √n rule: the noise averages down with the square root of the count, so precision is bought in bulk.
- Sixteen times the data. At 320 examples the wobble is ±2.5. Now a 5-point gap is twice the wobble, and the comparison starts to mean something.
- The gap you are trying to see. Five points. Draw it against the bars: it is swallowed by the first, matched by the second, and only clearly bigger than the third. Decide the eval size from the gap you need to detect, not the other way round.
There is no code block in this section on purpose: the proof already exists on your machine.
Re-run
eval_variance.py from Module 01 right now and re-read its three output
lines with today's vocabulary — that re-run is this section's exercise, and
reaching back a module is deliberate memory training.
Never read a number without asking how much it wobbles. The standard deviation is the typical wobble; a difference smaller than the wobble is a coin toss wearing a suit. And wobble shrinks with √n — four times the data, half the noise.
Out loud or on paper, from memory: (1) Which summary is hostage to outliers — mean or median — and why? (2) Your p95 latency is 2.1 s and your mean latency is 0.9 s — what does that gap tell you about the shape of the data? (3) What question does a standard deviation answer, in one sentence?
Check your answers
(1) The mean — every value pulls on it in proportion to its size, so one extreme value drags it far from typical; the median only sees the middle of the sorted list. (2) A mean far below the tail percentiles means the data is skewed with a long slow tail, the shape of row 2 in Fig. 1b.1b: most requests are fast, a few are very slow. (3) The standard deviation is the typical distance of a single measurement from the average — the data's day-to-day moodiness, in the data's own units.
05 · The toolboxThe Five Shapes of Randomness
Two tiles down, and both failures came from the shape of the data: tile 1's ten tickets had one 241-minute outlier dragging the mean to 28, and tile 2's eval scores wobbled ±10 points around a centre. Four tiles remain, and the team needs a way to predict a dataset's shape before collecting it, because the shape decides which summary and which alarm rule are safe to use. That is what the five recipes give you: how a number is made tells you its silhouette.
The first two lies both came down to shape — the average lied because the data had a long tail (the 241 in Fig. 1b.1b), and the eval lied because scores wobble around a center (the ±10 bars in Fig. 1b.1c). So it is worth pausing to meet shape properly.
Collect many measurements of the same thing — a thousand support tickets, a thousand API calls, a thousand eval runs — and pile them up by value, tallest pile where values are most common.
That resulting silhouette is called a distribution: the complete honest answer to "what values does this thing take, and how often?" Every summary you have met — mean, median, standard deviation, percentiles — is a one-number compression of that silhouette.
The useful surprise is that nature keeps reusing the same handful of silhouettes, and which one you get is determined by how the number was made. Learn five recipes and you can predict the shape of data you have never seen.
Recipe 1 — add up many small independent nudges, and you get the normal distribution (also called the Gaussian, or "the bell curve").
Adult height is the classic example: thousands of genes and childhood factors each nudge height a little up or a little down, no single one dominates, and the sum lands in a symmetric bell around the average.
Measurement error behaves the same way, which is why the bell curve is everywhere in lab science.
A bell is friendly: mean and median agree, and the standard deviation tells you nearly everything — about 68% of values land within 1 σ (sigma) of the average and about 95% within 2 σ.
That "95% within 2 σ" is exactly where Module 01's magic number 1.96 came from.
Recipe 2 — give every value an equal chance, and you get the uniform distribution. A fair die, a random draw from a hat, a well-behaved hash function spreading keys across buckets.
Flat, boring, and mostly useful as a
starting ingredient: rng.uniform() is the raw randomness from which
simulations cook up everything else.
Recipe 3 — count how many rare events land in a fixed window, and you get the Poisson distribution (pronounced "pwa-SON"): support tickets arriving per hour, errors per million requests, goals per football match.
Each event is individually unpredictable, but the count per window has a stable, predictable shape. Recipe 4 — measure the waiting time between those events, and you get the exponential distribution: lots of short waits, occasionally a long silence.
If tickets average one every 10 minutes, a 30-minute silence is uncommon but perfectly normal — a fact that stops teams panicking (or celebrating) over every quiet hour.
- The bell's bands. Add many small nudges and the pile is symmetric around its mean. With σ (sigma) = 5, 68% of values land between 45 and 55 and 95% between 40 and 60. That "95% within 2σ" is where Module 01's 1.96 came from.
- The flat top. Every value between 0 and 100 equally likely: a fair die with a hundred faces. Mean and median both sit at 50, and the maximum can never exceed 100. Boring, and the raw ingredient every simulation starts from.
- The busy hour. Count rare events per fixed window and the bars have this shape. At an average of 4 tickets an hour, an hour with 8 or more happens 1 time in 20, so it is weather, not news. The worst hour in 100,000 had 15.
- The long silence. Measure the wait between those events and most waits are short, with an occasional long one. At one ticket every 10 minutes on average, a 30-minute silence has probability e⁻³, about 5%: uncommon, and perfectly normal.
Recipe 5 is the one AI work lives inside: multiply many small effects together — instead of adding them — and you get the lognormal distribution. Multiplication is how compounding works, so this is the shape of anything that grows or cascades: wealth, city sizes, file sizes, viral posts — and LLM response latency, where queue delays, retries, token counts, and cold caches multiply into the occasional 10-second monster.
Its signature is the heavy tail, the accented far right of Fig. 1b.2 below: rare values so much larger than typical that they dominate totals and averages.
(Its more extreme cousin, the power law or "long tail", shows up in Module 13 — a few blockbuster items get most of the traffic while millions of items share the scraps.) Here are all five silhouettes side by side:
Before running the code: for which of the five shapes will the mean and the median roughly agree, and for which will they split apart? Make a prediction for each of the five before looking.
Reveal the answer
Symmetric shapes — normal and uniform — have mean ≈ median, because equal amounts of data sit on both sides of the center. Poisson at a moderate rate is nearly symmetric, so they roughly agree there too.
The two lopsided shapes split: exponential and lognormal both have a long right tail, and tails drag the mean up while leaving the median with the crowd.
A mean sitting well above the median is therefore a tail detector you can apply to any dataset in one line of code.
Step-by-step: what shapes_of_randomness.py does, in plain English
- Create a random-number generator seeded with 3, so every run of the script produces exactly the same "random" numbers and your output matches the one printed here.
- Draw 100,000 samples from each of the five recipes:
rng.normal(50, 5, N)is "add many nudges" (centered at 50, typical wobble 5);rng.uniform(0, 100, N)is "every value between 0 and 100 equally likely";rng.poisson(4, N)is "count events per window, averaging 4 per window";rng.exponential(10, N)is "waiting times that average 10";rng.lognormal(3.4, 0.7, N)is "multiply many nudges". - Store all five in a dictionary keyed by a label that names the recipe.
- For each shape, print four summaries in columns: the mean, the median, the 95th percentile, and the maximum.
- The point of the table is the comparison across rows: where mean and median agree the shape is symmetric, and where the mean drifts above the median — and the maximum explodes — a tail is present.
# pip install numpy
"""Five shapes of randomness -- and how to tell them apart from summaries."""
import numpy as np
rng = np.random.default_rng(3)
N = 100_000 # one hundred thousand samples of each shape
shapes = {
"normal (many small nudges) ": rng.normal(50, 5, N),
"uniform (every value fair) ": rng.uniform(0, 100, N),
"poisson (counts per hour) ": rng.poisson(4, N),
"exponential (waits between) ": rng.exponential(10, N),
"lognormal (multiplied nudges) ": rng.lognormal(3.4, 0.7, N),
}
print(f"{'shape':34s}{'mean':>8s}{'median':>8s}{'p95':>8s}{'max':>8s}")
for name, x in shapes.items():
print(f"{name:34s}{np.mean(x):8.1f}{np.median(x):8.1f}"
f"{np.percentile(x, 95):8.1f}{np.max(x):8.1f}")
shape mean median p95 max
normal (many small nudges) 50.0 50.0 58.2 71.8
uniform (every value fair) 50.1 50.2 95.0 100.0
poisson (counts per hour) 4.0 4.0 8.0 15.0
exponential (waits between) 10.0 6.9 30.0 135.6
lognormal (multiplied nudges) 38.3 30.0 94.6 907.2
Read the table row by row. The normal row is perfectly tame: mean and median both 50, the 95th percentile less than two standard deviations out, and even the most extreme value in 100,000 draws only reaches 71.8 — bells simply do not produce monsters. The uniform row agrees on mean and median too, because it is symmetric. The Poisson row shows counts averaging 4 per hour: an 8-ticket hour sits at the 95th percentile, and the worst hour in 100,000 had 15 — busy, but bounded. Now the exponential row: the mean is 10 but the median is 6.9 — the mean sits 45% above the typical wait, dragged by long silences, and the longest wait was 135. And then the lognormal row goes feral: mean 38 versus median 30, and a maximum of 907 — thirty times the typical value, from the same recipe that produced the crowd. That 907 is your future 10-second LLM response living happily in a system whose median response is 300 ms. Nothing is broken. That is simply what multiplication does.
- Symmetric. Rows 1 to 3. The normal, the uniform and the Poisson at a moderate rate put equal amounts of data on both sides of the centre, so the mean lands on the median. Their maxima are tame: 71.8, 100, 15.
- The gap. Row 4, the exponential. The mean (10.0) sits 45% to the right of the median (6.9). Nothing exotic happened; long silences simply add more to the total than short waits subtract. A mean sitting well above the median is a one-line detector for this shape.
- The monster. Row 5, the lognormal. Mean 38.3, median 30, and a maximum of 907 from the same recipe that produced the crowd. That 907 is a 10-second LLM response in a system whose median is 300 ms. Nothing is broken; multiplication did it.
Why does this matter beyond trivia? Because the shape tells you which summaries to trust and which alarms to set. Bell-shaped data: means and standard deviations work beautifully, and 3-σ (three-sigma) alerts are meaningful.
Heavy-tailed data: means mislead, standard deviations mislead worse, and you must reach for medians and percentiles — this is precisely why Module 12's monitoring stack watches p95/p99 and never averages.
Counting data: expect Poisson wobble, so a quiet hour or a double-rate hour is usually just weather, not news.
And when Module 02 hands you skewed inputs, you now know why taking the logarithm helps: log turns multiplication back into addition, which turns a lognormal back into a friendly bell.
Ask how the number was made, and you will know its shape before you see the data. Added nudges → bell. Equal chances → flat. Counted events → Poisson. Waits → exponential. Multiplied effects → heavy tail (row 5 of Fig. 1b.2b) — and heavy tails mean medians and percentiles, never means.
06 · Lie 3"The Fraud Filter Is 99.2% Accurate"
Tile 3 said the fraud filter was 99.2% accurate, and the manual-review team was cut. At SaaSify 8 payments in every 1,000 are fraud, so a model that never raises an alarm is also 99.2% accurate while missing every single one of them. The team needs a report card that cannot be gamed by staying quiet. That is the four boxes, and the two numbers read off them: precision and recall.
Here is a model you can build in zero lines of code: for every payment, predict "not fraud". Never look at the data. Never train anything.
At SaaSify, where 8 payments in every 1,000 are fraudulent, this do-nothing model is right 99.2% of the time — because 99.2% of payments really are legitimate, and it calls all of them correctly while missing every single fraud.
Accuracy — the share of all predictions that were right — sounds like the obvious way to grade a model, and it silently rewards ignoring the rare class completely.
Whenever the thing you care about is rare (fraud, churn, tumors, defects, security intrusions — which is to say, almost always), accuracy answers a question nobody asked.
The fix is to stop compressing the model's performance into one number and instead look at the four things that can actually happen. The model raises an alarm or stays quiet; the payment truly is fraud or truly is not.
Two choices by two truths gives four boxes, and this little grid — the confusion matrix — is the honest report card behind every classifier you will ever ship.
Each box has a standard name: a true positive (TP) is an alarm that was right (caught fraud), a false positive (FP) is a false alarm (an honest customer flagged), a false negative (FN) is a miss (fraud that slipped through), and a true negative (TN) is correctly staying quiet.
You already met the first two wearing court robes in Module 01: a false positive is a Type I error, a false negative is a Type II error — same ideas, now counted instead of feared.
From the four boxes come the two numbers that actually matter, and each is just a different reading direction on the grid. Precision reads across the alarm row: of all the alarms the model raised, what fraction were real? — TP ÷ (TP + FP).
It is the "boy who cried wolf" number: low precision means your alarms waste people's time and get ignored. Recall reads down the fraud column: of all the fraud that actually happened, what fraction did we catch? — TP ÷ (TP + FN).
It is the smoke-detector number: low recall means fires burn undetected. Say both sentences out loud until they feel different, because they are: precision is about trusting the alarms, recall is about covering the fires.
(When one summary number is required, the F1 score blends the two — it is high only when both are high. And the trade-off between them as you slide the alarm threshold is what Module 02's ROC and precision–recall curves will draw for you.)
Run the dummy first.
Fill the four boxes.
Read precision across the alarm row.
Read recall down the fraud column.
The dummy: panel 1 of Fig. 1b.3c, zero alarms and still 99.2% accurate. The four boxes: the grid in Fig. 1b.3, one box for each way an alarm can be right or wrong. Across the alarm row: TP ÷ (TP + FP), the top row of Fig. 1b.3, which is precision. Down the fraud column: TP ÷ (TP + FN), the left column, which is recall.
Step-by-step: what four_boxes.py does, in plain English
- Define one function,
four_boxes, which takes a scenario: how many payments (n), what fraction are truly fraud (the base rate), what fraction of real fraud the model catches (recall), and what fraction of honest payments it false-alarms on (the false-positive rate, "fpr"). - Split the n payments into truly-fraud and truly-legit counts using the base rate.
- Fill the four boxes with arithmetic: true positives = fraud × recall; false negatives = the fraud that remains; false positives = legit × fpr; true negatives = the legit that remain.
- Compute accuracy as (TP + TN) ÷ n, and precision as TP ÷ (TP + FP), guarding against dividing by zero when a model raises no alarms at all.
- Print the four boxes and the three metrics, each labeled with the plain-words question it answers.
- Run three scenarios: the do-nothing dummy that never alarms; a genuinely good model (85% recall, 2% false-alarm rate) at SaaSify's 0.8% fraud rate; and the identical model dropped into a marketplace where 10% of payments are fraud — so you can watch precision transform while the model itself never changes.
# no installs needed -- pure Python
"""The four boxes behind every 'accuracy' claim -- and the base-rate flip."""
def four_boxes(name: str, n: int, base_rate: float, recall: float, fpr: float) -> None:
"""Print the confusion matrix and the honest metrics for one model."""
fraud = round(n * base_rate) # payments that truly are fraud
legit = n - fraud # payments that truly are fine
tp = round(fraud * recall) # fraud we caught
fn = fraud - tp # fraud we missed
fp = round(legit * fpr) # honest payments we flagged
tn = legit - fp # honest payments we passed
accuracy = (tp + tn) / n
precision = tp / (tp + fp) if tp + fp else 0.0
print(f"--- {name} (fraud rate {base_rate:.1%}) ---")
print(f" caught fraud (TP) {tp:6,} missed fraud (FN) {fn:6,}")
print(f" false alarms (FP) {fp:6,} correct passes (TN){tn:7,}")
print(f" accuracy {accuracy:6.1%} <- sounds impressive, hides everything")
print(f" recall {recall:6.1%} <- of all real fraud, how much we caught")
print(f" precision {precision:6.1%} <- of all our alarms, how many were right\n")
N = 100_000
# The dummy: predicts "legit" for every single payment, catches nothing.
four_boxes("Dummy model: always say legit", N, base_rate=0.008, recall=0.0, fpr=0.0)
# A genuinely useful model: catches 85% of fraud, false-alarms on 2% of legit.
four_boxes("Real model", N, base_rate=0.008, recall=0.85, fpr=0.02)
# The SAME model, moved to a marketplace where 10% of payments are fraud.
four_boxes("Same model, riskier marketplace", N, base_rate=0.10, recall=0.85, fpr=0.02)
--- Dummy model: always say legit (fraud rate 0.8%) ---
caught fraud (TP) 0 missed fraud (FN) 800
false alarms (FP) 0 correct passes (TN) 99,200
accuracy 99.2% <- sounds impressive, hides everything
recall 0.0% <- of all real fraud, how much we caught
precision 0.0% <- of all our alarms, how many were right
--- Real model (fraud rate 0.8%) ---
caught fraud (TP) 680 missed fraud (FN) 120
false alarms (FP) 1,984 correct passes (TN) 97,216
accuracy 97.9% <- sounds impressive, hides everything
recall 85.0% <- of all real fraud, how much we caught
precision 25.5% <- of all our alarms, how many were right
--- Same model, riskier marketplace (fraud rate 10.0%) ---
caught fraud (TP) 8,500 missed fraud (FN) 1,500
false alarms (FP) 1,800 correct passes (TN) 88,200
accuracy 96.7% <- sounds impressive, hides everything
recall 85.0% <- of all real fraud, how much we caught
precision 82.5% <- of all our alarms, how many were right
The output hides two bombshells, so take them one at a time. Bombshell one: compare the first two scenarios by accuracy alone. The dummy scores 99.2%; the genuinely useful model scores 97.9%. By accuracy, the model that catches 85% of all fraud loses to the model that catches nothing. That single comparison should permanently cure you of trusting an accuracy number on imbalanced data — and it is why Modules 03 and 17 insist on precision- and recall-based metrics for rare-event problems, and why the first baseline you run in Module 02 is always the dummy. Bombshell two: compare the last two scenarios. The model is identical — same 85% recall, same 2% false-alarm rate — yet its precision leaps from 25.5% to 82.5% just because fraud went from rare to common. Precision is not a property of the model alone. It is a property of the model plus the world it is deployed into. Why? That question deserves its own section, because it is the fourth lie.
- The dummy wins on accuracy. Zero alarms, so the top row is empty. It misses all 800 frauds and correctly passes 99,200 honest payments, and accuracy counts the 99,200 as wins. That single number is what tile 3 showed the room.
- The real model, read the honest way. Across the alarm row: 680 real catches out of 680 + 1,984 alarms, precision 25.5%. Down the fraud column: 680 caught out of 680 + 120, recall 85%. Its accuracy, 97.9%, is lower than the dummy's, because 1,984 false alarms count against it while the dummy's 800 misses barely dent 100,000.
- Same model, different world. Move the identical model to a market where 10% of payments are fraud. Nothing about it changed: it still catches 85% and still false-alarms on 2% of honest payments. But now there are 10,000 frauds to catch and only 90,000 honest payments to false-alarm on, so the alarm pile is mostly real and precision reads 82.5%. Precision belongs to the model and the world together.
Accuracy asks "how often were we right?" Precision asks "when we raised an alarm, was it real?" Recall asks "of the real fires, how many did we catch?" On rare-event problems, always run the do-nothing dummy first — any model that cannot beat it is expensive decoration.
07 · Lie 4"The Alarm Fired, So It's Probably Fraud"
Tile 4 said a flagged payment means fraud, so the team began freezing cards on every flag. From tile 3 we know the filter catches 85% of fraud and false-alarms on 2% of honest payments, and that fraud is 0.8% of traffic. The question the analyst faces is not the one the filter answers: not "how often does fraud get flagged" but "how often does a flag mean fraud". This section counts payments to answer it, and the answer is 26%, not 85%.
The everyday version of this lie is famous enough to have fooled doctors in published studies. A disease affects 1 person in 1,000. The test for it is genuinely excellent: it catches 99% of sick people, and it false-alarms on only 5% of healthy people. Your test comes back positive. How worried should you be? Most people — including, in repeated experiments, most physicians — answer "about 95–99% chance I'm sick". The real answer is about 2%. Not ninety-five. Two.
The trick to seeing why is to stop thinking in percentages and start counting people — a frequency tree. Take 10,000 people. About 10 of them have the disease; the test catches essentially all 10.
The other 9,990 are healthy — but a 5% false-alarm rate on 9,990 people produces about 500 false positives. So the pile of people holding a positive result contains 10 sick and 500 healthy: 510 people, of whom 10 are actually sick — roughly 2%.
The alarm pile is dominated by false alarms, not because the test is bad, but because healthy people outnumber sick people five hundred to one. The rarity of the disease — its base rate — crushes the quality of the test.
Rare things stay rare, even after an alarm fires. Here is the same tree drawn for SaaSify's fraud filter:
Now the notation, because you have just been doing conditional probability in your head and it deserves its name.
P(fraud) — read "probability of fraud" — is the base rate. Here 0.8%: the chance for a random payment before you know anything else.
P(fraud | flag) — read "probability of fraud given a flag" — is the question the analyst actually faces. Among only the flagged payments, how many are fraud?
The vertical bar | means "given", or "among only the cases where".
The tree computed P(fraud | flag) = 68 ÷ 266 ≈ 26%.
And here is the trap the Monday meeting fell into, stated precisely: P(fraud | flag) is not the same number as P(flag | fraud).
The model catches 85% of fraud — so P(flag | fraud) = 0.85 — and yet a flag only means 26% fraud. Swapping the two sides of the bar is the single most common probability error in industry and in interviews.
- The base rate. Eight fraud dots in a thousand. Everything else in this picture follows from how small that number is next to the 992 honest ones.
- Read the fraud dots: P(flag | fraud). Of the 8 fraud dots, 7 are flagged. That is 85%, the filter's recall, and it is a fact about the filter that stays true in any market.
- Read the boxed dots: P(fraud | flag). Of the 27 flagged dots, 7 are fraud. That is 26%, and it is the only number an analyst holding a flag can use. Tile 4 read the previous number as if it were this one.
- Why they differ. Two percent of a huge pile (20 of 992) is bigger than 85% of a tiny pile (7 of 8). The honest pile is 124 times larger, so even a small false-alarm rate on it floods the alarm pile.
The two are connected. The recipe for getting from one to the other is Bayes' rule, and the frequency tree is Bayes' rule performed with counts. The formula itself is laid out piece by piece just below, and the Under the hood section plugs the numbers in.
You start with a prior belief (0.8%), evidence arrives (a flag), and you update to a posterior belief (26%). Thirty-two times more suspicious than before — and still probably innocent.
P(fraud | flag)1 = P(flag | fraud)2 × P(fraud)3 ÷ P(flag)4
- The posterior: the number you want. The probability of fraud given a flag, where the vertical bar reads "given" and means "among only the flagged payments". In the tree this was 68 ÷ 266. The mistake: reading it as the same thing as term 2, which is the swap that fooled the Monday meeting.
- The likelihood: the model's recall. Of the payments that truly are fraud, the share the model flags, 0.85 here. It is a fact about the model and stays the same in any market. The mistake: plugging in precision, which is the answer, not an input.
- The prior: the base rate. How common fraud is before any evidence arrives, 0.008 here. This is the term that keeps rare things rare. The mistake: leaving it out, which silently assumes fraud and honesty are equally common.
- The evidence rate: how often flags happen at all. Flags come from two sources, real catches and false alarms, so this is 0.85 × 0.008 + 0.02 × 0.992 = 0.0266. The mistake: counting only the real catches, which makes the answer come out as 1.0 and the alarm look perfect.
One more probability idea rides along with this one: independence. Two events are independent when knowing one tells you nothing about the other — coin flips, unrelated API failures.
When events are independent, probabilities multiply: the chance of ten independent successes at 95% each is 0.95 × 0.95 × … ten times ≈ 60%, which is the brutal arithmetic behind Module 09's agent chains.
But the moment events share a cause, multiplying becomes a lie: two services in the same rack do not fail independently, two eval questions about the same topic do not miss independently, and Module 03 will show you a whole ensemble method — bagging — whose entire job is manufacturing independence between models because averaging only cancels errors that are uncorrelated.
When you multiply probabilities, you are silently claiming independence. Say the claim out loud and check it.
Rare things stay rare, even after an alarm. Never read P(A | B) as P(B | A) — "how often fraud triggers a flag" and "how often a flag means fraud" are different numbers, connected only through the base rate. When in doubt, draw the tree and count people.
Before the two of them argue, look at what each one actually reads. Fig. 1b.4c puts tile 4's four boxes next to tile 3's dummy, the same filter in a riskier market, and the price of moving the threshold. Every line in the chat below points at a number in this picture.
- Precision reads across, recall reads down. Same four boxes, two directions. Across the alarm row: 68 real catches out of 266 alarms, 26%. Down the fraud column: 68 caught out of 80 frauds, 85%. Tile 4 froze 266 cards, and 198 of them belonged to honest customers.
- The dummy. Never fire. The alarm row is empty, so precision is 0 ÷ 0 and recall is 0 ÷ 80. Accuracy still reads 99.2%, because the 9,920 correct passes drown the 80 misses. This is the number that got the review team cut.
- Same model, a different world. Nothing about the filter changed between panels 1 and 3. Fraud went from 0.8% to 10% of traffic, so the alarm pile is now mostly real and precision reads 82.5%. Recall is 85% in both panels. Precision is a statement about the model and the world; recall is a statement about the model.
- The threshold is a price tag. Slide the threshold up and the alarms get cleaner but more fraud walks through. At $4 a look and $500 a miss, the messy threshold (0.5) costs $69,440 a day and the clean one (0.9) costs $204,380. Which number matters depends on which mistake is expensive.
Tonight's talk: Precision and Recall argue over the question, "Who's more important?"
Start with tile 4, panel 1 of Fig. 1b.4c. Ten thousand payments, 266 flags, and 198 of those flags are honest customers. Monday's rule was "a flag means fraud", so they froze all 266 cards: three in four belonged to people who did nothing wrong. Frozen cards, furious phone calls, a support queue on fire. I am the number that reads across the alarm row and says whether an alarm deserves to be believed: 68 ÷ 266, 26%.
precision is the share of alarms that were right. In panel 1 that is 68 real catches out of 266 flags, so a flag deserved to be believed one time in four.
And tile 3, panel 2, the one right before it. They cut the review team because the filter was "99.2% accurate". Look at the dummy's boxes: zero alarms, 80 frauds missed, 9,920 honest passes, and accuracy still reads 99.2%. Accuracy was delighted, I read 0 ÷ 80, you read 0 ÷ 0, and every fraud walked straight through. I am the number that reads down the fraud column and says how much of the real thing you caught. Without me, silence looks like success.
recall is the share of real fraud that was caught. The do-nothing model in panel 2 catches none of the 80, so its recall is zero even though its accuracy is 99.2%.
Without me, noise looks like diligence. Take the slider in panel 4 and push the threshold down until you catch every fraud, and you will get your 100%. You will also flag a fat slice of the honest customers. The reviewers stop reading, the queue gets rubber-stamped, and your perfect recall is decorative. Alarm fatigue is a precision failure, and it ends up killing you too.
a lower threshold raises recall but floods the queue with false alarms. Once reviewers stop trusting alarms, a high recall stops helping anyone.
Push the same slider up until every alarm is clean and you can have that too. Panel 4 prices it: at 0.9 there are 1,095 flags a day and most are right, but 400 frauds never ring a bell. A miss costs $500 and a look costs $4, so the "cleaner" threshold costs $204,380 a day against $69,440 at 0.5. Your tidiness had a price tag of about $135,000 a day and the ops lead never read it.
raising the threshold buys cleaner alarms by missing more fraud. Panel 4 shows that when one miss costs as much as 125 looks, the messy threshold is far cheaper.
Fair. But notice how that argument was won: by multiplying the boxes by the costs, not by you. Flip the costs and I win. Paging an engineer at three in the morning. Flagging a loyal customer as a thief. Auto-deleting a signed contract because a filter called it phishing. Every one of those lives in the 198 box in panel 1, and false alarms are my department.
which number matters depends on which mistake is expensive. When a false alarm costs more than a miss, precision is the one to protect.
Cancer screening. Safety filters on a chatbot. A recall notice on a brake part. Anywhere a miss cannot be undone, they set the slider in panel 4 low for me and hire people to absorb your false alarms. That is not a defeat for you. It is a job description.
when a miss is catastrophic, the threshold is set low to maximise recall, and the extra false alarms are handled by people on purpose.
Here is what actually bothers me. I am not even a property of the model. Compare panels 1 and 3: same filter, same 85% recall, same 2% false-alarm rate, and I read 26% in one market and 82.5% in the other. The base rate moves me and nobody asks my permission.
precision depends on how common fraud is. In panel 3 fraud is 10% of traffic instead of 0.8%, and the same model's alarms become right four times in five.
Which is why I am the one they can print in a spec. "68 of 80 caught" in panel 1 and "850 of 1,000" in panel 3 are the same 85%, wherever the model goes, as long as fraud keeps looking like fraud. "One flag in four is real" is true at SaaSify, this quarter. You are a statement about the model and the world together. I am a statement about the model.
recall stays the same across both markets because it only looks at the fraud column. Precision changes because it also depends on how big the honest pile is.
A statement about the model that says nothing about whether a human can act on its alarms.
a high recall alone does not tell you whether the alarm pile is worth reading.
A statement about the world that says nothing about how much of the world you missed. Shall we agree on the one thing the four boxes make obvious?
a high precision alone does not tell you how much fraud slipped through the quiet row.
That nobody should ever be shown one of us without the other. Fine. The threshold review is next quarter. We'll revisit this.
always report precision and recall together, and choose the threshold from the costs in panel 4, never from either number alone.
Questions you might be asking now
This section and the chat above move quickly between percentages that sound alike: 85%, 2%, 26%, 74%. If one of them did not land, open the question that matches yours. Every answer uses the same four counts from Fig. 1b.4, small enough to check with a pencil.
| Box | The payment really was | The filter | Count |
|---|---|---|---|
| TP · caught | Fraud | Flagged it | 68 |
| FP · false alarm | Honest | Flagged it | 198 |
| FN · missed | Fraud | Stayed quiet | 12 |
| TN · quiet pass | Honest | Stayed quiet | 9,722 |
The filter false-alarms on only 2% of honest payments. So why are 74% of its flags false? Aren't those the same number?
No. Both numbers start from the same 198 false alarms, but they divide by different piles. 198 ÷ 9,920 honest payments = 2.0%. 198 ÷ 266 flags = 74.4%. The first describes the filter; the second describes the queue an analyst actually works through.
Every rate in this chapter is a fraction with a top and a bottom. The top is a count of payments. The bottom answers the question "out of what?" Two rates with the same top and different bottoms are different numbers, even when both have the word "false" in their name.
Here are the two fractions, built step by step from the four counts.
- Find the false alarms. Honest payments that the filter flagged: the FP box, 198.
- Bottom 1 is the honest pile. Every honest payment, flagged or not: FP + TN = 198 + 9,722 = 9,920.
- Divide. 198 ÷ 9,920 = 0.020, so 2.0%. This is the false-alarm rate, written P(flag | honest): of the honest payments, the share that get flagged.
- Bottom 2 is the alarm pile. Every flag, right or wrong: TP + FP = 68 + 198 = 266.
- Divide again. 198 ÷ 266 = 0.744, so 74.4%. This is P(honest | flag): of the flags, the share that are honest customers. It is 100% minus precision.
The honest pile is huge, so 198 is a sliver of it. The alarm pile is small, so the same 198 payments are most of it. Fig. 1b.4e draws those 198 payments inside both piles, with dashed lines following them from one to the other.
- The honest pile. All 9,920 honest payments as one long bar. The filter flags 198 of them, the thin amber sliver at the left end. 198 ÷ 9,920 = 2.0%, the false-alarm rate. It is small because the bottom is huge.
- The same 198, in the alarm pile. Now the bottom is every flag: 198 false alarms plus 68 real catches, 266 in all. The same 198 payments fill almost three quarters of this bar: 198 ÷ 266 = 74.4%.
- The real catches. The green part, 68 of the 266 flags, is precision: 25.6%. The green and amber parts always add up to 100%, because every flag is either fraud or honest.
- Same top, different bottoms. The false-alarm rate divides by one kind of payment only, so it stays at 2% in any market. The share of false flags divides by a mix of fraud and honest payments, so it drops to 17.5% when fraud is 10% of traffic.
The table lists every rate from this section as a fraction, so each bottom is visible. The last column reruns the same filter in the 10% market of Fig. 1b.4c panel 3.
| Name in this chapter | Written with the bar | Top ÷ bottom at 0.8% fraud | Value | In the 10% market |
|---|---|---|---|---|
| Base rate | P(fraud) | 80 ÷ 10,000 | 0.8% | 10.0% |
| Recall | P(flag | fraud) | 68 ÷ 80 | 85.0% | 85.0% |
| False-alarm rate | P(flag | honest) | 198 ÷ 9,920 | 2.0% | 2.0% |
| Alarm rate (the 0.0266 in Bayes' rule) | P(flag) | 266 ÷ 10,000 | 2.66% | 10.3% |
| Precision | P(fraud | flag) | 68 ÷ 266 | 25.6% | 82.5% |
| Share of flags that are false | P(honest | flag) | 198 ÷ 266 | 74.4% | 17.5% |
Read the last column first. Recall and the false-alarm rate did not move, because each of their bottoms counts only one kind of payment. They are facts about the filter. The other rates changed, because their bottoms mix fraud with honest payments, and the mix is set by the market. That is why precision went from 25.6% to 82.5%.
So a vendor's "only 2% false positives" and an analyst's "three flags in four are wrong" can both be true of one filter. The standard names help once you know the bottoms. The 2% is the false positive rate. The 74.4% is called the false discovery rate.
The honest limit: neither number is "the" false-alarm number. The 2% is the one to compare filters with, because it travels between markets unchanged. The 74.4% is the one to plan staffing and customer apologies with, because it describes what the review queue will actually hold this quarter.
Before you trust any rate, ask "out of what?" The same 198 false alarms are 2% of the honest payments and 74% of the flags.
Is precision the same thing as the probability the model gives one payment?
No. Precision, 25.6%, is one average over all 266 flags. Flags with high scores are far more likely to be fraud than flags that only just passed the threshold. And a score is not a probability at all until someone checks it against real outcomes, which is the job of section 08.
Three numbers sit close together here, and it helps to name them before comparing them.
- The score. What the model outputs for one payment, like the 0.66 of payment p4 in the threshold exercise. It puts payments in order from least to most suspicious.
- The threshold. The cut-off you choose on the scores. Here it is 0.5: a payment scoring 0.5 or more is flagged.
- Precision. Of everything at or above the threshold, the share that really was fraud. It is one number for the whole pile: 68 ÷ 266.
To see how the score and precision differ, split the 266 flags by score. The table does that. The split itself is an illustration, because real teams learn it from months of labelled chargebacks. Its totals are exactly the four counts above.
| Score band | Fraud | Honest | Payments | Share that is fraud |
|---|---|---|---|---|
| 0.9 to 1.0 | 30 | 4 | 34 | 88.2% |
| 0.7 to 0.9 | 24 | 36 | 60 | 40.0% |
| 0.5 to 0.7 | 14 | 158 | 172 | 8.1% |
| All flags, 0.5 and up | 68 | 198 | 266 | 25.6%, the precision |
| Below 0.5, not flagged | 12 | 9,722 | 9,734 | 0.12% |
Now check that precision really is an average of the three bands. Weight each band's fraud share by the number of flags in it, then divide by all flags.
- Top band. 34 flags × 88.2% fraud = 30 frauds.
- Middle band. 60 flags × 40.0% fraud = 24 frauds.
- Bottom band. 172 flags × 8.1% fraud = 14 frauds.
- Add, then divide by all flags. (30 + 24 + 14) ÷ 266 = 68 ÷ 266 = 25.6%.
So precision is correct, and it still says little about any one payment. No single flag is "25.6% fraud". A flag scoring 0.95 sits in a band where nearly nine in ten are fraud. A flag scoring 0.55 sits in a band where fewer than one in twelve are. Fig. 1b.4f puts the three bands side by side.
- The bands. Each bar is one score band, and its length is the number of flags in it. Most flags only just passed the threshold: 172 of the 266 scored between 0.5 and 0.7. Green is fraud and amber is honest.
- Precision is the average. The dashed line at 25.6% is 68 ÷ 266, all three bands pooled. It sits between the bands' own shares, pulled toward the bottom band because that band holds most of the flags.
- A score is not a probability. The bottom band's flags scored between 0.5 and 0.7, yet only 8.1% of them were fraud. The score ranked them correctly, above the payments that were not flagged, but it did not state their chance.
- One payment. An analyst holding a single flag should read its band, not the pile's average. A 0.95 is close to nine in ten; a 0.55 is under one in twelve. Payments that were not flagged are 0.12% fraud, which is where the 12 missed frauds hide.
Notice that a score of 0.55 did not mean a 55% chance. In its band, 8.1% were fraud. A raw score is a ranking: higher means more suspicious. It becomes a probability only when someone counts outcomes at each score and finds that they match. That check is called calibration, and section 08 runs it on a churn model.
The split also changes what tile 4 could have done. Freezing only the top band stops 30 frauds and freezes 4 honest cards. Freezing every flag stopped 68 frauds and froze 198 honest cards. The other 232 flags, which hold 38 frauds, could go to a human reviewer. A rule per band needs the split; the average cannot support it.
The honest limit is volume. A count of 14 frauds among 172 flags would wobble by about ±3.6 from one batch of 10,000 payments to the next. That is √(172 × 0.081 × 0.919), where √ is the square root: case file 2's wobble for a share, multiplied by the count. Finer bands would hold two or three frauds each and mean little, so teams pool months of history first.
Precision is an average over every flag at one threshold. One payment's chance depends on where its score sits, and a score becomes a probability only after calibration.
How good would the filter have to be before a flag means "probably fraud"?
"Probably" means more than 50%, so the real catches must outnumber the false alarms. With 68 real catches per 10,000 payments, the false-alarm rate would have to fall from 2% to under 0.69%. Or, keeping the filter as it is, fraud would have to be at least 2.3% of payments, almost three times today's 0.8%.
A flag means "more likely fraud than not" exactly when the fraud part of the alarm pile is bigger than the honest part. In the four counts, that means TP is bigger than FP. Today it is 68 against 198. There are two ways to close that gap: fewer false alarms, or more fraud to catch.
Route 1: keep the market, improve the filter
- Keep the top. The filter still catches 85% of 80 frauds: 68 real catches.
- Set the goal. False alarms must be fewer than 68.
- Turn the goal into a rate. 68 ÷ 9,920 honest payments = 0.69%. The filter may flag at most 0.69% of honest payments. Today it flags 2%, almost three times too many.
Route 2: keep the filter, change the market
- Write both parts of the alarm pile for a fraud share b. Out of all payments, real catches are 0.85 × b and false alarms are 0.02 × (1 − b). Here b is the base rate, written as a decimal.
- Set the two parts equal. 0.85 × b = 0.02 × (1 − b). Move the b terms to one side: 0.85 × b + 0.02 × b = 0.02, so 0.87 × b = 0.02.
- Solve. b = 0.02 ÷ 0.87 = 0.023, or 2.3%. In any market with less fraud than that, most of this filter's flags are honest customers.
Both routes compare the same two numbers. The honest pile is 9,920 ÷ 80 = 124 times bigger than the fraud pile, the "124×" in the caption of Fig. 1b.4. The filter's recall divided by its false-alarm rate is 0.85 ÷ 0.02 = 42.5. A flag becomes "probably fraud" only when the second number beats the first. Today it falls short by a factor of about 3.
- SaaSify today. Fraud is 0.8% of payments, and this filter's flags are 25.6% fraud. The accent curve shows what the same filter's flags would mean in any other market. Nothing about the filter changes along it; only the mix of payments does.
- The break-even. The accent curve crosses 50% at 2.3% fraud. Below that, most flags are honest customers, however good the filter sounds. SaaSify would need almost three times its current fraud before "a flag means probably fraud" became true.
- A stricter threshold. Case file 6's model at its 0.9 threshold catches only 60% of fraud, but false-alarms on just 0.5% of honest payments. Its curve sits higher, and at 0.8% fraud its flags are 49.2% fraud. It bought cleaner flags by missing more fraud.
- The one comparison. Both curves obey one rule. A flag is more likely fraud than not when recall ÷ false-alarm rate is bigger than honest payments ÷ fraud payments. At 0.8% fraud that bar is 124; this filter scores 42.5 and the strict setting 120.
Route 1 has a catch, and the thin curve in Fig. 1b.4g shows it. The usual way to cut false alarms is to raise the threshold, and that also cuts recall. Case file 6's model at its strict threshold catches 60% and false-alarms on 0.5%. Its ratio is 0.60 ÷ 0.005 = 120, just short of 124. At SaaSify's 0.8% its flags are 49.2% fraud: still not "probably".
On the 10,000 payments, that strict setting would catch 48 frauds and miss 32, against 68 caught and 12 missed today. Case file 6 priced the same kind of swap: at $500 a miss and $4 a look, the cleaner alarms cost about $135,000 a day more. Trustworthy flags and caught fraud pull in opposite directions.
The honest limit: 50% is not a magic line either. At exactly 50%, freezing every flag still freezes one honest card for every fraud it stops. Whether to freeze, review or let a flag through depends on what each mistake costs, not on the probability alone. Section 10 answers that question with expected value.
A flag means "probably fraud" only when recall ÷ false-alarm rate beats honest payments ÷ fraud payments. At SaaSify that is 42.5 against 124.
From memory: (1) Why did the do-nothing dummy beat the real model on accuracy? (2) Precision and recall — which one grades the alarms, and which one grades coverage of the real cases? (3) A spam filter catches 98% of spam. An email lands in your spam folder. Is the probability it is really spam 98%? What extra number do you need before you can answer?
Check your answers
(1) Because 99.2% of payments are legitimate, so "always say legit" is right 99.2% of the time — accuracy lets the enormous true-negative box drown the 800 frauds that matter.
(2) Precision grades the alarms (of all flags, how many were real); recall grades coverage (of all real cases, how many we caught). (3) No — 98% is P(flagged | spam), and you were asked P(spam | flagged).
You need the base rate of spam (and the false-alarm rate on legitimate mail); if spam is rare or the false-alarm rate is high, the folder can easily be full of real mail. Draw the tree.
08 · Lie 5"The Model Said 90%, So It's Nearly Certain"
Tile 5 said 400 accounts carried a 90% churn risk, and all 400 got an expensive win-back discount. A model's "90%" is a promise about frequency: of every ten accounts it stamps 90%, about nine should actually leave. Nobody checked whether this model keeps that promise. This section runs the check the way a weather forecaster's record is checked, and finds that the model's 90% is really closer to 73%, which means roughly 100 of those 400 discounts went to customers who were staying anyway.
Think about what a weather forecaster's "70% chance of rain" is actually promising. It is not a promise about tomorrow — tomorrow it either rains or it does not.
It is a promise about the forecaster's track record: of all the days they say "70%", it should rain on roughly seven in ten of them.
A forecaster who keeps that promise is called calibrated, and checking the promise is easy: collect every "70%" day from the past year and count how many were wet. If it rained on 68% of them — calibrated.
If it rained on 45% of them, the forecaster is overconfident: their stated certainty runs ahead of their actual skill. (National weather services are, in fact, famously well calibrated. Human experts asked for confidence off the cuff are famously not — "90% sure" from a person is right roughly 70% of the time.)
- The kept promise. Collect every day the forecaster said 70% and count the wet ones. Fourteen of twenty is 70%, so "70%" from this forecaster means what it says. That is what calibrated means, and it is a fact about a track record, not about any single day.
- The broken promise. Collect every time the person said "90% sure" and count. Fourteen of twenty is 70%, not the 18 of 20 they promised. Their stated certainty runs ahead of their actual skill, which is what overconfident means.
- What it costs on tile 5. The model stamped 400 accounts with 90%, and the team treated all 400 as near-certain losses. If the model is only as honest as the person, 120 of those accounts were never leaving, and the win-back discount sent to them was pure cost.
Every probability your models emit is making the same promise, and the Monday meeting never checked it. The churn model said "90%" for 400 accounts, and the team treated all 400 as near-certain losses, spending real discount money on that belief.
But a model's output layer produces numbers between 0 and 1 shaped like probabilities whether or not they are honest ones — nothing in the training process guarantees that "0.9" means "happens 9 times in 10".
The check is exactly the weather check, and it has a name: a reliability diagram. Bucket the predictions by stated confidence — all the "around 30%" predictions together, all the "around 70%" together — then, within each bucket, count how often the event actually happened.
Plot stated against actual. An honest model draws a diagonal line: said 30, happened 30; said 70, happened 70. An overconfident model draws a line flatter than the diagonal (marker 2 in Fig. 1b.5) — its extremes are exaggerated:
- The honest diagonal. Every point on the dashed line is a kept promise: said 30, happened 30; said 70, happened 70. A calibrated model's buckets sit on this line. Nothing about ranking is drawn here, only honesty.
- The overconfident model. Its buckets form a line flatter than the diagonal. At the low end it says 13 and reality delivers 28; at the high end it says 88 and reality delivers 73. Both ends are pulled toward the middle, because the model's certainty runs ahead of its skill.
- The 88% bucket. The circled point is tile 5's problem in one dot: the model said "around 88%" and the thing happened 73% of the time. The 400 accounts stamped 90% were treated as near-certain, and about a quarter of them were staying.
"Isn't calibration just accuracy with extra steps? If the model is right 90% of the time, its 90% is honest."
— an ML engineer who has shipped three classifiers and checked accuracy on all of them
No, and the two can disagree completely. Accuracy grades the yes-or-no decisions after you have picked a threshold. Calibration grades the probabilities themselves, before any threshold. A model that says 0.99 on every case, right or wrong, can be 90% accurate and badly calibrated: its "99%" happens 90% of the time. On Fig. 1b.5 that is a single point sitting below the honest diagonal (marker 1), further off than the circled 88%-to-73% bucket (marker 3).
The reverse is also possible. A model that says 0.8% for every single payment, the base rate, is perfectly calibrated and completely useless. Of all the payments it stamps "0.8%", exactly 0.8% are fraud, and it cannot tell any two payments apart. Calibration says nothing about ranking. That is why the reliability check and the ROC-AUC check are run separately in Module 02.
The honest downside of the calibration check: it needs volume. A reliability bucket with forty predictions in it has a wobble of several points, so a "said 70%, happened 64%" gap can be noise. And a calibrated model drifts the moment the base rate moves, which Lie 4 just showed you. Calibrate on the traffic you will actually serve, and re-check when that traffic changes.
The step-by-step list and the code below use the Brier score before this page has explained it. You are not expected to know it yet. The paragraph after the terminal output defines it in one sentence, and the pencil exercise that follows computes one by hand.
Step-by-step: what calibration_check.py does, in plain English
- Create a seeded random generator (seed 11) so the output is repeatable.
- Simulate 50,000 churn predictions: the model's stated confidences (
p_pred) are drawn uniformly between 5% and 95%. - Build a dishonest world on purpose: the actual churn probability (
p_true) is pulled 40% of the way back toward 50% from whatever the model said — so when the model says 90%, reality behaves like 74%; when it says 10%, reality behaves like 26%. This is what an overconfident model looks like from the outside. - For each prediction, flip a biased coin with the true probability to decide whether that customer actually churned.
- Group the 50,000 predictions into five confidence buckets (0–20%, 20–40%, and so on). For each bucket, print the average stated confidence next to the fraction of customers who actually churned — the reliability diagram as a table.
- Compute the Brier score — for every prediction, take (stated confidence − what happened)², where "what happened" is 1 for churned and 0 for stayed, and average all 50,000 of those squared gaps. Lower is better: 0 is a perfect prophet, 0.25 is what always-say-50% scores.
- Recompute the Brier score after a "calibration repair": each stated confidence is relabeled with the frequency that actually occurs when the model says it (the 90%s become 74%s). The score improves — same model, honest labels. This before/after is exactly what Module 02's lab asks you to produce with isotonic regression.
# pip install numpy
"""Is a '90%' really a 90%? -- checking a model's honesty, bucket by bucket."""
import numpy as np
rng = np.random.default_rng(11)
N = 50_000
# The model's stated confidence for 50,000 churn predictions.
p_pred = rng.uniform(0.05, 0.95, N)
# The world's ACTUAL behaviour: this model is overconfident. When it says
# 90%, reality behaves like 74%; when it says 10%, reality behaves like 26%.
p_true = 0.5 + 0.6 * (p_pred - 0.5)
happened = rng.random(N) < p_true # did the customer actually churn?
print("model said actually happened predictions")
for lo in (0.0, 0.2, 0.4, 0.6, 0.8):
hi = lo + 0.2
in_bucket = (p_pred >= lo) & (p_pred < hi)
said = p_pred[in_bucket].mean()
observed = happened[in_bucket].mean()
print(f" ~{said:4.0%} {observed:4.0%} {in_bucket.sum():8,}")
# Brier score: the average squared gap between stated confidence and reality.
# 0 is a perfect forecaster; 0.25 is what plain 50/50 guessing scores.
brier_before = np.mean((p_pred - happened) ** 2)
# "Calibration repair": relabel each stated confidence with the frequency
# that actually happens when the model says it (its 90% becomes 74%).
brier_after = np.mean((p_true - happened) ** 2)
print(f"\nBrier before repair: {brier_before:.3f} (0 = perfect, "
f"0.25 = coin-flip guessing)")
print(f"Brier after repair: {brier_after:.3f} (same model, honest labels)")
model said actually happened predictions
~ 13% 28% 8,361
~ 30% 38% 11,102
~ 50% 49% 11,108
~ 70% 61% 11,147
~ 88% 73% 8,282
Brier before repair: 0.237 (0 = perfect, 0.25 = coin-flip guessing)
Brier after repair: 0.226 (same model, honest labels)
Read the bucket table like a lie detector chart. In the middle bucket the model is honest — it says 50%, reality delivers 49%. But look at the edges: when it says "around 88%", the thing happens only 73% of the time, and when it says "around 13%", the thing happens 28% of the time. Both extremes are exaggerated toward certainty — the signature of overconfidence (the two end buckets in Fig. 1b.5b below). Concretely for the Monday meeting: of the 400 accounts labeled "90% churn risk", about 100 were never going to leave, and the win-back discounts sent to them were pure cost. Then the two Brier lines: the score is the average squared gap between stated confidence and reality, one number a team can put on a dashboard and watch. Repairing the labels — teaching the model that its "90%" is really a "74%", which is what isotonic regression does in Module 02's lab — improves the score without retraining anything. Notice also how close 0.237 sits to the 0.25 of blind guessing: this model's stated confidence, taken at face value, was barely more informative than a coin — even though its ranking of risky versus safe customers was genuinely useful. Ranking skill and honesty are separate virtues. ROC-AUC grades the first; calibration grades the second; a model can ace one and flunk the other.
- The buckets. Each dot is one bucket: the average confidence the model stated against the share of customers who actually churned. The middle dot sits on the honest line (said 50, happened 49). The two end dots do not.
- The 88% bucket. Said 88, happened 73. Every prediction in this bucket was treated as near-certain, and one in four of them was wrong. The 13% bucket is the mirror image: said 13, happened 28. The model exaggerates in both directions.
- The Brier arithmetic. For each prediction, take the gap between what was said and what happened (1 for churned, 0 for stayed) and square it. Four predictions, four squared gaps: 0.01, 0.49, 0.09, 0.01.
- The confident miss. One prediction, the 0.7 that stayed, contributes 0.49 of the 0.60 total. Squaring is what does this: a gap of 0.7 costs more than five times a gap of 0.3. The average, 0.15, beats a coin flip's 0.25; the real model's 0.237 barely does.
- What tile 5 paid. Four hundred accounts stamped 90%. If they behave like the 88% bucket, 292 churn and 108 stay. The win-back discounts sent to those 108 were spent on customers who were not leaving.
Questions you might be asking now
The code, the plot and the pencil exercise above used the Brier score three ways in a few screens. If the score still feels like an arbitrary formula, open the question that matches yours. Every answer uses the same five churn accounts, small enough to score with a pencil.
| Account | The model said | What happened next month | As a number |
|---|---|---|---|
| A | 0.90 | Churned | 1 |
| B | 0.90 | Stayed | 0 |
| C | 0.70 | Churned | 1 |
| D | 0.30 | Stayed | 0 |
| E | 0.10 | Stayed | 0 |
Why does the Brier score square the gap? Wouldn't the plain average gap be simpler?
Simpler, but it rewards exaggeration. Scored by the plain gap, a forecaster does best by rounding every prediction to 0 or 1, the exact overconfidence this section is hunting. Scored by the squared gap, the best strategy is to say the true chance. On calibration_check.py's 50,000 predictions, rounding to 0 or 1 wins on the plain gap and comes last on Brier.
Start with accounts A and B. The model gave both of them 0.90. In calibration_check.py's world we know something the model does not: the script's recipe says an account stamped 0.90 really churns 74% of the time. So picture a forecaster who knows that 74% and must choose a number to say. Which number earns the best score?
Here, "best score" means the lowest average penalty over many accounts like this one. Such an account churns 74% of the time, and then the gap is 1 minus the number said. It stays 26% of the time, and then the gap is the number said. Weight each case by how often it happens, and add.
- Say 0.74, the truth, scored by plain gap. 0.74 × (1 − 0.74) + 0.26 × 0.74 = 0.1924 + 0.1924 = 0.385.
- Say 1.00, pretend certainty, scored by plain gap. 0.74 × 0 + 0.26 × 1 = 0.260. That is lower than the truth's 0.385, so the plain gap prefers the exaggeration.
- Say 0.74, scored by squared gap. 0.74 × 0.26² + 0.26 × 0.74² = 0.74 × 0.0676 + 0.26 × 0.5476 = 0.0500 + 0.1424 = 0.192.
- Say 1.00, scored by squared gap. 0.74 × 0² + 0.26 × 1² = 0.260. That is higher than the truth's 0.192, so the squared gap prefers the truth.
- Say 0.90, what the model said. Plain gap: 0.74 × 0.10 + 0.26 × 0.90 = 0.308. Squared gap: 0.74 × 0.01 + 0.26 × 0.81 = 0.218. The plain gap praises the model's exaggeration; the squared gap charges for it.
Why does the plain gap behave like this? Its penalty changes in a straight line. Each step toward 1 shrinks the gap on the 74% of accounts that churn and grows it, by the same amount, on the 26% that stay. Since 74 beats 26, every step toward 1 lowers the average, all the way to the end.
Squaring bends that straight line. A small gap squared is tiny, and a large gap squared is big. Near the truth, a small move costs almost nothing either way. Far from the truth, the side you are betting against grows fast. The two pulls balance exactly at the true chance. Fig. 1b.5d draws both penalties for every number a forecaster could say.
- The squared gap is lowest at the truth. For an account that churns 74% of the time, the average squared penalty is lowest, 0.192, when you say exactly 0.74. Say more or less and it rises on both sides. Saying the true chance is the best strategy.
- The plain gap is lowest at certainty. The same account scored by plain gap gives a straight line that falls all the way to the right. Its lowest point, 0.260, is at 1.00: pretend the account is certain to churn. A score shaped like this teaches a model to exaggerate.
- The model's 0.90. The middle dot in each panel. The squared gap charges it 0.218, more than the honest 0.192. The plain gap scores it 0.308, better than the honest 0.385, so it would praise the very overconfidence that tile 5 paid for.
The same thing happens across the whole simulated year. The table scores three forecasters on calibration_check.py's 50,000 accounts, both ways.
| Forecaster | What it says | Brier score (squared gap) | Plain average gap |
|---|---|---|---|
| Honest | Each account's true chance, 0.23 to 0.77 | 0.226, best | 0.451, worst |
| The model | 0.05 to 0.95, overconfident | 0.237 | 0.419 |
| Exaggerated | 1 when the model said 0.5 or more, otherwise 0 | 0.368, worst | 0.368, best |
A scoring rule under which honesty is the best long-run strategy is called proper. The Brier score is proper, and the plain average gap is not. The log loss behind cross-entropy is proper too. That is the real reason for the square. It also punishes confident misses, as the pencil exercise showed, but that is a side effect.
The honest limit: "best at the truth" is a promise about averages over many accounts. On one account, the honest number can score worse than a wild guess. Account B was stamped 0.90 and stayed. Saying the honest 0.74 would have cost 0.74² = 0.55, while saying 0.10 would have cost only 0.01. The Brier score pays honesty back over volume, never case by case.
The Brier score squares the gap so that saying the true chance is the best long-run strategy. A plain average gap would reward rounding every prediction to 0 or 1.
The script printed 0.237 before the repair and 0.226 after. Is that a big change, and what does a Brier score actually tell me?
A Brier score only means something next to the score of a forecaster who knows nothing but the base rate. For churn at about 50%, that forecaster scores 0.25. The model's 0.237 is 0.25, minus 0.024 that its ranking removes, plus 0.011 that its exaggeration adds back. A calibration repair can remove only the 0.011.
Step 1: score the five accounts by hand
- Square each gap. A: (0.90 − 1)² = 0.01. B: (0.90 − 0)² = 0.81. C: (0.70 − 1)² = 0.09. D: (0.30 − 0)² = 0.09. E: (0.10 − 0)² = 0.01.
- Average them. (0.01 + 0.81 + 0.09 + 0.09 + 0.01) ÷ 5 = 1.01 ÷ 5 = 0.202.
- Find the know-nothing score. Two of the five churned, so the base rate is 0.40. A forecaster who says 0.40 for everyone scores 0.40 × 0.60 = 0.240. That shortcut, b × (1 − b), works for any base rate b.
- Compare the two. 1 − 0.202 ÷ 0.240 = 0.158. The model beats knowing only the base rate by 15.8%. This ratio is called the Brier skill score.
Steps C and D are the habit worth keeping. The number 0.202 alone says nothing. It means "some skill" only next to 0.240, the score earned by knowing the base rate and nothing else. On five accounts it is also fragile: B's one confident miss supplies 0.81 of the 1.01, so one more account could swing the verdict.
Step 2: what 0.237 is made of
On calibration_check.py's 50,000 accounts we can do more than compare, because the script knows each account's true chance. That lets the score split into three parts. Their textbook names are uncertainty, resolution and reliability. The table gives each one a plain name, and the three add up, to four decimals, to the measured score.
| Part | What it measures | How it is computed | Value |
|---|---|---|---|
| Know-nothing score (uncertainty) | How unpredictable churn is when about half the customers leave | b × (1 − b), with churn rate b = 0.497 | 0.2500 |
| Removed by ranking (resolution) | How far apart the accounts really are: true chances from 0.23 to 0.77 | The variance of the true chances | − 0.0243 |
| Added by exaggeration (reliability) | How far the stated numbers sit from the true chances | The average of (stated − true)² | + 0.0108 |
| The model's Brier score | All three together | 0.2500 − 0.0243 + 0.0108 | 0.2365, printed as 0.237 |
Now the two printed lines make sense. The repair swaps the stated numbers for honest ones, so it deletes the exaggeration part: 0.2365 − 0.0108 = 0.2257, printed as 0.226. It cannot touch the ranking part. Only a model that tells customers apart better, usually through better features, can remove more than 0.024.
It also explains the puzzle in the paragraph after the code: a score close to a coin flip from a model that ranks well. The ranking is real, but even the honest chances only run from 23% to 77%. No account is close to certain, so perfect honesty still leaves 0.226. Here "close to 0.25" says churn is hard to predict, not that the model is broken.
- Knowing nothing. Say 50% to every account and each squared gap is 0.25, whatever happens. With churn at 49.7%, that is also the score of always saying the base rate: b × (1 − b) = 0.250. Every other bar in this panel is read against this one.
- What ranking removes. Use each account's true chance instead, 0.23 to 0.77, and the score drops by 0.024 to 0.226. The drop is the variance of the true chances: how far apart the accounts really are. Only better features can widen that spread.
- What exaggeration adds. The model states 0.05 to 0.95 where the truth runs from 0.23 to 0.77. The squared distance between the two, averaged, adds 0.011 back. This red sliver is all a calibration repair can remove, which is why 0.237 becomes 0.226.
- The rare-event baseline. For fraud at 0.8%, knowing only the base rate scores 0.008 × 0.992 = 0.0079. That is about thirty times smaller than the churn baseline, so a fraud model's Brier score must be judged against 0.0079, never against 0.25.
- Tile 4's rule as a forecast. "A flag means fraud" says 100% or 0%, and it is wrong by a full 1 on 198 false alarms and 12 misses: 210 ÷ 10,000 = 0.021. That looks tiny next to 0.237, yet it is about 2.6 times worse than saying 0.8% for every payment.
Step 3: the baseline moves with the base rate
The script's comment calls 0.25 "coin-flip guessing". That is the know-nothing score only when half the customers churn. For a rare event, b × (1 − b) is tiny. For the fraud of Fig. 1b.4 it is 0.008 × 0.992 = 0.0079. So a fraud model scoring 0.02 looks ten times better than the churn model, and is worse than knowing nothing.
Tile 4's rule is exactly such a model. Read "a flag means fraud" as a forecast: 100% for every flagged payment and 0% for the rest. It is wrong by a full 1 on the 198 false alarms and the 12 misses. Its Brier score is (198 + 12) ÷ 10,000 = 0.021, about 2.6 times worse than always saying 0.8%.
The honest limit: a Brier score rolls ranking and honesty into one number. Two models can tie on it for opposite reasons, one sharp but exaggerated, one honest but vague. When the score moves, the reliability buckets of Fig. 1b.5b show whether honesty moved. Read the score and the buckets together, and always next to b × (1 − b).
Compare a Brier score only with b × (1 − b), the score of knowing just the base rate. A calibration repair removes the exaggeration part; only better ranking removes the rest.
Walk one account through the repair: the model says 90%. What number comes out, and does that account still get the discount?
The 0.90 lands in the 80–100% bucket, where 73.1% of last year's customers churned, so it comes out as 0.73. Under case file 4's offer economics the discount still pays, but its expected profit falls from $21.00 to $5.70. Account C's 0.70 comes out as 0.61, below the 66.7% break-even, and loses its offer.
The repair in calibration_check.py took a shortcut: it used each account's true chance, which only a simulation knows. The simplest repair a real team can build is bucket relabelling. It needs nothing but last year's predictions and what happened. The script repair_one_account.py builds one and walks accounts through it, station by station.
Account B, stamped 0.90
- Read the model's number. 0.90. Taken at face value, B churns nine times in ten.
- Find its bucket. Last year's predictions were sorted into five buckets, each 0.2 wide. A 0.90 falls in the top bucket, 0.8 to 1.0.
- Read last year's record for that bucket. 8,282 predictions landed there. They averaged a stated 87.6%, and 73.1% of those customers actually churned. This is the last row of the terminal output above.
- Relabel. Replace 0.90 with the bucket's record, rounded: 0.73. Every account in that bucket gets the same 0.73, whether the model said 0.81 or 0.94.
- Price the offer. Case file 4's discount costs $60 and rescues 30% of customers who were really leaving, each worth $300. One offer is worth p × 0.30 × $300 − $60, which is p × $90 − $60, where p (the churn chance) is the number you trust.
- At face value. 0.90 × $90 − $60 = +$21.00 per offer.
- Repaired. 0.73 × $90 − $60 = +$5.70 per offer. Still worth sending, at about a quarter of the promised profit.
Account C, stamped 0.70
- Find its bucket. 0.6 to 0.8. Last year 11,147 predictions landed there, and 61.2% of those customers churned.
- Relabel. 0.70 becomes 0.61.
- Price the offer. At face value: 0.70 × $90 − $60 = +$3.00. Repaired: 0.61 × $90 − $60 = −$5.10. The offer now loses money on average.
- Compare with the break-even. An offer pays when p × $90 is more than $60, so when p is above $60 ÷ $90 = 66.7%. The model's 0.70 cleared that bar; the honest 0.61 does not.
- The model's number. What the churn model printed for each account. Both numbers are too confident: this model's high numbers overstate what happens, as the two right-hand buckets of Fig. 1b.5b showed.
- The bucket. Last year's predictions sorted by what the model said, in five bands 0.2 wide. The account is matched to the band its number falls in. Nothing else about the account is looked at.
- Last year's record. How many predictions landed in that band, and how many of those customers churned: 73.1% of 8,282 and 61.2% of 11,147. With thousands of predictions per band, a rate like 73.1% wobbles by only about ±0.5 points.
- The relabelled number. The record replaces the model's number. The order between buckets is kept, so a 0.90 still outranks a 0.70, but accounts inside one bucket become tied. The numbers are now honest on average.
- The offer. Case file 4's economics: p × $90 − $60 per offer, positive above 66.7%. Account B's offer shrinks from +$21.00 to +$5.70 and is still sent. Account C's flips from +$3.00 to −$5.10, and the offer is not sent.
Now scale that up to tile 5, assuming its discount had case file 4's economics. If all 400 accounts behave like the top bucket, the campaign's expected profit falls from 400 × $21.00 = $8,400 to 400 × $5.70 = $2,280.
That margin is thin enough to flip on a small error. If the offer rescues 25% of leavers instead of 30%, each offer is worth 0.73 × 0.25 × $300 − $60 = −$5.25, and the whole campaign loses money.
Across all accounts, the repair changes many decisions. On a fresh year of 50,000 accounts from the same world, the model's face values would send offers to 31.6% of accounts. The repaired numbers send them to 16.6%. For 15.1% of all accounts, about one in seven, the decision flips from "send" to "don't send".
Did the repair work on data it had never seen? It was built from last year's 50,000 and scored on the fresh year. The Brier score went from 0.2369 as the model speaks to 0.2272 after relabelling. The unreachable ideal, using the true chances, is 0.2261. Five coarse buckets captured about 90% of the possible improvement.
Isotonic regression, the repair Module 02's lab uses, is the same idea with smarter buckets. It chooses the bucket edges from the data, and it guarantees that the repaired numbers never go down as the model's number goes up. The honest limits apply to both.
- One account can get worse. In the five-account table, A, C, D and E all score worse after relabelling. Only B's large gain makes the average better, 0.202 to 0.196.
- A bucket needs volume. From 40 predictions instead of 8,282, a 73.1% rate would wobble by about ±7 points, enough to flip account B's offer.
- The record goes stale. If the churn rate moves, last year's 73.1% is simply wrong. The buckets must be rebuilt on recent outcomes, the same warning the bubble above gave.
A calibration repair swaps the model's number for last year's track record at that number. It keeps the ranking and changes every decision that uses the number, here the offer for about one account in seven.
When does this matter? Every time a probability crosses from the model into a decision that mixes it with money or risk: expected-value math (next-but-one section) multiplies payoffs by these probabilities, Module 12 routes low-confidence answers to humans, Module 14 defines fairness partly as "calibrated within every group", and Module 16 puts "wrong-answer rate below 1-in-25" into client contracts. Uncalibrated probabilities poison all of it silently — the dashboards stay green while the arithmetic underneath is fiction.
A probability is a promise about frequency: of all the times you say 70%, the thing should happen seven times in ten. Check the promise like a weather forecaster's record — bucket by stated confidence, count reality. Ranking well and being honest are different skills; test them separately.
09 · Lie 6"Dashboard Users Churn Less, So the Dashboard Retains Customers"
Tile 6 said customers who use the new dashboard churn half as much, and the dashboard was made mandatory. The correlation is real and would reproduce every quarter. What the team needs to know is whether making people use the dashboard would change their churn, which is a different claim. This section shows a hidden third thing, engagement, driving both numbers, with code that measures a correlation of +0.84 and then watches it collapse to +0.10 once the third thing is removed.
In beach towns, ice cream sales and drowning deaths rise and fall together, year after year, with remarkable reliability. Nobody concludes that ice cream causes drowning.
The explanation is obvious the moment you say it out loud: hot weather sends people to buy ice cream, and hot weather sends people swimming. The two numbers share a cause; neither causes the other.
Obvious with ice cream — yet swap in business nouns and the same structure fools entire leadership teams. "Customers who use the new dashboard churn half as much" has identical anatomy: engaged, invested customers are exactly the people who both explore new dashboards and stick around.
Engagement is the hot weather. Making the dashboard mandatory is selling ice cream to stop drownings.
The number behind "move together" is the correlation coefficient, written r: +1 means perfect lockstep, −1 means a perfect see-saw (one rises exactly as the other falls), 0 means no straight-line relationship at all.
It is a genuinely useful measurement — Module 02 uses it to find promising features, Module 13 uses it to describe how popularity feeds on itself. The trap is a single silent word-swap: r measures moves-together, and every human brain that hears it whispers causes.
- Lockstep, r = +1. Every point on one rising line. Know one quantity and you know the other exactly. Nothing in real data looks this clean.
- Unrelated, r = 0. Knowing one quantity tells you nothing about the other. The points are placed so the ups and downs cancel exactly. This is what tile 6's dashboard-versus-churn numbers would look like if the two had nothing to do with each other.
- See-saw, r = −1. One rises exactly as the other falls. Correlation runs from −1 through 0 to +1, and the sign says the direction, the size says the tightness.
- The real cloud, r = +0.84. Forty-eight months of ice cream sales and drownings. The cloud leans up and right, tightly enough for r to read +0.84. This is a true fact about the numbers, and it would reproduce every year you re-measured it. What it does not say is that either one causes the other.
The classic hidden structure has a name — a confounder, a third variable that drives both of the two you happened to plot:
Step-by-step: what correlation_trap.py does, in plain English
- Create a seeded generator (seed 5) for repeatable output.
- Build 48 months of city weather: temperature follows a yearly sine wave (hot summers, cool winters) plus a little random noise.
- Construct ice cream sales and drownings so that each depends only on temperature plus its own unrelated noise — by construction, neither has any effect on the other. We know the ground truth because we wrote it.
np.corrcoefcomputes the correlation coefficient r between ice cream and drownings across the 48 months — it comes out strongly positive, because summer lifts both.- Now "control for temperature": fit a straight line predicting ice cream from temperature (
np.polyfit), and keep only each month's leftover — how far actual sales were above or below what temperature alone predicts. Do the same for drownings. The leftovers (called residuals) are the parts of each series that temperature cannot explain. - Correlate the two leftover series. If ice cream truly influenced drowning, the link would survive. It collapses to almost zero — the entire correlation was the confounder's doing.
# pip install numpy
"""Ice cream does not cause drowning -- finding the hidden third variable."""
import numpy as np
rng = np.random.default_rng(5)
# 48 months of city data. Temperature swings with the seasons.
months = np.arange(48)
temperature = 22 + 12 * np.sin(2 * np.pi * months / 12) + rng.normal(0, 2, 48)
# BOTH of these are driven by temperature -- and by nothing else.
ice_cream_sales = 20 + 2.5 * temperature + rng.normal(0, 8, 48)
drownings = 1 + 0.15 * temperature + rng.normal(0, 0.8, 48)
r = np.corrcoef(ice_cream_sales, drownings)[0, 1]
print(f"correlation(ice cream, drownings) r = {r:+.2f}")
# Remove temperature's influence from both series (keep only the part
# each series does NOT owe to temperature), then correlate what's left.
ice_resid = ice_cream_sales - np.polyval(
np.polyfit(temperature, ice_cream_sales, 1), temperature)
drown_resid = drownings - np.polyval(
np.polyfit(temperature, drownings, 1), temperature)
r_controlled = np.corrcoef(ice_resid, drown_resid)[0, 1]
print(f"same, after removing temperature's effect r = {r_controlled:+.2f}")
correlation(ice cream, drownings) r = +0.84
same, after removing temperature's effect r = +0.10
Two output lines, one autopsy. The raw correlation is +0.84 — strong, stable, and it would reproduce every year you re-measured it. This is worth sitting with: the correlation is not a statistical fluke, and collecting more data would only make it more solid. It is a true fact about the numbers and a false suggestion about the world. The second line removes temperature's influence from both series and correlates the leftovers: +0.10, statistical dust. The entire relationship flowed through the confounder. Now the honest caveat: in real life you cannot "control for" a confounder you have not measured — and the dangerous confounders (engagement, customer intent, patient frailty) are precisely the ones nobody logged. That is why the gold standard is not cleverer arithmetic but an experiment: randomly assign who gets the dashboard and who does not, and randomness severs every possible confounder at once, because coin flips are correlated with nothing. That is exactly what an A/B test is — Module 01's machinery was built for precisely this moment — and it is why "correlational study" and "randomized experiment" carry such different weight everywhere from medicine to growth teams. Correlation is still valuable: it is how you find candidates for causation (and Module 14 shows its dark side — a "harmless" zip-code feature correlating with a protected attribute). The discipline is refusing to let a candidate graduate to a cause without an experiment.
- The triangle. Two real causal arrows come down from the top; the dashed edge along the bottom is what the dashboard measured. Read tile 6 onto it: engagement at the top, dashboard use and staying subscribed at the bottom, "churn half as much" on the dashed edge.
- Remove the top and the edge collapses. Fit each bottom series to temperature, keep only the leftovers, and correlate those: +0.10, statistical dust. All of the +0.84 was temperature's doing. In real life the top of the triangle is often something nobody logged, and then this subtraction is impossible.
- The coin. Randomly assign who gets the dashboard. Now engagement cannot choose who is in which group, so its arrow into the left box is cut, and so is every other confounder's, including the ones nobody thought of. Compare churn between the two groups and the difference is causal. That is an A/B test, and it is what Module 01 built.
Correlation says "these move together", never "this moves that". Before acting on any correlation, hunt the third thing that could drive both — and remember that only randomization truly kills confounders, which is what A/B tests are for.
10 · The payoffDeciding With Numbers — Expected Value
Six tiles, six lies, and the team now holds honest versions of each number: a median of 4.5 minutes, a wobble of ±10 points, a precision of 26%, a 90% that is really 73%. Honest numbers still have to become decisions, and the sharpest one on the table is tile 3's: was cutting the $3.50-a-flag review team the right call? This section turns a probability and a cost into one dollar figure, expected value, and sweeps the assumptions to see whether the verdict survives being wrong.
Everything so far has been defense — catching numbers that lie. This section is offense: the one-line tool that turns honest probabilities into decisions. Start with the everyday version. An insurance company offers to protect your $800 phone for $79 a year. Should you buy?
You never know what will happen — but you can average over what could happen. Suppose phones like yours die or vanish about 5% of the time per year. Then going uninsured costs, on average, 5% × $800 = $40 a year.
The insurance costs $79, guaranteed. Averaged over many years — or many phones — insurance loses you $39 a year, which is exactly how insurers stay in business.
That average-over-possibilities is called expected value, written E[X] and read "expected value of X": each outcome, times its probability, summed up. It is what the number "would be worth per repetition if you played this gamble many times".
(The name is misleading in one way: E[X] is often a value you never actually receive on any single play — no year costs you exactly $40. It is a long-run rate, not a prediction of one outcome.)
- A hundred years. You cannot know which year the phone dies, but you can count over a hundred years like this one: about 5 bad years at $800 each is $4,000, which is $40 a year. That per-year rate is the expected value of going uninsured.
- The certain price. Insurance costs $79 every year, bad or good. Against a $40 risk, buying it loses $39 a year on average, which is exactly the insurer's margin. Expected value is a long-run rate, not a prediction of any single year.
- A hundred flags. One flag is fraud 26 times in 100. Skip the review on all hundred and about 26 chargebacks at $420 arrive: $10,920, or $109.20 per flag. That is what one skipped review costs on average.
- The look. A human review costs $3.50 per flag, thirty-one times less than the expected loss from skipping it. Cutting the review team was wrong by a factor of 31 even at a mediocre 26% precision, and the code below checks whether that verdict survives worse assumptions.
Two honest footnotes before the code, because expected value has famous failure modes. First: it needs calibrated probabilities — feed it the overconfident "90%"s from Lie 5 and it launders fiction into confident-looking arithmetic. Second: it assumes you can afford to play many times.
Averages are for repeatable, survivable bets — flags to review, emails to send, tickets to route.
For a one-shot bet that could end the company, the worst case matters more than the average, which is why Module 16 teaches sensitivity tables ("what if we're wrong by 2×?") and leads every client conversation with the pessimistic scenario.
The code below does both things at once — expected value at the center, a range of assumptions around it:
Step-by-step: what expected_value.py does, in plain English
- Fix the two business constants: a fraud that slips through costs $420 on average (the chargeback), and a human review of one flagged payment costs $3.50 of analyst time.
- Define
decide, which takes one assumption — the precision of the flags, i.e. the probability that a flagged payment really is fraud (from Lie 4's tree: about 26%). - Inside, compute the expected cost of skipping the review: precision × $420 — the chargeback, weighted by how often it would actually occur.
- Compare that to the certain $3.50 review cost and print the verdict: review when the expected loss exceeds the review cost.
- Run the decision across pessimistic / measured / optimistic precision values (10%, 26%, 45%) — a sensitivity sweep, so the recommendation shows whether it survives being wrong about the assumption.
- Run it again for a future low-fraud world where flags are almost never right — and watch the same arithmetic flip to "skip", finding the break-even point near 0.8%.
# no installs needed -- pure Python
"""Should a human review every fraud flag? Decide with expected value."""
CHARGEBACK_COST = 420.0 # average loss if a fraudulent payment slips through
REVIEW_COST = 3.50 # analyst time to manually check one flagged payment
def decide(precision: float) -> None:
"""Compare the expected cost of reviewing vs auto-approving one flag."""
# If we skip review, we eat the chargeback whenever the flag was right.
expected_loss_if_skipped = precision * CHARGEBACK_COST
verdict = "REVIEW" if expected_loss_if_skipped > REVIEW_COST else "skip"
print(f" precision {precision:5.1%}: expected loss if skipped "
f"${expected_loss_if_skipped:6.2f} vs review cost ${REVIEW_COST:.2f}"
f" -> {verdict}")
print("Is a $3.50 human review worth it, per flagged payment?\n")
print("pessimistic / measured / optimistic precision of the flags:")
for precision in (0.10, 0.26, 0.45):
decide(precision)
print("\nand for a future low-fraud market where flags are rarely right:")
for precision in (0.005, 0.008, 0.02):
decide(precision)
Is a $3.50 human review worth it, per flagged payment?
pessimistic / measured / optimistic precision of the flags:
precision 10.0%: expected loss if skipped $ 42.00 vs review cost $3.50 -> REVIEW
precision 26.0%: expected loss if skipped $109.20 vs review cost $3.50 -> REVIEW
precision 45.0%: expected loss if skipped $189.00 vs review cost $3.50 -> REVIEW
and for a future low-fraud market where flags are rarely right:
precision 0.5%: expected loss if skipped $ 2.10 vs review cost $3.50 -> skip
precision 0.8%: expected loss if skipped $ 3.36 vs review cost $3.50 -> skip
precision 2.0%: expected loss if skipped $ 8.40 vs review cost $3.50 -> REVIEW
The first block is the useful kind of boring: even under the pessimistic assumption — flags right only 10% of the time — the expected loss from skipping ($42) dwarfs the $3.50 review. A recommendation that survives its own pessimistic case is one you can defend in any meeting; that is what a sensitivity sweep buys, and it is why the Monday team's decision to cut the review team was wrong even though their precision was mediocre. The second block shows the same arithmetic changing its mind honestly: when flags are almost never right, $3.50 per flag stops paying for itself, with the break-even near 0.8% precision. Notice what expected value really did here: it converted three statistical quantities you now own — a precision (Lie 3), which is really a conditional probability P(fraud | flag) (Lie 4), which must be calibrated to mean anything (Lie 5) — into dollars, the only unit executives share. Module 02 uses this exact move to set a profit-maximizing threshold, Module 15 prices AI dev-tooling with it, and Module 16 builds entire consulting engagements on it.
- The rising line. Each point is one row of the first terminal block: at 10% precision a skipped review costs $42 on average, at 26% it costs $109.20, at 45% it costs $189. The pessimistic assumption is the leftmost point, and it is still twelve times the review cost.
- The flat line. A human look costs $3.50 whatever the precision. A recommendation that survives its own pessimistic case, $42 against $3.50, is one you can defend in any meeting. That is what the sweep buys.
- The zoom. The second terminal block lives down here, in a market where flags are almost never right. At 0.5% precision a skipped review costs $2.10, less than the look, so the arithmetic honestly says skip. At 2% it says review again.
- The break-even. The lines cross where precision × $420 = $3.50, at 0.83%. Above it, review; below it, skip. Move the chargeback or the review cost and the crossing moves with it, which is the sensitivity a one-shot gut call never shows you.
Expected value = each outcome × its probability, added up — the cost per play of the long run. Use it for repeatable, survivable bets with calibrated probabilities; sweep the assumptions to see if the verdict survives pessimism; and never use a naked average for a bet you can only afford to lose once.
11 · Under the hoodThe Math, If You Want It
The six tiles have been audited by counting and drawing. The formulas behind the counting are here for readers who want them: Bayes' rule is Fig. 1b.4's tree written as algebra, the √n rule that would have shrunk tile 2's ±10 wobble comes from the way variances add, and the loss function Module 02 will train with is the same idea of surprise. Nothing in the Monday memo needs these blocks. Everything in the later modules does.
Bayes' rule — the frequency tree as one line of algebra
Everything Fig. 1b.4 did by counting people compresses into:
P(fraud | flag) = P(flag | fraud) × P(fraud) ÷ P(flag)
Symbol key: P(fraud | flag) is the answer you want — the probability of fraud given a flag (the | bar reads "given"); P(flag | fraud) is the model's recall (0.85); P(fraud) is the base rate, the prior belief before evidence (0.008); P(flag) is how often flags happen at all, from both sources combined — real catches plus false alarms: 0.85 × 0.008 + 0.02 × 0.992 = 0.0266.
Plug in: 0.85 × 0.008 ÷ 0.0266 ≈ 0.256 — the same 26% the tree gave. Read the formula as a recipe: start from the base rate, scale up by how strongly the evidence points at fraud, scale down by how common the evidence is overall.
Rare evidence that strongly favors the hypothesis moves belief a lot; common evidence moves it barely at all.
That prior → evidence → posterior loop is the "Bayesian" reasoning you will meet again in Module 08 (a model's prior beliefs fighting retrieved context) and Module 13 (Thompson sampling, which chooses actions by sampling from posterior beliefs).
Why variances add (and standard deviations don't)
For independent sources of noise, variances add: σ²_total = σ²_a + σ²_b. Symbol key: σ² ("sigma-squared") is the variance, the squared typical wobble; the subscripts name the two independent noise sources.
Standard deviations do NOT add — combining a wobble of 3 with a wobble of 4 gives √(9 + 16) = 5, not 7, because independent wobbles partly cancel: when one noise source pushes up, the other is as likely pushing down.
- The triangle. Square each wobble, add the squares, take the root: √(9 + 16) = 5. The squares are the variances, and those add. The wobbles themselves do not, because when one noise source pushes up the other is as likely to push down, so they partly cancel.
- The √n rule, seen once. Four measurements, each ±10. Their average has one quarter of the variance, and one quarter of a variance is half a wobble: ±5. This is the whole reason Fig. 1b.1d's bars halve every time the eval quadruples, and why Module 03's ensembles average many trees.
This one fact explains the chapter's recurring √ (square root): average n independent measurements and the variance of the average shrinks by n, so the standard deviation — the wobble you actually experience — shrinks by √n. Four times the data, half the wobble.
It is also why Module 03's ensembles average many trees (independent errors cancel), and why correlated errors — trees that share a blind spot, eval questions that share a topic — put a hard floor under how much averaging can help: ρσ² in Module 03's formula is exactly the part that refuses to cancel.
Surprise, entropy, and cross-entropy — the loss function you'll meet in Module 02
Information theory measures surprise as −log p ("minus log p"): an event with probability 1 carries zero surprise, an event at p = 0.01 carries a lot, and an event the model called impossible (p = 0) carries infinite surprise.
- The curve. Every prediction the model makes is scored by how much probability it gave to what actually happened. Give it p = 1 and you are not surprised at all. Give it p = 0.5, a coin flip, and the surprise is 0.69.
- Confident wrongness. Give the true outcome p = 0.01, because the model was 99% sure of something else, and the surprise is 4.61, seven times the hedge. Give it p = 0 and the surprise is infinite. This is why training on cross-entropy punishes overconfidence so hard, and why tile 5's overconfident 90%s would have been expensive on this scale too.
- No surprise. The right end. A model that always gives the true outcome a probability near 1 has near-zero cross-entropy. Training "to minimise cross-entropy" means walking every prediction toward this end of the curve.
Symbol key: p is the probability assigned to the event that actually happened; log is the logarithm (the "how many doublings" function); the minus sign flips small probabilities into big surprises. Entropy is a distribution's average surprise — how unpredictable it is overall.
Cross-entropy is the average surprise you feel when reality follows one distribution but you bet using another — always at least the true entropy, and bigger the wronger your beliefs.
That is why cross-entropy is the standard training loss in Modules 02, 04, and 05: training a model to minimize cross-entropy literally means "be as unsurprised by reality as possible", and it punishes confident wrongness savagely because −log p explodes as p → 0.
The gap between cross-entropy and true entropy — the extra surprise caused purely by wrong beliefs — is the KL divergence, the standard "distance between two distributions".
When Module 12's PSI monitors drift, it is a symmetrized KL divergence asking "how much extra surprise is today's traffic, measured against last month's beliefs?"
Monte Carlo — the name of the trick this course keeps using
Three times now, a script in this course has answered a hard probability question by simulating it many times and counting: Module 01's 10,000 parallel- universe evals, Module 07's simulated null runs, and this chapter's 50,000 simulated churn predictions.
The technique is called Monte Carlo simulation (named for the casino): when the formula is hard or unknown, generate thousands of random scenarios from the assumptions, measure the outcome in each, and let the counts approximate the answer.
Its accuracy improves with the same √n law as everything else — 100× the simulations for 10× the precision — which is cheap, because simulations are just a for-loop.
It is the standard
tool for questions with awkward shapes ("what's the p99 of this whole pipeline
if each stage has this latency distribution?") and you now have a name for the
pattern every time you see rng inside a loop.
12 · When to use whatThe Cheat Sheet
The memo to the CEO is nearly written. What the team needs now is the one-page version to keep on the wall: for each question a dashboard tile could be asking, the tool that answers it and the story that anchors it, from the 241-minute ticket to the $79 phone insurance. This table is that page, and it is also the thing to come back to tomorrow.
This is the table to revisit tomorrow, and again in a week — recall practice disguised as a reference. Cover the right-hand columns and quiz yourself from the left: what question does this answer, and what's the anchor story?
| You're asking… | Reach for | Anchor story | Where you'll use it |
|---|---|---|---|
| What's typical? | Median (mean only if no heavy tail) | The overnight ticket dragging "28 minutes" (Fig. 1b.1b) | Latency, cart values, handling times (M02, M16) |
| How bad for the unlucky? | Percentiles p90/p95/p99 | The angriest user's screenshot | SLOs, monitoring (M01, M06, M12) |
| How much does it wobble? | Standard deviation s; CIs for scores | The café's good days and bad days | Eval scores, cv_scores ± (M01, M02, M07) |
| Is this value unusual? | z-score (value − mean) ÷ s | "How many moods away from normal?" | Feature scaling, anomaly alerts (M02, M12) |
| What shape will this data have? | Ask how it was made (add/count/wait/multiply) | Multiplication breeds monsters (the 907) | Synthetic data, alert design (M02, M12, M13) |
| Is this difference real or luck? | Hypothesis test + CI + sample size | The $180K meeting (Module 01) | A/B tests, model comparisons (M01, M07) |
| Is this classifier any good? | Four boxes → precision & recall, vs dummy | The do-nothing model that scored 99.2% | Fraud, churn, judges (M02, M03, M07, M17) |
| The alarm fired — now what? | Base rate + frequency tree (Bayes) | 510 positives, 10 sick — count people | Alerts, moderation, medical-grade claims (M07, M12, M14) |
| Can I trust its "90%"? | Reliability diagram + Brier score | The weather forecaster's track record | Churn scores, routing to humans (M02, M12, M14) |
| Does X actually drive Y? | Suspect a confounder; randomize (A/B) | Ice cream and drownings share a summer | Feature "wins", product claims (M01, M13, M14) |
| Is this bet worth it? | Expected value + sensitivity sweep | The $79 phone insurance | Thresholds, review queues, ROI (M02, M15, M16) |
| Formula too hard? | Monte Carlo — simulate and count | 10,000 parallel universes | Eval variance, pipeline p99 (M01, M07) |
There are no dumb questions
- Do I need to memorize the formulas, or derive them in interviews?
- Neither, with one exception. Interviewers for AI engineering roles probe whether you reach for the right tool and read its output honestly — "why is accuracy misleading here?", "what would you check before trusting this probability?" — not whether you can derive the normal distribution. The exception is precision and recall: be able to define both cold, in plain words, with the four boxes on a whiteboard. That one comes up verbatim.
- How big does a sample need to be? Is 30 the magic number?
- There is no magic number — "n = 30" is folklore. The honest answer is that the sample you need depends on the size of the effect you are trying to see and the wobble of the data: detecting a big effect in calm data takes dozens, while detecting a small lift in noisy conversion data takes thousands (Module 01's calculator told you: 2,028 per arm for a 3-point lift). The reflex to build is not "is n ≥ 30?" but "is my wobble small compared to the difference I care about?" — which is a question the sample-size calculator answers before you start.
- If the mean is so fragile, why does anyone use it?
- Because the mean connects to totals, and totals are money. Mean revenue per user × users = total revenue; median revenue per user × users = nothing useful. Finance, capacity planning, and cost models genuinely need means. The rule is to match the summary to the question: money and totals → mean; typical experience → median; promises about the worst cases → percentiles. The lie is never the mean itself — it is presenting a mean as if it described a typical case.
- My model's probabilities are miscalibrated. Is the model garbage?
- No — ranking and honesty are separate skills. A model can order customers from safest to riskiest brilliantly (high ROC-AUC) while its stated probabilities all run too hot. If you only need ordering — "review the top 300" — miscalibration is harmless. The moment probabilities enter arithmetic (expected value, alert thresholds, "tell the customer 90%"), repair them: isotonic regression or Platt scaling, both one-liners in scikit-learn, both in Module 02's lab. Repair is cheap; retraining is not required.
- When is correlation actually enough to act on, without an experiment?
- When the cost of being wrong is small and reversible — reordering a menu by what correlates with clicks risks little. Correlation also legitimately powers prediction: a proxy that merely correlates with churn still predicts churn (Module 02 is built on this). The dividing line is intervention: the moment you plan to change X hoping Y follows — mandate the dashboard, ban the ice cream — you are claiming causation, and that claim needs randomization or, at minimum, a hunt for confounders you can name and measure.
Statistical literacy is cheap insurance against expensive confidence. The pitch: "Module 01 saved $180K by asking one question of one A/B test. This chapter is the other five questions — the ones that catch a misleading average, a fake accuracy number, an alarm system nobody trusts, a probability nobody checked, and a correlation about to become a mandate. Every one of those has a five-figure mistake attached at our scale." The elevator version: we don't make the numbers — we make sure the numbers aren't lying before we spend on them.
13 · The labThe Six-Lies Audit
You have watched the SaaSify team's six decisions fail and seen the number that should have replaced each tile: 4.5 minutes instead of 28, a wobble instead of a win, four boxes instead of 99.2%, 26% instead of "fraud", 73% instead of 90%, an experiment instead of a mandate. The lab asks you to be the person who writes the Monday-morning memo: run the six scripts, change one assumption in each, and tell the CEO in plain words which tile lied, why, and what to read instead.
The stack, and why
Before the lab, here is every tool this chapter leans on, and what you would pick instead. It is a short list on purpose: the point of the chapter is the idea, so the tools stay out of the way.
The stack, and why
The one question that decides it: do you want to see every number being computed, or do you want a tested library to compute it for you? As of October 2026.
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Language | Python 3.12, standard library only for the four-box and expected-value scripts | R, Julia, a spreadsheet | Plain Python with tiny numbers can be checked with a pencil, so you see every step. Weakness: no built-in statistics tests; you write the arithmetic. | Your analysts already live in R for formal statistics, or the team shares spreadsheets: do it there instead. |
| Numbers and randomness | numpy, with a seeded default_rng | Python's random module, pandas, Polars | Fast arrays, and a seed makes every simulated run repeat exactly. Weakness: seeded runs hide how different a second run could look. | You need results that must not repeat (a real random draw for assigning users): use the operating system's random source, not a seed. |
| Calibration and scores | Brier score and calibration table written by hand | scikit-learn (brier_score_loss, calibration_curve), netcal | Eight lines you can read beat a function name you cannot. Weakness: easy to get a detail wrong that the library already got right. | The model is going into a real pipeline: switch to scikit-learn, which is tested and what Module 02 uses. |
| Significance tests | none here; shown by hand in Module 01 | scipy.stats, statsmodels | This chapter builds the intuition; Module 01 builds the test with scipy. Weakness: nothing here replaces a real test. | You must report a p-value or interval to someone: use scipy or statsmodels, as in Module 01. |
| Pictures | Hand-drawn SVG figures on the page, no plotting library | matplotlib, Plotly, seaborn | The figures show exactly the numbers in the text and nothing more. Weakness: you cannot change them without editing the markup. | You explore your own data: use matplotlib or Plotly, which draw from your numbers directly. |
Learn the idea with the smallest tool you can check by hand, then move to the tested library the moment the number goes into a decision.
Mission: run all six scripts from this chapter
(code/01b-statistics-intuition/), then write the one-page memo the
SaaSify data team should have sent on Monday morning: for each of the six
dashboard tiles, two or three sentences naming the lie, the concept that catches
it, and the number that should replace it. Write it for the CEO — plain words,
no symbols.
- All six scripts run on your machine; you changed at least one assumption in each (a different outlier, base rate, or cost) and watched the verdict respond
- The memo names, in plain words: the right summary for tile 1, the wobble problem in tile 2, the dummy-baseline problem in tile 3, the base-rate problem in tile 4, the calibration check for tile 5, and the confounder in tile 6
- One measurement criterion: for tile 2, state the eval size that would make a 5-point gap trustworthy (use Module 01's
required_sample_sizethinking — or Monte Carlo it) - README documents the three assumptions you changed and how each verdict moved
Stretch goal: point the same six questions at one real dashboard you have access to (work, a side project, even a public dataset) and write the same memo about it. Finding one real lie counts as passing with distinction.
14 · PracticeCase Files — Solve Before You Peek
The memo covers SaaSify's six tiles. The next dashboards you meet will not label their lies, so these eight case files present real numbers in scrambled order: a latency board with a mean of 640 ms, a 50-example eval, a phishing folder, a retention budget, a yoga program, a threshold war, a silent hour and a lucky quarter. Each one is one of the six tiles wearing different clothes, and the reveal names which.
Eight small cases, each a realistic situation with real numbers.
This is where the chapter either sticks or slides off, so treat it like a workout, not a reading: for each case, write your answer down — the tool you'd reach for, the rough arithmetic, the decision — before opening the reveal.
A wrong attempt followed by a correction builds more memory than ten smooth re-reads. The cases mix every concept in this chapter, in scrambled order (real problems don't announce their topic), and a few reach back into Module 01 on purpose.
Come back and redo two or three of them in a week — they will feel different, and that difference is the learning.
Your API dashboard shows: mean latency 640 ms, median latency 210 ms, p99 latency 4.8 s. An on-call engineer proposes: "Mean is under our 700 ms budget, so we're healthy — and let's page whenever a request exceeds mean + 3 standard deviations." Three questions: what does the gap between mean and median tell you about this data's shape? Why is the proposed alert rule going to misbehave? And what should the latency promise be written in instead?
Reveal the worked answer
The shape. The mean (640 ms) sits three times above the median (210 ms).
- The median, 210 ms. Half of all requests finish in 210 ms or less. This is the number that describes a typical user, and it sits under the tallest part of the pile.
- The mean, 640 ms. Three times the median. Nothing but a long right side can do that, so the gap itself is the shape detector: the same signature as tile 1's 28 against 4.5 in Fig. 1b.1b, here on latency.
- The p99, 4,800 ms. The unluckiest one in a hundred waits 23 times the typical time. "Mean under 700 ms" is true and describes nobody: the typical user is far faster and the suffering users are far slower.
A mean far above the median is a tail detector: half of all requests finish in 210 ms or less, but a small number of very slow requests are dragging the total upward.
Latency is made by multiplication — queueing, retries, token counts, cold caches compounding — so this is the lognormal/heavy-tail recipe, and the p99 of 4.8 s confirms it: the unluckiest 1-in-100 user waits 23× the typical time.
"Mean under 700 ms" is technically true and describes nobody: the typical user is far faster, the suffering users are far slower.
The alert rule. "Mean + 3σ (three sigma)" imports a rule of thumb that belongs to bell-shaped data, where 3σ excursions are genuinely rare (about 1 in 1,000).
On heavy-tailed data both ingredients break: the mean is inflated by the tail, and the standard deviation is inflated even worse, because squaring the gaps makes extreme values dominate it.
The result is a threshold so high it sleeps through real degradation — and a couple of routine tail requests can still trip it, so it pages randomly instead of meaningfully. The wobble vocabulary only works after you have checked the shape.
The fix. Write the promise in percentiles, which are tail-proof by construction: "p95 under 1 s, p99 under 5 s", and alert when a rolling p95/p99 crosses its line. This is exactly why Module 12's monitoring stack and every serious SLO you will ever sign are written in percentiles. The trap avoided: trusting mean and σ on data whose recipe (multiplication) you already knew produces monsters.
You compare two prompts on a 50-example eval. Prompt v1 passes 38 of 50 (76%); prompt v2 passes 42 of 50 (84%). The PM says: "Eight points is a clear win — ship v2 today." You have ten minutes before the meeting. What do you check, roughly what will you find, and what do you say?
Reveal the worked answer
What to check: the wobble of each score. Each eval score is a measurement with luck in it — which 50 examples happened to be in the set.
The typical wobble (standard error) of a pass rate is √(p × (1−p) ÷ n). For v2: √(0.84 × 0.16 ÷ 50) ≈ 0.052, so about ±5 points — meaning v2's honest 95% range is roughly 74% to 94%. v1's is roughly 64% to 88%. The two ranges overlap heavily: both scores are consistent with the two prompts being identical.
The sharper version is Module 01's two-proportion test on the gap itself: the 8-point difference divided by its combined wobble gives z ≈ 1.0, and luck alone produces a z of 1.0 or more about a third of the time. A one-in- three shuffle is nowhere near "beyond reasonable doubt" (the α = 0.05 bar wants roughly z ≥ 2).
What you say: "On 50 examples, an 8-point gap is inside the noise — the same prompt scored twice can easily differ by this much. Two options: grow the eval set to a few hundred examples, or — cheaper — run the paired comparison from Module 07: same 50 cases through both prompts, count the cases where they disagree. If v2 wins most of the disagreements, ship it." The trap avoided: shipping on a difference smaller than one good-or-bad day — the café war after one cup.
Your company deploys a phishing detector: it catches 96% of phishing emails and false-alarms on 3% of legitimate mail. About 1 email in 500 is phishing. The security lead proposes: "When it quarantines something, it's almost certainly phishing — let's auto-delete instead of quarantining, and stop wasting people's time reviewing the folder." Estimate the actual probability that a quarantined email is phishing, and give your verdict on auto-delete.
Reveal the worked answer
Draw the tree — count emails, not percentages. Take 100,000 emails. Phishing: 1 in 500 → 200 phishing emails, of which the detector catches 96% → 192 quarantined. Legitimate: 99,800, of which 3% get false-alarmed → 2,994 quarantined. The quarantine folder therefore holds 192 + 2,994 = 3,186 emails, of which 192 are actually phishing: 192 ÷ 3,186 ≈ 6%.
- The rare pile. One email in 500 is phishing, so a week of 100,000 emails holds 200 of them. Everything about the folder follows from how small 200 is next to 99,800.
- The false alarms. Three percent sounds tiny, but it is 3% of the huge pile: 2,994 legitimate emails a week land in quarantine. The detector's 96% catch rate applies to the small pile and yields only 192.
- The folder. 192 real phishing emails among 3,186. Auto-delete would destroy 2,994 real messages to remove 192 threats. The security lead read "96% of phishing is quarantined" as "96% of the quarantine is phishing", which is tile 4's swap.
The verdict. The security lead has silently swapped the two sides of the bar: "catches 96% of phishing" is P(quarantined | phishing), but the folder question is P(phishing | quarantined) — and the base rate crushes it to 6%. Auto-delete would destroy roughly 94 legitimate emails for every 6 phishing ones — thousands of real messages a week, including, inevitably, a customer contract. Quarantine-plus-review is not waste; it is the correct response to an alarm pile that is 94% innocent.
What would change the math: either a higher base rate (a targeted-attack week) or a lower false-alarm rate. Cutting the false-alarm rate from 3% to 0.3% (299 false alarms) lifts the folder's honesty to 192 ÷ 491 ≈ 39% — better, still nowhere near "almost certainly". The trap avoided: reading P(B | A) as P(A | B) — the most expensive punctuation error in industry.
Your churn model labels 1,000 customers as "80% likely to churn". The plan: send each a retention offer costing $60.
History says the offer persuades about 30% of customers who truly were leaving to stay, and a rescued customer is worth $300 in remaining value. Finance approved the plan using the model's 80%.
Then you run a reliability check: among last year's "80%" predictions, only 55% actually churned. Was the plan profitable under the model's claim? Is it still profitable under the calibrated number? Show the arithmetic.
Reveal the worked answer
The expected value per customer is churn probability × rescue rate × customer value − offer cost: the offer only pays off when the customer really was leaving (p) and the offer works (0.30), in which case it saves $300; the $60 is spent regardless.
Under the model's claim (p = 0.80): 0.80 × 0.30 × $300 = $72 expected benefit, minus $60 cost = +$12 per customer, or about +$12,000 across the thousand. Finance saw a profitable plan.
Under the calibrated number (p = 0.55): 0.55 × 0.30 × $300 = $49.50, minus $60 = −$10.50 per customer, or about −$10,500 overall. The same plan, fed the honest probability, is a money loser. Nothing about the model's ranking changed — these may still be the 1,000 riskiest customers — but the arithmetic that justified the spend was fiction, because an uncalibrated probability walked into an expected-value formula.
What to do: repair the calibration (isotonic regression, Module 02's lab), then re-rank: the plan is profitable for customers whose honest churn probability exceeds the break-even p where p × 0.30 × 300 = 60, i.e. p ≥ 67%. Target the segment above that line instead of everyone the overconfident model waved at. The trap avoided: Lie 5 flowing silently into the expected-value arithmetic of section 10 — miscalibration is invisible on a green dashboard and vivid in a budget.
HR reports: "Employees who attend our optional Friday yoga sessions take 40% fewer sick days. Making attendance mandatory should cut company-wide sick leave substantially." The data is accurate and the sample is large. What's wrong, what would you check, and what experiment would settle it? Then name one situation from AI engineering with this exact structure.
Reveal the worked answer
What's wrong: the comparison is between volunteers and everyone else. People who choose to attend optional Friday yoga are, on average, healthier, younger, more energetic, and more engaged with work — and every one of those traits independently reduces sick days.
Health-and-engagement is the hot weather; yoga attendance and low sick leave are the ice cream and the drownings. The 40% gap can be entirely real as a correlation and entirely empty as a causal claim — and more data makes it more precise, not more causal.
(This flavor of confounding — where people select themselves into the treatment — is called selection bias, and it is the default state of every "users who did X also did Y" statistic.)
The check: compare attendees and non-attendees on things measured before yoga existed — prior-year sick days, age, role. If attendees were already taking fewer sick days before the program launched, the confounder is confessing on camera.
The experiment: randomize. Invite a random half of employees (or randomize which teams get sessions), then compare sick days between the randomly-invited and not-invited groups. Randomness is correlated with nothing, so it severs engagement, health, and every confounder nobody thought of — this is exactly the A/B machinery of Module 01 pointed at an HR question.
The AI-engineering twin: "customers who use the new dashboard churn less" (this chapter's Lie 6), "users who enable feature X retain better — force-enable it", "developers who use the AI assistant close more tickets — mandate it" (Module 15's pilot design exists precisely to randomize that last one). The trap avoided: letting a volunteer effect graduate into a mandate.
Your fraud model outputs a score, and you must choose an alert threshold. At a threshold of 0.5: recall 90%, false-positive rate 4%. At 0.9: recall 60%, false-positive rate 0.5%. Traffic is 100,000 payments/day with a 1% fraud rate. Every flag gets a $4 human review (assume review always gets the truth); every missed fraud costs $500. The ops lead wants 0.9 — "the alarms are cleaner". The fraud lead wants 0.5 — "we catch more". Settle it with arithmetic.
Reveal the worked answer
Fill the four boxes for each threshold, then price them. Per day: 1,000 payments are truly fraud, 99,000 are legitimate.
Threshold 0.5: catches 90% → 900 caught, 100 missed. False alarms: 4% of 99,000 = 3,960. Total flags = 4,860 → review bill 4,860 × $4 = $19,440. Missed-fraud bill: 100 × $500 = $50,000. Total ≈ $69,400 per day.
Threshold 0.9: catches 60% → 600 caught, 400 missed. False alarms: 0.5% of 99,000 = 495. Total flags = 1,095 → review bill $4,380. Missed-fraud bill: 400 × $500 = $200,000. Total ≈ $204,400 per day.
Verdict: the "messy" threshold is $135,000 a day cheaper.
The ops lead is optimizing precision (cleaner alarms feel better); the business loses $500 per miss and pays only $4 per look, so with a 125:1 cost ratio you should tolerate a great deal of alarm noise to buy recall.
The general lesson: thresholds are business decisions, and expected value — costs in the four boxes, not vibes about the four boxes — is how you set them. Module 02 formalizes this as the profit-maximizing threshold.
Two honest caveats worth saying in the meeting: 4,860 reviews/day must actually be staffable (alarm fatigue makes reviewers rubber-stamp, quietly breaking the "review gets the truth" assumption), and the $500-per-miss figure deserves a sensitivity sweep before anyone signs.
The trap avoided: choosing a threshold by which metric feels tidier instead of what the boxes cost.
Your service normally logs about 3 errors per hour, arriving independently at random. The last hour logged zero. A teammate says: "Zero errors? The monitoring pipeline must be down — page infra." Before you page anyone: how unusual is a zero-error hour, actually? And what if the hour had shown 9 errors instead — is that a real incident or Tuesday weather?
Reveal the worked answer
Name the shape first. Independent rare events counted per fixed window is the Poisson recipe. Poisson counts wobble more than intuition expects: "an average of 3 per hour" does not mean "about 3 every hour".
- The silent hour. Zero errors has probability e⁻³ ≈ 5%. With 24 hours in a day, a perfectly healthy system produces a silent hour roughly once a day. Paging infra over one is paging over weather.
- The busy hour. Nine or more errors at an average of 3 has probability about 0.4%, once every ten days by luck alone. Worth a look, and one glance at the error types settles it: nine unrelated errors is bad luck, nine identical ones is an incident.
The zero-error hour: for a Poisson with average 3, the chance of zero events is e⁻³ (e to the minus three) ≈ 5%. Symbol key: e ≈ 2.718 is the natural-growth constant; the −3 is the hourly average.
One hour in twenty
is silent — with 24 hours in a day, a zero-error hour happens roughly once a
day in a perfectly healthy system. Paging infra over it is paging over
weather. (No formula handy? Monte Carlo it: rng.poisson(3, 100_000)
and count the zeros — about 5,000 of them.)
The 9-error hour: 9 or more events at an average of 3 has probability around 0.4% — once every ~10 days by luck. That is worth a look, though one glance at the error types beats any threshold: 9 unrelated errors is bad luck, 9 identical errors is an incident. (Notice the echo of Module 01: "how often would luck alone produce this?" is exactly a p-value, computed on a Poisson instead of a bell.)
The design lesson: alert rules on counted events should be set from Poisson wobble, not gut feel — "alert if errors > 2× average" fires constantly at low averages (5 errors when averaging 2 is routine) and too slowly at high ones. The trap avoided: treating ordinary count wobble as signal in either direction — panic at silence, or celebration at a lucky quiet week.
The growth team ran 14 A/B experiments this quarter, each tested at α (alpha) = 0.05. Thirteen came back "not significant"; one — a new onboarding flow — came back significant with p = 0.04, and the PM is drafting a company-wide blog post titled "Onboarding 2.0 lifted conversion". Before that post ships: how many "significant" results would you expect from 14 experiments if every single change was actually useless? What do you recommend?
Reveal the worked answer
The expected count of false alarms. α = 0.05 means: if a change does nothing, the test will still cry "significant!" 5% of the time — that is the deal you signed in Module 01.
Fourteen useless experiments × 0.05 = 0.7 expected false winners per quarter. Getting exactly one "winner" from 14 tries is therefore the most ordinary possible outcome of testing fourteen duds.
The p = 0.04 does not distinguish "onboarding 2.0 works" from "onboarding 2.0 was this quarter's lucky dud". (This is the multiple-comparisons problem from Module 01's warning about 20 dashboards — here it is deciding a launch.)
What makes it worse: the blog post is selecting the winner after looking — nobody proposes posts about the 13 losers. Selection after peeking converts ordinary luck into a confident public claim; it is the same mechanism as a stock-picking newsletter bragging about its one good fund.
The recommendation: replicate before publicizing — rerun the onboarding experiment once, on fresh traffic, ideally pre-registered ("we predict a lift of at least X"). A real effect passes twice; a lucky dud almost never does (its chance of passing the rerun is just 5% again).
Also report the confidence interval, not the verdict — "somewhere between +0.2% and +6%" tells the company how much is actually known. Cost of the rerun: two weeks.
Cost of a company strategy built on a false positive: Module 01 priced that at $180K. The trap avoided: the file-drawer effect — luck looks like skill whenever losers go unreported.
15 · Interview radarHow This Shows Up in Interviews
Statistics questions in AI-engineering interviews are rarely math tests — they are judgment tests wearing a math costume. The rubric underneath every one of these: does the candidate reach for the right question before the right formula?
"Our fraud model is 99% accurate. Should we ship it?"
The real test Do you immediately ask about the base rate, or do you start discussing deployment logistics?
Strong answer "Accuracy alone can't answer that — if fraud is 1% of traffic, a model that never flags anything is also 99% accurate while catching zero fraud. I'd ask three things: what does the do-nothing baseline score, what are the model's precision and recall on the fraud class specifically, and what do a missed fraud and a false alarm each cost? A model catching 85% of fraud with 25% precision might be hugely valuable or operationally unusable depending on those costs and the review team's capacity."
Land it On rare-event problems I grade against the dummy baseline and price the confusion matrix in dollars — accuracy is the one number I ignore.
"Explain precision and recall to a product manager — and tell me when you'd optimize for each."
Strong answer "Precision: when the system raises an alarm, how often is it right — the boy-who-cried-wolf number. Recall: of all the real cases out there, how many did we catch — the smoke-detector number. You buy more of one by giving up some of the other, using the alert threshold. Optimize precision when a false alarm is expensive or erodes trust — flagging a customer as fraudulent, paging an on-call engineer. Optimize recall when a miss is catastrophic and a false alarm is just a second look — cancer screening, safety filters for a chatbot. In my last example, missed fraud cost $500 and a review cost $4, so we ran high-recall at 25% precision and it was the right call."
Land it The threshold is a business decision, so I set it with the cost of each error, not with a default 0.5.
"Your model says a customer will churn with 90% probability. Can we tell the account team it's 90%?"
The real test Whether you know that probabilities need calibration before they can leave the building.
Strong answer "Only after a calibration check. A probability is a promise about frequency — of all the accounts we stamp 90%, about nine in ten should actually churn. I'd bucket last year's predictions by stated confidence and count outcomes per bucket: if the '90%' bucket churned at 60%, the model ranks well but exaggerates, and every downstream calculation using 0.9 — retention budgets, expected value — is quietly wrong. The repair is cheap: isotonic regression on a held-out set, no retraining. I'd also track a Brier score so calibration drift shows up on a dashboard rather than in a budget miss."
Land it Ranking skill and honest probabilities are separate properties — AUC checks the first, calibration the second, and I test both before a probability touches money.
"Our data shows users who enable feature X retain 30% better. The VP wants it enabled for everyone. What do you tell them?"
Strong answer "That correlation is probably real and the conclusion probably isn't. Users who choose to enable a feature are the engaged users, and engagement drives both the enabling and the retention — same structure as ice cream sales correlating with drownings through summer. Force-enabling X onto unengaged users likely delivers a fraction of the 30%, possibly none. I'd propose a two-week experiment: randomly enable X for half of new users, compare retention between the arms — randomization cuts every confounder at once, including ones we haven't thought of. If the effect survives randomization, roll it out with the real number attached."
Land it I treat correlations as hypotheses to test, not results to ship — prediction can run on correlation, but intervention needs an experiment.
Quick reference — Statistics intuition
- Stack rule
- Learn each idea with a tool small enough to check by hand, then switch to the tested library (scikit-learn, scipy) once the number drives a real decision.
- mean vs median
- The mean is the balance point and one outlier drags it. The median is the middle value and ignores how extreme the extremes are. For money and latency, prefer the median.
- standard deviation
- The typical distance from the mean. Small means everyone is near the middle; large means spread out.
- z-score
- How many standard deviations a value sits from the mean. It puts different measurements on one comparable scale.
- heavy tail / power law (row 5 of Fig. 1b.2b)
- Rare huge values are common enough to dominate the total. Averages become meaningless and “typical” stops describing anything.
- confusion matrix
- The four outcomes of a yes/no prediction: true positive, false positive, false negative, true negative. Every classification metric is built from these four numbers.
- precision vs recall
- Precision: when it says yes, how often is it right. Recall: of all the real yeses, how many did it catch. Raising one lowers the other.
- The base-rate trap
- A 99%-accurate test for something that affects 1 in 10,000 people is wrong nearly every time it fires. The rarity of the thing beats the accuracy of the test.
- false-alarm rate vs the share of flags that are false
- Same top, different bottom. 198 ÷ 9,920 honest payments = 2% describes the filter; 198 ÷ 266 flags = 74% describes the review queue. Always ask "out of what?" (worked in section 07).
- Brier score baseline
- Judge a Brier score against b × (1 − b), the score of always saying the base rate b: 0.25 for churn near 50%, but 0.0079 for fraud at 0.8% (worked in section 08).
- calibration repair
- Replace each prediction with how often last year's predictions at that level came true: bucket relabelling, or isotonic regression. The ranking stays; the numbers, and the decisions that use them, change.
16 · RecapWhat You Can Do Now
- You can read a mean–median gap as a tail detector (marker 2 in Fig. 1b.1b), and choose mean, median, or percentile to match the question being asked — money, typical, or worst-case
- You can refuse to compare two scores until you know the wobble of each, and estimate that wobble from the sample size with the √n rule
- You can predict a dataset's shape from how its numbers are made — added, counted, waited-for, or multiplied — and pick summaries and alert rules that survive that shape
- You can build a confusion matrix from a scenario's raw counts, compute precision and recall from it, and beat an accuracy claim to death with a dummy baseline
- You can un-swap P(A|B) and P(B|A) with a frequency tree, and explain to anyone why a good alarm on a rare event is still mostly false alarms
- You can ask "out of what?" of any rate, and explain how a filter with a 2% false-alarm rate fills a queue where three flags in four are honest
- You can audit a model's probabilities like a weather forecaster's track record — reliability buckets and a Brier score — and say when repair matters and when ranking is enough
- You can judge a Brier score against the base-rate forecaster's b × (1 − b), and walk one prediction through a bucket repair into the decision it drives
- You can spot the confounder inside a "users who did X also did Y" claim, and design the randomized experiment that settles it
- You can turn probabilities and costs into an expected-value decision, sweep its assumptions, and know when a naked average is the wrong tool for a one-shot risk
From this chapter: close the page and redraw the two core pictures from memory — the four boxes with precision reading across and recall reading down, and the frequency tree for the phishing filter (1-in-500 base rate, 96% catch rate, 3% false alarms). Check yourself against Fig. 1b.3 and Fig. 1b.4. Reaching back to Module 01: the $180K meeting's test came back p = 0.22. Using this chapter's café vocabulary — wobble, moodiness, luck — explain to a non-technical friend what that 0.22 meant and why the team refused to ship.