A fraud model that flags nothing scores 99% accuracy and catches zero frauds. A metric is a choice about which mistakes count, and a bad choice ranks the useless model first.
Pick a model, then drag the fraud rate from 50% down to 0.5%. Watch accuracy reward the model that does nothing. Then we build, piece by piece, the counts, curves, scores and averages that this trick cannot fool.
You need fractions and a little Python. Whether a measured gap is real or noise lives in The Statistics of Evaluation. We build the rest from zero.
Part of the Evaluation and Analytics family. Its neighbours: eval statistics, eval plots and the metrics ladder.
Illustrative toy on 10,000 transactions. The trying model catches 60% of frauds and wrongly flags about 2% of legitimate payments, at every fraud rate.
Chapter 0
See how accuracy rewards a model for agreeing with the majority, and price the two kinds of mistake
A payments company sees 10,000 transactions a day. About 100 are fraud. An engineer reports a new model with 99% accuracy. The model is one line long: it says "legitimate" every time.
Accuracy is the share of predictions that are correct. Here it is 9,900 correct out of 10,000, so 99%. The model learned nothing about fraud. It agreed with the majority, and the majority is 99% of the data. This is class imbalance: one class is much rarer than the other. Fraud, disease and defects are all rare, so most problems worth a model are imbalanced.
Now a second model tries. It catches 60 of the 100 frauds and wrongly flags 200 legitimate payments. It is correct on 60 frauds plus 9,700 legitimate payments: 9,760 of 10,000, so 97.6%. By accuracy, trying is worse than doing nothing.
The fix starts with one question: what does each mistake cost? A miss lets a fraud through, and the company pays the chargeback. A false alarm freezes an honest card, and a support agent spends time on it. Accuracy counts both as one wrong answer.
Red is the cost of misses, yellow the cost of false alarms. Drag the price of one miss and see which model is cheaper.
Illustrative prices: a false alarm costs $5 of support time. Counts are the two models above at 1% fraud.
Work it at $100 a miss. Flag nothing: 100 misses, so $10,000 a day. The trying model: 40 misses cost $4,000, and 200 false alarms cost $1,000, so $5,000. The trying model wins once a miss costs more than $1,000 / 60, about $16.67.
Chapter 1
Sort every prediction into one of four boxes, and read precision and recall off the boxes
A moderation model reviews 1,000 posts. It flags some as harmful. Accuracy squeezed its work into one number. Instead, keep four counts.
| Box | The model said | The truth was | Name |
|---|---|---|---|
| TP | flag | harmful | true positive, a catch |
| FP | flag | fine | false positive, a false alarm |
| FN | pass | harmful | false negative, a miss |
| TN | pass | fine | true negative |
This grid is the confusion matrix. The second letter is what the model said. The first letter says whether it was right. Most binary metrics are a ratio of these four counts.
Each dot is a post at its model score. Orange dots are harmful, blue are fine. Posts right of the teal line get flagged. Drag the line.
Illustrative scores for 10 harmful and 30 fine posts.
Two questions fall out of the grid. Of the posts I flagged, how many were harmful? Of the harmful posts, how many did I flag? Call the catches TP, the false alarms FP and the misses FN.
Precision equals T-P divided by T-P plus F-P.
Count every flag, TP plus FP. Divide the correct flags TP by that count.
With made-up numbers: TP = 40, FP = 10. Precision = 40 / 50 = 0.8. Four flags in five are right.
Recall equals T-P divided by T-P plus F-N.
Count every harmful post, TP plus FN. Divide the catches TP by that count.
Same model: TP = 40, FN = 60. Recall = 40 / 100 = 0.4. With TN = 890, accuracy is 930 / 1,000 = 0.93, and it hides the 60 misses.
The two pull against each other. Flag everything and recall is 1, but precision falls to the share of harmful posts. Flag one sure post and precision is 1, but recall is near 0.
Chapter 2
Combine precision and recall so a strong half cannot pay for a weak one, and tilt the scale by the cost of a miss
Your manager wants one number, not two. A model has precision 0.9 and recall 0.1: it misses 90% of the harm. The plain average of the two is (0.9 + 0.1) / 2 = 0.5, a passing grade. That average lets a strong half pay for a dead half.
The F-score blocks that trade. Write it with the counts. Call the catches TP, the false alarms FP and the misses FN. Pick a weight β (beta) that says how much worse a miss is than a false alarm.
F-beta equals one plus beta squared times T-P, divided by one plus beta squared times T-P, plus beta squared times F-N, plus F-P.
Charge each miss FN beta squared points and each false alarm FP one point. F-beta is the weighted catches over the weighted catches plus the charges.
The moderation model: TP = 40, FN = 60, FP = 10. With beta = 1: 80 / (80 + 60 + 10) = 0.533. With beta = 2: 200 / (200 + 240 + 10) = 0.444. With beta = 0.5: 50 / (50 + 15 + 10) = 0.667.
Set precision and recall. Pink is the F-score, grey the plain average. Push one slider to 0.1 and watch which bar follows it.
F-beta from precision and recall: (1 + β²)PR / (β²P + R), the same score as the count form.
At precision 0.9 and recall 0.1, F-one is 2 × 0.9 × 0.1 / 1.0 = 0.18. It stays near the weaker number. Pick beta from cost: a missed tumour is far worse than a second scan, so screening uses beta = 2. A spam filter that buries real mail uses beta = 0.5.
Chapter 3
Sweep every threshold at once, count winning pairs to get AUC, and switch to the PR curve when positives are rare
A model does not output decisions. It outputs a score for each case, and you pick a threshold later. So one model is a whole family of classifiers, one per threshold. Compare two models at one threshold and you mix model quality with a knob you can turn.
The ROC curve shows the whole family. Sort the cases by score. Lower the threshold one case at a time. Each positive moves the curve up; each negative moves it right. The y-axis is recall, also called the true positive rate. The x-axis is the false positive rate: false alarms divided by all negatives.
Left: five positives and five negatives on a score line. Right: the ROC curve, with your threshold as a dot. Drag the threshold, then press Count pairs.
Illustrative scores. "×50 negatives" copies each negative 50 times, as if fraud were rarer.
The area under the ROC curve, AUC, has an exact meaning. Pick one positive and one negative at random. AUC is the chance the positive scores higher. Call the positives n-plus and the negatives n-minus, and the pairs where the positive wins W.
A-U-C equals W divided by n-plus times n-minus.
Pair each positive with each negative. Count the pairs W the positive wins. Divide by the number of pairs.
Positives 0.9, 0.8, 0.7, 0.5, 0.3; negatives 0.6, 0.4, 0.35, 0.2, 0.1. The wins are 5 + 5 + 5 + 4 + 2 = 21 of 25 pairs. AUC = 0.84.
AUC ignores the class mix. That is its weakness on rare events. Turn on ×50 negatives at threshold 0.45: the ROC point stays at (0.2, 0.8), but precision falls from 4 / 5 = 0.8 to 4 / 54 = 0.07. The PR curve plots precision against recall, so it shows that collapse. Its area is the average precision.
Chapter 4
Check whether a model's probabilities come true, measure the gap with ECE and the Brier score, and repair it without touching the ranking
A hospital model gives a patient a sepsis risk of 0.8. The protocol pages a nurse at that number. Of all patients scored 0.8, do 80% get worse? If only half do, the 0.8 is not a probability. It is a ranking score with a wrong label.
A model is calibrated when, among predictions with confidence p, the share that come true is p. Calibration is separate from ranking. Squeeze every score toward 0.5 in the same order: AUC stays perfect, and the probabilities become nonsense.
The reliability diagram shows it. Put predictions in bins by confidence. For each bin, plot the average confidence against the share that came true. A calibrated model sits on the diagonal. Bars below it mean overconfident.
Bars show how often each confidence bin came true. Drag overconfidence and watch the bars leave the diagonal while AUC stays still. Then press Rescale.
Illustrative: 400 simulated patients with a known true risk. Overconfidence multiplies the log-odds; rescaling divides them back.
One number for the diagram: weight each bin's gap by its share of the data. Call a bin b, its count n-b, the total N, its average confidence conf-b and its observed rate acc-b.
E-C-E equals the sum over bins b of n-b over N, times the absolute gap between conf-b and acc-b.
For each bin, take the gap between conf-b and acc-b. Weight it by the bin's share n-b over N. Add the bins.
Ten made-up predictions in 3 bins. Gaps 0.2, 0.167 and 0.0875 with shares 0.3, 0.3 and 0.4. ECE = 0.06 + 0.05 + 0.035 = 0.145.
ECE changes with the bin count, so always state it. The Brier score needs no bins: the average of (prediction minus outcome) squared, with outcome 1 or 0. On the same ten, the terms add to 1.2525, so Brier = 0.125. The biggest term, 0.49, is a 0.7 that did not happen. Brier rewards honest probabilities, because a model scores best when it reports what it believes.
The repair is temperature scaling: divide the log-odds by one number fitted on held-out data. The order stays, so AUC cannot move. Guo et al. (2017) found modern neural networks poorly calibrated, and this one-number fix worked on most datasets.
Chapter 5
Choose an error metric whose best forecast is the forecast your decision needs
You forecast electricity demand for a grid. A miss of 50 megawatts (MW) at 3 a.m. costs little. The same miss at the 6 p.m. peak can start an expensive backup plant. The cost of an error depends on its size and its side. The metric must match.
MAE, the mean absolute error, is the average size of the misses. Every megawatt costs the same. The constant forecast that minimises MAE is the median of the target, so a few disasters barely move it.
RMSE squares each miss first. Call the true value of hour i y-i, the forecast y-hat-i, and the number of hours n.
R-M-S-E equals the square root of one over n times the sum over i of y-i minus y-hat-i, squared.
For each hour, take the miss y-i minus y-hat-i and square it. Average the squares over n. Take the square root.
With made-up misses 1, −2, 1, 2 and 10 MW: squares 1, 4, 1, 4, 100 average to 22, so RMSE = 4.69 MW. MAE is 16 / 5 = 3.2 MW.
Five hourly misses as stems. Drag the 6 p.m. miss. Grey is MAE, pink is RMSE.
Illustrative misses. The other four hours stay at 1, −2, 1 and 2 MW.
The 10 MW hour gives 100 of the 110 squared units. When RMSE is much larger than MAE, a few big misses dominate: go and find them. The constant that minimises RMSE is the mean.
If a shortfall costs 9 times an excess, use the pinball loss at level 0.9. An under-forecast costs 0.9 per MW and an over-forecast 0.1. With truth 100 MW: forecast 80 costs 0.9 × 20 = 18; forecast 120 costs 0.1 × 20 = 2. Its best forecast is the 90th percentile of demand.
| Metric | Best constant forecast | Trap |
|---|---|---|
| MAE | median | blind to how bad the worst miss is |
| RMSE | mean | one outlier can own the score |
| Pinball at 0.9 | 90th percentile | needs the cost ratio |
| R² | compares with "always the mean" | truth 10, 12, 14, 16, 18 and forecast 11, 11, 15, 15, 19 give 1 − 5/40 = 0.875; on new data it can go below 0 |
| MAPE | percent of truth | truth 0.1 forecast 0.2 is a 100% miss; with a 10% miss on 100, MAPE is 55% |
Chapter 6
Score an ordered list so a good document near the top counts more than one near the bottom
A search system returns 5 documents for a query. The one that answers it sits at rank 5. A reader scans from the top and stops early. So a ranking metric is a model of attention that fades with position.
Three simple metrics come first. Precision at k is the share of the top k that is relevant. Recall at k is the share of all relevant documents that made the top k. MRR, the mean reciprocal rank, averages 1 / (rank of the first relevant result) over queries. First hits at ranks 1, 3 and 2 give (1 + 1/3 + 1/2) / 3 = 0.611.
Relevance often has grades: 3 is a perfect answer, 0 is useless. Call the grade at rank i rel-i and the cut-off k.
D-C-G at k equals the sum over i from one to k of two to the rel-i minus one, divided by log base two of i plus one.
Turn each grade rel-i into a gain. Divide the gain by the discount for rank i. Add the top k.
Made-up grades 3, 2, 0, 1, 2 give 7/1 + 3/1.585 + 0 + 1/2.322 + 3/2.585 = 7 + 1.893 + 0 + 0.431 + 1.161 = 10.484.
Raw DCG grows with the number of good documents, so divide by the DCG of the best possible order, the IDCG. The result, NDCG, runs from 0 to 1.
Tap a document to move it up one rank. Compare a swap at the top with a swap at the bottom.
Illustrative grades. Relevant means grade 1 or more; the query has 4 relevant documents.
Swap ranks 1 and 2 of the start order and NDCG falls to 0.832. Swapping ranks 4 and 5 moves it to 0.977. The top costs most. One more trap: scikit-learn's ndcg_score uses linear gain (the grade itself) and gives 0.960 on the same list. State the gain.
Chapter 7
See how the weights of an average decide its answer, and compare models only on matched mixes
A moderation model covers two harms: 100 hate-speech cases and 10 harassment cases. Leadership wants one F-score for both. The arithmetic below is correct both ways, and the two answers differ by 33 points.
| Class | TP, FP, FN | F-one |
|---|---|---|
| Hate speech | 90, 10, 10 | 0.90 |
| Harassment | 1, 9, 9 | 0.10 |
| Macro: average the two F-ones | — | 0.50 |
| Micro: pool the counts first | 91, 19, 19 | 0.83 |
A micro average pools every decision, so each decision gets one vote and the big class wins. A macro average gives each class one vote. If the rare class is why the product exists, report macro or a table per class.
The deeper trap is Simpson's paradox: a model wins on every slice and loses overall. An overall score is a weighted sum.
Each tile's height is accuracy on that slice; its width is the slice's share of the test set. Drag model B's share of hard cases.
Illustrative: A scores 0.90 easy and 0.30 hard on a mix with 10% hard. B scores 0.95 and 0.35.
At 90% hard, B gets 0.1 × 0.95 + 0.9 × 0.35 = 0.41, while A gets 0.9 × 0.90 + 0.1 × 0.30 = 0.84. B is better on both slices. With matched weights of 50/50, A is 0.60 and B is 0.65. The paradox was in the mixes, not the models.
Chapter 8
Watch a proxy split from its goal under optimization, and build defences into the metric
Economist Charles Goodhart made the point in 1975 about monetary statistics. Anthropologist Marilyn Strathern's 1997 wording is the one people quote: "When a measure becomes a target, it ceases to be a good measure." This is Goodhart's law.
Here is the mechanism. A proxy is a number that stands in for the goal. It tracks the goal on the behaviour that existed when you checked it. Optimization pushes behaviour into corners where nobody checked. The proxy did not break. You left the region where it was valid.
Each dot is a behaviour: proxy score across, true goal up. Pressure keeps only the top share by proxy. Drag it, then turn on the counter-metric.
Illustrative: 400 behaviours. Some include an exploit that raises the proxy and lowers the goal. The counter-metric measures the exploit's cost.
Machine translation shows the pattern. BLEU scores a translation by its word overlap with reference translations. The BLEU paper (Papineni et al., 2002) gives the exploit. Its candidate is "the the the the the the the" against "The cat is on the mat". Plain word precision is 7/7. BLEU clips each word's count at its most frequent count in any single reference, here 2, so the score is 2/7.
At machine speed this is reward hacking. OpenAI's CoastRunners agent (2016) circled a lagoon to hit respawning targets, never finished the race, and scored on average 20% higher than human players. In April 2025 OpenAI rolled back a GPT-4o update that had become sycophantic. Its post says the update focused too much on short-term feedback such as thumbs up.
Defences, each against one failure:
Chapter 9
Move the separation, the base rate and the threshold, and sort the metrics into model properties and deployment properties
Put one model on the bench as two score curves: negatives centred at 0, positives centred further right, both with spread 1. Add a threshold. Every binary metric in this lesson is a function of these three things.
Blue is negatives, orange positives, sized by how common each is. Drag the base rate to 1% and watch precision fall while AUC and recall hold.
Exact values from the normal curves, not a simulation.
Recall and the false positive rate look inside one true class each, so they are model properties. Precision mixes in how common positives are. Call the base rate π (pi), recall R and the false positive rate FPR.
Precision equals pi times R, divided by pi times R plus one minus pi times F-P-R.
Multiply the base rate π by recall R to get the catches. Multiply the negatives 1 − π by FPR to get the false alarms. Precision is catches over catches plus false alarms.
A vendor's model: π = 0.05, R = 0.8, FPR = 0.1. Precision = 0.04 / (0.04 + 0.095) = 0.30. At π = 0.005 it is 0.004 / (0.004 + 0.0995) = 0.04.
The default bench: separation 1.5, threshold 0.5. Recall is 0.841 and FPR is 0.309. AUC is 0.856 at every base rate. At π = 0.5, precision is 0.732. At π = 0.01, it is 0.027: a 27-fold fall with the same model.
Three puzzles to solve on the bench:
Chapter 10
Keep the terms, the numbers, the checks and the code in one place, and follow each thread to its sibling lesson
A metric is a contract about which mistakes count. Choose it from the decision it drives, then try to break it before an optimizer does.
| Output | Metric | One worked number | What fools it |
|---|---|---|---|
| Decisions | precision, recall | TP 40, FP 10, FN 60: 0.8 and 0.4 | the threshold you chose |
| Decisions | F-beta | same counts, β = 2: 0.444 | a beta not set from cost |
| Scores | AUC, PR curve | 21 of 25 pairs: 0.84 | rare positives (use PR) |
| Probabilities | ECE, Brier | 0.145 and 0.125 | the bin count (ECE) |
| Numbers | MAE, RMSE, pinball | 3.2 and 4.69 MW | one big miss (RMSE) |
| Rankings | NDCG, MRR | 0.969 (0.960 linear) | the gain convention |
| Any, over slices | micro, macro | 0.83 against 0.50 | the mix of slices |
| Any, under pressure | portfolio, counter-metrics | BLEU 7/7 clipped to 2/7 | the optimizer itself |
pythonimport numpy as np def confusion(y, pred): # y, pred: arrays of 0/1 TP = int(((pred == 1) & (y == 1)).sum()); FP = int(((pred == 1) & (y == 0)).sum()) FN = int(((pred == 0) & (y == 1)).sum()); TN = len(y) - TP - FP - FN return TP, FP, FN, TN def f_beta(TP, FP, FN, beta=1.0): # each miss counts beta**2 b2 = beta * beta return (1 + b2) * TP / ((1 + b2) * TP + b2 * FN + FP) def auc_pairs(scores, y): # chance a positive outscores a negative pos, neg = scores[y == 1], scores[y == 0] wins = (pos[:, None] > neg[None, :]).sum() + 0.5 * (pos[:, None] == neg[None, :]).sum() return wins / (len(pos) * len(neg)) def ece(p, y, n_bins=10): # state n_bins when you report it idx = np.minimum((p * n_bins).astype(int), n_bins - 1) return sum((idx == b).mean() * abs(p[idx == b].mean() - y[idx == b].mean()) for b in range(n_bins) if (idx == b).any()) def ndcg(rels, k=None): # exponential gain 2**rel - 1 dcg = lambda r: sum((2 ** g - 1) / np.log2(i + 2) for i, g in enumerate(r[:k])) return dcg(rels) / dcg(sorted(rels, reverse=True)) def precision_at(pi, recall, fpr): # recompute a vendor's precision at YOUR base rate return pi * recall / (pi * recall + (1 - pi) * fpr) print(f_beta(40, 10, 60), f_beta(40, 10, 60, 2)) # 0.533 0.444 print(ndcg([3, 2, 0, 1, 2])) # 0.9686 print(precision_at(0.05, 0.8, 0.1)) # 0.296
Now explain it back: open Teach and draw the confusion matrix from memory. Or go back to the hero and find the fraud rate where flagging nothing starts to win.