Metric Design

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.

Make accuracy lie

1%

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

The Accurate Model That Catches Nothing

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.

Price the two mistakes

Red is the cost of misses, yellow the cost of false alarms. Drag the price of one miss and see which model is cheaper.

$100

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.

The failure, and how to catch it

The road

  1. The confusion matrix: four counts, precision and recall.
  2. The F-score: one number that refuses to hide a weak half.
  3. ROC, AUC and PR: judge the scores before any threshold.
  4. Calibration: does 0.8 mean 80%?
  5. Regression errors: MAE, RMSE and the asymmetric pinball loss.
  6. Ranking: NDCG and MRR, where position is everything.
  7. Averages that lie: micro, macro and Simpson's paradox.
  8. Goodhart's law: a metric decays once you optimize it.
  9. The playground: one model, every metric at once. It explains the hero's base rate.
  10. The field guide: terms, numbers, code and links.
A disease affects 2% of patients. A test always says "healthy". What are its accuracy and its recall on sick patients (the share of sick patients it finds)?

Chapter 1

The Confusion Matrix: Four Counts, No Hiding

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.

BoxThe model saidThe truth wasName
TPflagharmfultrue positive, a catch
FPflagfinefalse positive, a false alarm
FNpassharmfulfalse negative, a miss
TNpassfinetrue 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.

Move the threshold, sort the boxes

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.

0.50

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.

Say it aloud

Precision equals T-P divided by T-P plus F-P.

precision
precision the share of flags that were right, from 0 to 1.
TP
T-P true positives: harmful posts the model flagged.
TP + FP
T-P plus F-P every post the model flagged.
FP
F-P false positives: fine posts the model flagged.
In plain words

Count every flag, TP plus FP. Divide the correct flags TP by that count.

With numbers

With made-up numbers: TP = 40, FP = 10. Precision = 40 / 50 = 0.8. Four flags in five are right.

Say it aloud

Recall equals T-P divided by T-P plus F-N.

recall
recall the share of real positives the model found, from 0 to 1.
TP
T-P harmful posts the model flagged.
TP + FN
T-P plus F-N every harmful post, found or not.
FN
F-N false negatives: harmful posts the model passed.
In plain words

Count every harmful post, TP plus FN. Divide the catches TP by that count.

With numbers

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.

A spam filter flags 50 emails. 45 are spam. The inbox held 90 spam emails. What are precision and recall?

Chapter 2

The F-Score: One Number That Will Not Hide a Weak Half

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.

Say it aloud

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.

Fβ
F-beta the combined score, from 0 to 1. F-one is the case beta = 1.
(1 + β2)·TP
one plus beta squared times T-P the catches, given a weight.
same term below
the same weighted catches they appear on the bottom too, so a perfect model scores 1.
β2·FN
beta squared times F-N each miss counts beta squared times.
FP
F-P each false alarm counts once.
In plain words

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.

With numbers

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.

Try to buy recall with precision

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.

0.90
0.10

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.

The failure

A model has precision 1.0 and recall 0.02. What is its F-one, roughly?

Chapter 3

ROC, AUC and PR: Judge the Scores, Not One Threshold

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.

Trace the ROC curve, then count the pairs

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.

0.45

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.

Say it aloud

A-U-C equals W divided by n-plus times n-minus.

AUC
A-U-C area under the ROC curve, from 0 to 1. 0.5 is a coin flip.
W
W the number of positive and negative pairs where the positive scores higher.
n+
n-plus the number of positives.
n−
n-minus the number of negatives. The product counts every pair.
In plain words

Pair each positive with each negative. Count the pairs W the positive wins. Divide by the number of pairs.

With numbers

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.

The failure

AUC = 0.84 means exactly:

Chapter 4

Calibration: Do the Probabilities Come True?

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.

Bend the probabilities, keep the ranking

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.

×2.00

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.

Say it aloud

E-C-E equals the sum over bins b of n-b over N, times the absolute gap between conf-b and acc-b.

ECE
E-C-E expected calibration error, from 0 (calibrated) up.
Σb
the sum over bins b one term for each confidence bin.
nb / N
n-b over N the share of predictions in bin b.
|confb − accb|
the absolute gap between conf-b and acc-b average confidence minus the share that came true, sign dropped.
In plain words

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.

With numbers

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.

You apply temperature scaling to an overconfident network. What happens to AUC and ECE?

Chapter 5

Regression Errors: MAE, RMSE and the Pinball Loss

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.

Say it aloud

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.

RMSE
R-M-S-E root mean squared error, in the target's unit (MW).
√
the square root brings squared megawatts back to megawatts.
(1/n) Σi
one over n times the sum over i the average over the n hours.
(yi − ŷi)2
y-i minus y-hat-i, squared the miss in hour i, squared, so big misses weigh much more.
In plain words

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 numbers

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.

Grow one miss, watch RMSE run

Five hourly misses as stems. Drag the 6 p.m. miss. Grey is MAE, pink is RMSE.

10 MW

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.

MetricBest constant forecastTrap
MAEmedianblind to how bad the worst miss is
RMSEmeanone outlier can own the score
Pinball at 0.990th percentileneeds 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
MAPEpercent of truthtruth 0.1 forecast 0.2 is a 100% miss; with a 10% miss on 100, MAPE is 55%
Your forecaster's RMSE is three times its MAE. What does that tell you?

Chapter 6

Ranking: NDCG and MRR, Where Position Is Everything

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.

Say it aloud

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.

DCG@k
D-C-G at k discounted cumulative gain over the top k results.
Σi=1..k
the sum over i from one to k one term per rank, from the top down to k.
2reli − 1
two to the rel-i minus one the gain: a grade 3 document is worth 7, a grade 1 worth 1.
log2(i + 1)
log base two of i plus one the discount: 1 at rank 1, 1.585 at rank 2, 2 at rank 3.
In plain words

Turn each grade rel-i into a gain. Divide the gain by the discount for rank i. Add the top k.

With numbers

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.

NDCG = DCG / IDCG = 10.484 / 10.823 = 0.969 (best order 3, 2, 2, 1, 0)

Reorder the results

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.

A RAG system puts the top 5 chunks into the model's context and lets the model sort them. Which retrieval metric limits answer quality most?

Chapter 7

Averages That Lie: Micro, Macro and Simpson's Paradox

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.

ClassTP, FP, FNF-one
Hate speech90, 10, 100.90
Harassment1, 9, 90.10
Macro: average the two F-ones—0.50
Micro: pool the counts first91, 19, 190.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.

overall = (share easy) × (accuracy on easy) + (share hard) × (accuracy on hard)

Win every slice, lose the total

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.

90%

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.

The failure

Model B beats model A on every slice of the test set, but scores lower overall. What must be true?

Chapter 8

Goodhart's Law: The Metric Becomes the Target

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.

Push on the proxy

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.

top 10%

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:

  1. A portfolio: several metrics whose cheap tricks differ, so a trick that lifts one sinks another.
  2. A held-out set that the optimizer never sees, refreshed on a schedule.
  3. Probes for known exploits: repetition, length, flattery.
  4. Read the winners: sample the top-scoring outputs by hand.
A boat-racing agent scores 20% above humans by circling a lagoon and never finishing. What is the best diagnosis?

Chapter 9

The Playground: One Model, Every Metric

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.

Change the world, not the model

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.

1.50
50%
0.50

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.

Say it aloud

Precision equals pi times R, divided by pi times R plus one minus pi times F-P-R.

precision
precision the share of flags that are real positives.
π·R
pi times R the share of all cases that are caught positives.
same term below
pi times R again the caught positives, part of all flags.
(1 − π)·FPR
one minus pi times F-P-R the share of all cases that are false alarms.
π
pi the base rate: the share of cases that are positive. Here it is not 3.14.
In plain words

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.

With numbers

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:

  1. Find a setting where accuracy rises while F-one falls.
  2. Find AUC above 0.85 with precision under 0.1.
  3. Set separation to 0: AUC is 0.5, and no threshold helps.
On the bench you slide the base rate from 50% to 1% and touch nothing else. What happens?

Chapter 10

The Field Guide

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.

OutputMetricOne worked numberWhat fools it
Decisionsprecision, recallTP 40, FP 10, FN 60: 0.8 and 0.4the threshold you chose
DecisionsF-betasame counts, β = 2: 0.444a beta not set from cost
ScoresAUC, PR curve21 of 25 pairs: 0.84rare positives (use PR)
ProbabilitiesECE, Brier0.145 and 0.125the bin count (ECE)
NumbersMAE, RMSE, pinball3.2 and 4.69 MWone big miss (RMSE)
RankingsNDCG, MRR0.969 (0.960 linear)the gain convention
Any, over slicesmicro, macro0.83 against 0.50the mix of slices
Any, under pressureportfolio, counter-metricsBLEU 7/7 clipped to 2/7the optimizer itself

Before you ship a metric

  1. Name the decision and the cost of each error type.
  2. Write the base rate next to every rate, and compute the do-nothing baseline.
  3. Separate model properties (AUC, recall) from deployment properties (precision, accuracy).
  4. Declare the averaging weights and the slices before you evaluate.
  5. Ask: what is the cheapest behaviour that raises this number without serving the goal?
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

Where each thread goes next

Sources named on this page

The takeaway. Start from the decision, never quote a rate without its base rate, declare your weights, and red-team every number you plan to optimize.
A vendor quotes 95% precision. Which question matters most before you trust it?

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.

Metric Design: Measuring What Matters
Back to Gleams