Skip to content
Tech Interview Prep
Technical interview guide

Model Evaluation Metrics

Picking the right metric (accuracy, precision/recall, F1, ROC-AUC) for the problem and its class balance.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: scikit-learn stable model-evaluation, calibration, and cross-validation guidance and Google ML Crash Course classification, fairness, and monitoring guidance accessed 2026-08-31..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Explain precision and recall to a nontechnical stakeholder.

Answer

The 90-second version

Two questions, and they move independently:

  • Of everything we flagged, how much was actually real? (precision)
  • Of all the real cases out there, how many did we flag? (recall)

I wouldn't use the words "precision" and "recall" with a stakeholder. I'd say "how clean the queue is" and "how much we catch," then put counts on both at the threshold we're proposing.

Worked example: fraud review, 1M transactions/day

Assume 1,000 of those transactions are genuinely fraudulent (0.1%). The model flags 5,000.

Actually fraudActually cleanTotal
Flagged7004,3005,000
Not flagged300994,700995,000
Total1,000999,0001,000,000

Precision = 700 / 5,000 = 14%. Recall = 700 / 1,000 = 70%.

The 14% is the number that lands: 86 of every 100 alerts are customers who did nothing wrong. That isn't a broken model: at a 0.1% base rate, a model has to be very good to keep the queue clean.

The trade-off, in their units

Tighten the threshold so only 1,500 transactions get flagged: 450 frauds caught, 1,050 false alarms. Precision 30%, recall 45%.

Loose (5,000 alerts)Tight (1,500 alerts)
Precision14%30%
Recall70%45%
Analyst hours/day (6 min per alert)500150
Missed fraud ($400 average)$120,000$220,000
False investigations ($12 each)$51,600$12,600
Total daily cost$171,600$232,600

The tighter threshold looks better on precision and cuts the review team from roughly 63 analysts to 19, and still costs $61,000 more per day, because a missed fraud is worth more than a wasted review. That's the conversation to have: not "which metric is better," but "what does a miss cost versus a false alarm."

Failure modes and how I'd catch them

  • Base rate moves. Fraud spikes at holidays, so the same threshold flags far more. Watch the confirmed-fraud share of alerts weekly; if it slides from 14% to 5%, the queue is mostly noise and the threshold is stale.
  • Labels arrive late. Chargebacks land 30–60 days out, so today's precision is unknown. Track alert-to-label lag and report precision on the matured cohort, not the last week.
  • Recall decays silently. Fraudsters adapt. Hold back a labelled sample each week and measure recall on it, or you're only measuring the cases you already caught.
  • Feedback loop. Analysts only see flagged cases, so missed fraud never generates a label. Without that holdout sample, recall is unmeasurable.

When to lead with which

High recall first when a miss is expensive and a false alarm is cheap: screening before a human confirm, anything where the next step is a review. High precision first when the action is costly or irreversible: freezing an account, blocking a payout, anything customer-visible. If the two costs are within an order of magnitude, tune the threshold on total cost and report both numbers.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

When is accuracy an appropriate primary metric?

Answer

The 90-second answer. Accuracy is the right primary metric when the decision loss is symmetric 0-1, every misclassification costs the same, and the class prior in your evaluation set matches the prior you deploy against. Under those two conditions accuracy is an unbiased estimate of expected loss, and the Bayes-optimal rule (predict the most likely class) is exactly the rule that maximizes it. Break either condition and accuracy stops measuring what you care about, because its denominator is dominated by whichever class is common.

Why it behaves that way. Write accuracy in terms of prevalence p, recall r and false-positive rate f:

accuracy = (1 - p) + p*r - (1 - p)*f

Differentiate: one point of recall is worth p points of accuracy, one point of false-positive rate costs 1 - p. At p = 0.5 those weights are equal and accuracy is a fair referee. At p = 0.01 a single false positive costs as much accuracy as 99 missed positives. That asymmetry is the whole story: accuracy is a majority-class metric wearing a neutral name.

Arithmetic. The Kaggle credit-card fraud set has 492 frauds in 284,807 transactions, a 0.17% positive rate. A model with 80% recall at a 0.1% false-positive rate scores:

(1 - 0.0017) + 0.0017*0.80 - 0.9983*0.001 = 0.99866

Predicting "not fraud" for every row scores 0.9983. Catching four out of five frauds buys 0.036 percentage points of accuracy. One extra false positive per thousand rows costs 0.0998 points: roughly 587 missed frauds' worth. Any threshold tweak that adds a handful of false positives erases the entire gain.

When it holds.

ConditionWhy it mattersCheck
Loss is symmetric 0-1accuracy is the empirical risk of the Bayes rule only under 0-1 lossask what a false positive and a false negative each cost in dollars or hours
Test prior ≈ deployment priorthe p and 1 - p weights must match realitycompare the positive rate in the eval set against production monitoring
No segment matters more than anotheraccuracy aggregates all rows equallyslice accuracy by segment; a 5% segment at 60% is invisible inside a 95% overall
Decisions are hard labelsaccuracy is thresholded and cannot rankif you need a top-k review queue, use precision@k instead

When it doesn't. A rare class matters (use PR-AUC or recall at a fixed FPR), error costs differ (use expected cost or a cost-weighted loss), capacity is bounded (precision@k), or you need probabilities (log loss or Brier: accuracy is not a proper scoring rule and is blind to calibration: a 0.51 and a 0.99 prediction score identically).

Failure modes and how to catch them.

  • Majority collapse: compare against a DummyClassifier baseline. If the gap is under a point, the model learned nothing.
  • Subgroup failure: slice accuracy per group. Overall 95% with a 60% subgroup is a deployment risk, not a rounding error.
  • Prior shift: monitor the production positive rate and recompute accuracy under the deployment prior before trusting the offline number.
  • Threshold sensitivity: sweep the threshold and plot accuracy. Near the boundary a 0.01 move can swing whole percentage points; a flat curve means the score is uninformative.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How do prevalence changes affect classification metrics?

Answer

Core answer (first 90 seconds)

Prevalence changes the composition of the prediction set, not the classifier's behavior at a fixed threshold. If the class-conditional score distributions P(s|y) and the threshold are unchanged, TPR, FPR, TNR, FNR, the likelihood ratio TPR/FPR, and AUROC are all invariant. Everything that mixes predictions across classes: precision/PPV, NPV, accuracy, F1, MCC, alert volume, AUPRC, and the calibration map: moves, sometimes by an order of magnitude.

The reason is Bayes. Precision = π·TPR / (π·TPR + (1−π)·FPR). Prevalence sits in the denominator next to FPR, so when π is small the false-positive term dominates.

Worked arithmetic

Fixed threshold, TPR = 0.90, FPR = 0.05, N = 100,000.

π = 1%π = 10%
TP / FN900 / 1009,000 / 1,000
FP / TN4,950 / 94,0504,500 / 85,500
Precision900/5,850 = 15.4%9,000/13,500 = 66.7%
NPV94,050/94,150 = 99.89%85,500/86,500 = 98.84%
Accuracy94.95%94.50%
F10.2630.766
Alerts per 100k5,85013,500
FP per TP5.50.5

TPR and FPR are identical in both columns. Precision moves 4.3×, F1 moves 2.9×, accuracy moves 0.45 points, and the false-positive burden per true positive moves 11×. A majority-class classifier at π = 1% scores 99% accuracy with zero recall: the accuracy paradox is just this table with TPR = 0.

Failure modes and how to catch them

  1. Alert fatigue from precision collapse. A model tuned at 10% prevalence deployed at 1% keeps its 5% FPR, so 4,950 of 5,850 alerts are false. At 15 minutes of human review per alert that is ~1,240 hours of wasted review per 100,000 screened. Detect by tracking adjudicated-alert precision weekly; a drop below the training-prevalence estimate by more than the Bayes factor predicted means the deployment prevalence moved.

  2. Stale calibration. A score of 0.70 calibrated at π = 0.10 means 0.175 at π = 0.01. Prior correction: p' = p·(π'/π) / [p·(π'/π) + (1−p)·((1−π')/(1−π))]. Check with a reliability diagram and expected calibration error on a deployment-prevalence sample; don't trust the training-set ECE.

  3. Case-control training. Train on a 50/50 resample and deploy at 1%: the same 0.70 becomes 0.023, a 30× inflation. Detect by comparing mean predicted probability to the observed base rate; fix by correcting the intercept, not by re-thresholding.

  4. AUROC looks fine, PR-AUC doesn't. AUROC is prevalence-invariant; AUPRC's no-skill baseline is the prevalence itself (0.01 vs 0.10 here). Comparing AUPRC across prevalences without the baseline is meaningless. Report AUPRC alongside its baseline, or report precision at a fixed recall.

What to report

State the evaluation prevalence, the confusion counts, and TPR/FPR at the operating threshold. If you reweight to a deployment prevalence, say which prevalence and why: reweighting assumes P(s|y) is unchanged between the two populations, which is exactly the assumption a covariate shift breaks. Re-check the threshold after any real population or policy change, because the cost-optimal threshold depends on π through the FP:TP ratio.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Compare ROC AUC and precision-recall evaluation.

Answer

Both are threshold-free summaries of a ranking, so neither one picks an operating point. What decides between them is how rare the positive class is, and whether a false positive costs the same as a false negative.

ROC plots TPR against FPR across all thresholds. AUC equals the probability that a random positive outranks a random negative, has a 0.5 baseline, and is prevalence-invariant: it depends only on the score distributions inside each class. PR plots precision (TP/(TP+FP)) against recall. Its baseline is the prevalence itself, and the curve moves when prevalence moves.

That difference is the whole argument. Take a model whose chosen threshold gives TPR 0.80 and FPR 0.05:

1% prevalence (100 pos / 9,900 neg)50% prevalence (100 pos / 100 neg)
TP8080
FP4955
precision80/575 = 0.1480/85 = 0.94
ROC point(0.05, 0.80)(0.05, 0.80)

Identical ROC point, precision 0.14 versus 0.94. ROC AUC cannot see the difference; PR shows it immediately.

Scale it. One million events a day at 1% prevalence is 10,000 positives and 990,000 negatives. At TPR 0.8 and FPR 0.05 you emit 8,000 true alerts and 49,500 false ones: 57,500 alerts a day, 86% of them wrong. At 50 alerts per analyst per day that is roughly 1,150 analyst-days of work per day. That is the operational cost of choosing ROC AUC on a rare-positive problem and never looking at precision.

Failure modes, with how to catch each:

  • Shipping on ROC AUC alone. Detection: compute precision at the deployed threshold on a held-out set carrying production prevalence, and monitor alerts per day against queue capacity. Cost: the 57,500 alerts/day above.
  • Prevalence shift between evaluation and production. PR AUC is prevalence-dependent, so an average precision measured on a 1% sample does not transfer to a 0.1% stream. Detection: compare the positive rate in the labeled window against training and recompute AP. Cost: capacity sized for the wrong alert volume. A 10x drop in positives means roughly 10x fewer alerts, and the reverse under-staffs.
  • Comparing PR AUC across two models scored on different populations. Detection: check the positive rate of each evaluation set before comparing. Cost: you pick the model that won on the easier sample.
  • Reading one AUC number as the operating point. Detection: plot the curve and inspect the region near the threshold you will actually deploy; a model can win on AUC and lose there. Partial AUC over the relevant FPR band is the fix.

Two details worth stating. Use average precision, the step-wise sum over recall increments, rather than trapezoidal interpolation of the PR curve, which overstates the area. And put an interval on whatever you report: with 100 positives, a recall of 0.80 has a 95% interval of about ±0.08, so a 0.02 AUC gap between two models on that test set is noise.

When to use which: ROC when both classes matter, prevalence is stable, or you need a ranking comparable across populations. PR when positives are rare and false positives dominate the cost: fraud, abuse, retrieval, alerting. Neither replaces the threshold decision. Pick it from the cost ratio and the queue capacity: if a false alert costs $5 of analyst time and a missed fraud costs $500, the threshold sits where the likelihood ratio crosses 100:1.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do you select a classification threshold?

Answer

Core answer (first 90 seconds). A threshold isn't a property of the model: it's the operating point where the marginal cost of one more false negative equals the marginal cost of one more false positive. Two inputs decide it: calibrated probabilities and a stated objective. If the scores are calibrated, the cost-minimizing rule is closed-form: flag when p > C_FP / (C_FP + C_FN). With a $5 manual review and a $400 chargeback, that's p > 5/405 ≈ 0.012. If you can't defend the costs, the objective becomes a constraint instead: maximize recall subject to flagged volume ≤ review capacity, or precision ≥ some floor. State which one you're using before quoting a number.

Worked sweep. Validation set of 100,000 transactions, 1,000 frauds (1% prevalence). C_FN = $400, C_FP = $5.

thresholdflaggedTPFPFNcost
0.501,200600600400$163,000
0.104,0008503,150150$75,750
0.0212,00097011,03030$67,150
0.01216,00098515,01515$81,075
0.00530,00099529,0055$147,025

The minimum is interior, at 0.02, not at "flag everything" or "flag nothing." Pushing recall from 0.97 to 0.995 costs $80k/day because false positives grow faster than true positives. The closed-form 0.012 predicts a lower threshold than the sweep finds; the gap is tail miscalibration, which is why I sweep rather than trust the formula. If the review team handles 15,000/day, 0.012 is infeasible (16,000 flagged) and capacity binds, so 0.02 wins.

Sweep code:

Python
import numpy as np

def best_threshold(y, p, c_fp, c_fn):
    order = np.argsort(-p)
    y = y[order]
    tp = np.cumsum(y)
    fp = np.cumsum(1 - y)
    fn = y.sum() - tp
    cost = c_fp * fp + c_fn * fn
    i = np.argmin(cost)
    return p[i], cost[i]

Alternatives, and when each is wrong. Top-k (flag the highest-scoring k%) is robust to score drift but ignores prevalence: if fraud goes 1% → 3%, you flag the same volume and miss two-thirds of the new fraud. A two-threshold abstention band (auto-approve below t_low, human review between, auto-block above t_high) is right when review is the bottleneck and the middle band is genuinely ambiguous; it's wrong when you can't staff the band. Per-cohort thresholds fix a global threshold that under-flags a small cohort, but they need legal review and enough positives per cohort to estimate.

Failure modes. Prevalence drift moves the flagged volume even when the Bayes threshold doesn't: at 3% prevalence, t=0.02 flags roughly 36,000/day and swamps the queue. Monitor flagged volume and prevalence, not just AUC. Retraining shifts calibration: a new model with identical AUC but scores compressed toward 0.5 moves the operating point, so re-sweep and check the reliability curve (Brier score, ECE) before reusing the old threshold. Cost drift, chargebacks rising from $400 to $600, moves the optimum to 5/605 ≈ 0.008; version the cost assumptions with the threshold. And with 1% prevalence, ROC AUC of 0.98 can coexist with precision 0.08 at the operating point, so select on the precision-recall curve, not ROC. Pick on validation, confirm once on a held-out test set, then freeze the threshold with the cost assumptions it was derived from.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Compare log loss and Brier loss.

Answer

Core answer. Both are strictly proper: their expected value is minimized by reporting the true conditional probability, so neither can be gamed by hedging or by overconfidence in expectation. They differ in the shape of the penalty. Log loss is the negative log-likelihood of the true class, unbounded above, and it diverges as the probability assigned to the true class goes to zero. Brier is the squared error of the probability, bounded in [0,1]. If a confident wrong probability is expensive (risk pricing, anything where the tail is the point) log loss is the honest score. If you want a bounded, outlier-robust score, or the reliability/resolution decomposition to separate calibration from discrimination, Brier is the better instrument. They usually rank models the same way; they disagree when one model is confidently wrong on a few examples.

Mechanism. For one example with true label y and predicted p:

  • Log loss: L = −[y ln p + (1−y) ln(1−p)], gradient dL/dp = (p − y)/(p(1−p)).
  • Brier: B = (p − y)², gradient dB/dp = 2(p − y).

The gradient is the whole story. At p = 0.999 with y = 0, the log-loss gradient is 0.999/(0.999 × 0.001) = 1000; the Brier gradient is 2 × 0.999 ≈ 2.0. Log loss pulls roughly 500× harder on that single example. That is why one confident error can dominate a log-loss mean and barely move a Brier mean.

Per-example penalty, y = 0:

plog lossBrier
0.50.6930.250
0.92.3030.810
0.994.6050.980
0.9996.9080.998
0.99999.2100.99998

Log loss grows without bound; Brier saturates at 1. That is the practical difference in one table.

Decomposition. Brier has the clean Murphy decomposition B = reliability − resolution + uncertainty, where uncertainty = ȳ(1−ȳ) depends only on the base rate. That makes raw Brier scores incomparable across datasets with different positive rates unless you report the terms separately. Log loss has an analogous reliability/resolution split, but the terms are KL divergences rather than squared errors. Log loss is also the only strictly proper local score up to affine transformation: it depends on each example only through the probability assigned to the true class, which is why it is the objective logistic regression and most neural classifiers already optimize.

When each wins.

  • Log loss: you care about the probability itself, the tail matters, or you are already fitting by maximum likelihood. The right default for a calibrated risk model.
  • Brier: you want a bounded score, you want to compare across base rates via the decomposition, or you want robustness to a handful of confident errors. It is the standard in weather forecasting for exactly this reason.

Failure modes and detection.

  • Clipping. Log loss is undefined at p ∈ {0, 1}. Clipping to [1e-15, 1−1e-15] caps the per-example loss at ≈34.5. Document the clip; it changes the score.
  • One example dominating. Compute the max per-example log loss and the share of total loss from the top 1% of examples. If the top 1% carries more than half the loss, the mean is a tail statistic, not a summary.
  • Brier hiding tail miscalibration. A model that never predicts outside [0.1, 0.9] can post a respectable Brier while being badly wrong in the tails. Plot a reliability diagram and inspect the extreme bins.
  • Neither is a ranking metric. Both are proper, so both reward calibration; if you only care about ordering, report AUC or a rank score alongside, not instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

What does probability calibration mean, and how do you evaluate it?

Answer

The 90-second answer. A model is calibrated when its predicted probabilities match observed frequencies: of all the cases it scores near 0.8, about 80% should be positive. Calibration is a property of the number, not of the ranking: a model can have AUC 0.90 and be badly calibrated, and a monotone calibrator (Platt, isotonic) leaves AUC exactly unchanged. So I evaluate three things together: a reliability diagram that prints bin counts, ECE computed from those bins, and a proper score (Brier or log loss) decomposed into reliability, resolution and uncertainty, so I can tell miscalibration from weak discrimination. The calibrator is fit on scores the base model never trained on, out-of-fold predictions or a held-out split, and checked on a third, untouched set.

Why models come out miscalibrated. Boosted trees and SVMs push scores toward the extremes; a softmax net is overconfident by construction; class reweighting or negative downsampling shifts the base rate so the output no longer matches deployment prevalence. Platt scaling fits a 1-D logistic on the score (two parameters); isotonic regression fits a monotone step function. Niculescu-Mizil and Caruana (ICML 2005) found sigmoid scaling reliable from roughly 1,000 samples, while isotonic needs more and otherwise overfits into step artifacts. Neither fixes a bad ranking.

Worked example (hypothetical numbers). 1,000 held-out predictions, five equal-count bins:

binmean predicted pobserved ratecount
[0.0, 0.2)0.100.08200
[0.2, 0.4)0.300.26200
[0.4, 0.6)0.500.52200
[0.6, 0.8)0.700.78200
[0.8, 1.0]0.900.95200

ECE = Σ (n_b/N)·|p_b − o_b| = 0.2 × (0.02 + 0.04 + 0.02 + 0.08 + 0.05) = 0.042. Brier decomposition with base rate ō = 0.518: reliability = mean (p_b − o_b)² = 0.00226, resolution = mean (o_b − ō)² = 0.1027, uncertainty = ō(1−ō) = 0.2497, so Brier = 0.00226 − 0.1027 + 0.2497 = 0.149. The reliability term is small while ECE is 0.042: the two disagree because ECE is absolute and unweighted by variance, which is exactly why I never read one scalar.

Python
import numpy as np
p = np.array([0.10, 0.30, 0.50, 0.70, 0.90])  # bin mean predicted
n = np.array([200, 200, 200, 200, 200])       # bin counts
o = np.array([0.08, 0.26, 0.52, 0.78, 0.95])  # bin observed rate
ece = np.sum(n / n.sum() * np.abs(p - o))
print(round(ece, 4))   # 0.042

In scikit-learn 1.5: CalibrationDisplay.from_predictions(y, prob, n_bins=10, strategy='quantile') for the diagram, and CalibratedClassifierCV(estimator=clf, method='sigmoid', cv=5) to fit. cv=5 gives out-of-fold scores, so the calibrator never sees in-sample predictions.

Failure modes. (1) Aggregate ECE 0.042 looks fine while one slice is broken: on a new-merchant cohort the top bin predicts 0.90 and observes 0.62. Detect with per-slice ECE requiring ≥ 50 positives per bin, alerting when slice ECE exceeds 0.05 in two consecutive daily windows; at 2% prevalence that needs ~2,500 scored cases per window. (2) Calibrator leakage: fit on in-sample scores, ECE reads 0.01 in-sample and 0.06 on the held-out third. (3) Prevalence shift: a calibrator fit at 5% base rate deployed at 1% makes every probability too high; monitor rolling mean(p) − mean(y) and refit when it exceeds 0.02, remembering that a 30-day label delay means you are always calibrating on stale prevalence. (4) Bin noise: 10 equal-width bins over 200 samples is 20 per bin, where ECE swings ±0.05 from sampling alone. Print counts and switch to quantile bins.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Explain micro, macro, and weighted averaging for multiclass metrics.

Answer

The 60-second answer. All three collapse per-class scores into one number; they differ in what gets pooled.

  • Micro pools every decision across all classes and computes the metric once. On single-label multiclass, micro precision = micro recall = micro F1 = accuracy, because each prediction is exactly one class and each error is one false positive plus one false negative. It answers "how often is the model right per instance."
  • Macro computes the metric per class, then takes the unweighted mean. A class with 10 examples counts the same as one with 10,000. It answers "how well does the model do on a typical class," which is what you want when rare-class performance is the point.
  • Weighted takes the same per-class scores and weights each by its support. It answers "how well does the model do on a typical instance," and it tracks whatever class distribution you happen to have.

Worked example. Three classes, 140 instances. Rows are true labels, columns predicted:

        A    B    C
A      90    8    2     (100)
B       5   20    5     ( 30)
C       1    1    8     ( 10)

Correct predictions: 118 of 140.

classsupportprecisionrecallF1
A10090/96 = 0.93890/100 = 0.9000.918
B3020/29 = 0.69020/30 = 0.6670.678
C108/15 = 0.5338/10 = 0.8000.640
macro—0.7200.7890.745
weighted1400.8560.8430.847
micro1400.8430.8430.843

Two identities fall out of this and are worth carrying into the room: micro F1 equals accuracy (118/140 = 0.843), and weighted recall always equals accuracy, because weighted recall is Σ TPᵢ / N. Weighted precision and F1 do not have that shortcut.

In scikit-learn the choice is always explicit: the default average='binary' raises on multiclass input:

Python
from sklearn.metrics import precision_recall_fscore_support as prfs
prfs(y_true, y_pred, labels=['A','B','C'], average=None)      # per-class
prfs(y_true, y_pred, labels=['A','B','C'], average='macro')
prfs(y_true, y_pred, labels=['A','B','C'], average='weighted')
prfs(y_true, y_pred, labels=['A','B','C'], average='micro')

What changes the decision. The gap between macro and weighted is the class imbalance, and it is where the two disagree. Take the same model and make it fail class C entirely (recall 0.800 → 0.000): macro recall drops 0.789 → 0.522, about 27 points, while weighted recall drops 0.843 → 0.786, about 6 points. Same errors, two very different headlines. That is the whole argument for reporting both.

Failure modes. Macro on a class with support 1 lets a single flipped example swing the score by roughly 1/k; always print per-class support next to it. Weighted hides rare-class collapse, as above. Micro is dominated by the majority class, so it can look healthy while a small class is at zero. And neither macro nor micro is comparable across runs with different label sets or class balance: adding a class changes macro's denominator, and rebalancing the data changes micro's. Disclose the label set and the support when you quote a number.

Close. If the decision is "does the model work for the users we have," report weighted or micro plus per-class support. If it is "does it work for every class we care about," report macro and show the per-class rows, because macro alone tells you the average moved without telling you which class failed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

How do you evaluate multilabel classification?

Answer

What I say first

Two things decide the metric before I compute anything: whether the label set is fixed and closed, and whether a false positive and a false negative cost the same for every label. In practice they never do, so a single number is the wrong deliverable. I report a fixed panel: subset accuracy, micro-F1, macro-F1, per-label F1 with support, and mean predicted cardinality against true cardinality, and I name which one is primary based on the error cost. The rest exist to catch the primary metric lying.

Why the averages disagree

Micro-F1 pools every (sample, label) decision into one confusion matrix: TP, FP and FN summed over labels, then F1 computed once. A label with 10,000 positives contributes 10,000 times as much as a label with one positive, so micro-F1 tracks the head of the distribution and is nearly blind to rare labels. Macro-F1 computes F1 per label and takes the unweighted mean, so each label moves the score by 1/L regardless of support. With L=200 labels, one label collapsing from F1 0.9 to 0.0 costs macro 0.0045, small, but a label with 3 positives can swing it by 0.005 on a single flipped example, which is why macro on tiny support is noise rather than signal. Weighted-F1 weights each label's F1 by its support, so it inherits micro's blindness.

A worked panel

5 samples, 4 labels, binary indicator matrices. A and B are common; C and D have one positive each.

labelsupportTPFPFNprecisionrecallF1
A44001.001.001.00
B33001.001.001.00
C1001—0.000.00
D1001—0.000.00

Micro: TP=7, FP=0, FN=2 → P=1.00, R=7/9=0.778, F1=14/16=0.875. Macro F1: (1.00+1.00+0.00+0.00)/4 = 0.500. Subset accuracy: 3 of 5 samples exactly right = 0.600. Hamming loss: 2 wrong cells out of 20 = 0.100. Samples-averaged F1: per-sample F1 = 1.00, 1.00, 0.80, 0.667, 1.00 → 0.893.

Micro says 0.875, macro says 0.500. Both are right; they answer different questions. The 0.375 gap is entirely the two single-positive labels, and that gap is what I put in front of someone asking "is the model good".

Python
from sklearn.metrics import accuracy_score, hamming_loss, f1_score, classification_report
# y_true, y_pred: (n_samples, n_labels) binary indicator arrays
accuracy_score(y_true, y_pred)               # 0.600  subset accuracy
hamming_loss(y_true, y_pred)                 # 0.100
f1_score(y_true, y_pred, average="micro")    # 0.875
f1_score(y_true, y_pred, average="macro")    # 0.500
f1_score(y_true, y_pred, average="samples")  # 0.893
print(classification_report(y_true, y_pred, zero_division=0))

Thresholds

Scores are per-label, so the decision is L thresholds, not one. I fit them on validation, never on test: for each label, sweep the precision-recall curve and take the threshold maximizing that label's F1, or the lowest threshold that hits a target precision when a false positive is expensive. Two traps. First, L thresholds fitted on a validation set with few positives per label overfit: with 200 labels and 500 validation positives, most labels have 1-3 positives and the chosen threshold is noise. I fall back to one shared threshold or a few buckets by support, and check the validation-to-test F1 gap per label. Second, thresholds tuned for F1 are not calibrated; if downstream code multiplies probabilities or compares them across labels, tune for calibration instead (scikit-learn's TunedThresholdClassifierCV, added in 1.5, does the F1-style sweep with cross-fitting).

Failure modes I check for

  • Dead rare label. Micro-F1 reads 0.875 while label C has recall 0. Detect it with the per-label recall table and a count of labels with recall 0 and support ≥ 1. Cost: the rare label is usually the one the system exists for.
  • Threshold overfitting. Detect by subtracting per-label test F1 from validation F1; a gap above roughly 0.1 on labels with support under 10 means the threshold did not generalize.
  • Cardinality drift. Independent sigmoids impose no joint constraint, so mean predicted positives can drift from true cardinality under shift. Detect by plotting mean predicted cardinality against true cardinality per time bucket.
  • Hierarchy violations. Predicting a child label without its parent. Detect by counting violations per parent; the cost is a downstream rule engine rejecting the record.

I report the panel with per-label support, and I state the group or time split the numbers came from.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Compare MAE, MSE, and RMSE.

Answer

Short answer: all three measure the same residuals, but they disagree about how much a big miss should cost. MAE charges linearly, MSE charges quadratically, RMSE is just the square root of MSE so it reads in target units again. Pick the one whose penalty matches what a wrong prediction actually costs you.

Assumptions I'd state first: same test set, same units, predictions and actuals on the same scale, and residuals treated as exchangeable across the cohort. If any of those break: e.g. you're averaging over segments with very different variance: the aggregate hides more than it shows.

Why squaring changes behaviour. With residuals $r_i = y_i - \hat{y}_i$:

  • MAE $= \frac{1}{n}\sum |r_i|$, gradient w.r.t. a prediction is $-\text{sign}(r_i)/n$: constant magnitude. A 200-unit miss pulls exactly as hard as a 10-unit miss.
  • MSE $= \frac{1}{n}\sum r_i^2$, gradient is $-2r_i/n$: linear in the residual, so a 200-unit miss pulls 20× harder than a 10-unit miss.
  • RMSE $= \sqrt{\text{MSE}}$ has the same minimiser as MSE; its gradient is just MSE's scaled by $1/(2,\text{RMSE})$, so it trains identically and only changes the reporting units.

That single difference explains the rest: MSE/RMSE are smooth everywhere and gradient descent behaves well; MAE is non-differentiable at $r=0$ (libraries use the sign subgradient, so the gradient is 0 there) and its constant-magnitude gradient means it can crawl near the optimum or oscillate. MAE's minimiser is the conditional median, MSE's is the conditional mean, so on a skewed target, MAE quietly predicts the median.

Worked numbers. Five house prices in $1000s, actual [100, 200, 300, 400, 500], predicted [110, 190, 300, 380, 700]. Residuals: 10, -10, 0, -20, 200.

metriccomputationvalue
MAE(10+10+0+20+200)/548
MSE(100+100+0+400+40000)/58120
RMSE√8120≈ 90.1

One 200k miss nearly doubles RMSE over MAE (90 vs 48). MSE's 8120 is in dollars-squared and is not reportable; that's the only reason RMSE exists.

Failure modes and how to detect them.

  • MSE/RMSE explode under heavy tails. A single outlier dominates the loss. Detect by comparing the two: an RMSE/MAE ratio well above ~1.3–1.5 signals a fat tail, and a residual histogram or QQ plot confirms it. Fix with Huber or quantile loss, or by modelling the tail separately.
  • MAE under-penalises large misses. Being off by 200k on one house costs the same per-unit as being off by 10k on twenty. If a big miss is catastrophic, MAE will happily choose that model.
  • MAE's non-differentiability and flat gradient slow convergence and can leave you oscillating around the optimum; smooth it with Huber if training stalls.
  • Aggregate hides cohorts. Report per-segment MAE/RMSE, not just the global number.

What would change the decision: if the cost of error is roughly linear (inventory overage, staffing), use MAE; if large errors are disproportionately expensive (structural load, safety margins), use RMSE; if the target is skewed and you care about the mean, don't let MAE's median bias fool you. I'd show the residual distribution and the RMSE/MAE ratio next to whichever aggregate I quote.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Explain R-squared and its common misinterpretations.

Answer

R² answers one narrow question: how much of the evaluation set's squared error does my model remove compared with always predicting the mean of that same set? Formally, R² = 1 − SSE/SST, where SSE is the sum of squared residuals and SST is the sum of squared deviations of the true values from their mean. One is perfect, zero is the mean baseline, and negative means you'd have done better predicting the mean. That's the whole definition: everything else people say about it is an interpretation, and most of them are wrong.

Let me make it concrete. Take three targets, y = [10, 20, 30], so the mean is 20 and SST = 100 + 0 + 100 = 200. A model predicting [12, 20, 28] has residuals −2, 0, 2, so SSE = 8 and R² = 1 − 8/200 = 0.96. A lazier model predicting [15, 20, 25] has SSE = 50 and R² = 0.75. Fine so far.

Now the first misinterpretation: R² is not a property of the model, it's a property of the model and the target spread. Keep the good model's SSE at 8 but widen the targets to [0, 20, 40]. Now SST = 400 + 0 + 400 = 800 and R² = 1 − 8/800 = 0.99. Same absolute error, higher R², purely because the target varies more. That's why comparing R² across datasets, across time windows, or across a filtered slice is unsafe: you're comparing denominators, not models. If you must compare, compare SSE or RMSE in target units.

Second: negative R² is not a bug. Predict a constant 40 for y = [10, 20, 30]: residuals −30, −20, −10, SSE = 1400, R² = 1 − 1400/200 = −6. The model is six times worse than the mean. On a held-out set this is the single most useful signal you get: a model with training R² of 0.9 and test R² of −0.2 is overfitting, and you'd never see that from an accuracy-style metric.

Third, and the one that costs money: high R² does not mean the model learned the mechanism. Fit a time index against a trending target, say monthly revenue that grows steadily, and you'll get R² above 0.95 from a model that has learned nothing but the trend. It will fail the moment the trend breaks. The detection is residual plots against time and against each feature: a high R² with structure left in the residuals means the number is describing the trend, not the model.

Fourth: R² is not calibration and not decision quality. A model can rank well and be badly scaled: R² 0.8 with predictions that are all 20% too high. And it says nothing about whether the errors land where they matter. A model with R² 0.9 overall can have R² −0.5 on the 5% of rows that are your high-value segment.

So when is R² the right metric? When the target is continuous, the loss is squared error, and you want a scale-free summary against a mean baseline on a fixed evaluation set. When it isn't (classification, asymmetric costs, ranking, or any cross-population comparison) use something else. In practice I report R² alongside RMSE in target units, a residual plot, and per-slice R², and I treat a big train/test R² gap as the first thing to investigate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you evaluate a regression model?

Answer

First 90 seconds. I fix four things before choosing a metric: the unit of error and what it costs, whether the decision is symmetric, the horizon, and the incumbent I have to beat. Then I score against a baseline, seasonal naive (same weekday last week) or DummyRegressor(strategy="median"), never against zero.

If the decision is asymmetric, MAE is the wrong summary. Forecasting daily order volume for staffing: under-forecasting by 100 units buys overtime, over-forecasting by 100 buys idle capacity. Different prices, so I score with pinball loss at the quantile the decision needs: q=0.9 if I want to be covered nine days in ten, not the mean.

The split is time-ordered, never shuffled: 18 months train, 3 months validation for tuning, 3 months held out. Rolling origin, refit monthly, three folds (TimeSeriesSplit gives the folds; the refit happens inside each). I report per-fold numbers, because 8 / 9 / 40 across folds is a worse model than 14 / 15 / 16 even when the means match.

MAE vs RMSE, worked. Eight days of actuals and predictions, residual = actual − pred:

dayactualpredresidualabs errsq err
1100105−5525
2120115+5525
390100−1010100
4150140+1010100
5110115−5525
6130125+5525
795100−5525
8400150+25025062500

Sum of absolute errors 295, so MAE = 295/8 = 36.9. Sum of squares 62,825, so MSE = 7,853 and RMSE = 88.6. Drop day 8 and MAE falls to 45/7 = 6.4 while RMSE falls to √(325/7) = 6.8. One 250-unit miss moves MAE by 5.7× and RMSE by 13×. If a single bad day is the business problem, RMSE tells you; if every day's error costs the same, MAE is the honest number and RMSE is quietly letting day 8 drive your tuning. scikit-learn 1.4's mean_absolute_error and mean_squared_error compute exactly those two columns.

Pinball at q=0.9 on day 8: under-forecasting by 250 costs 0.9 × 250 = 225; over-forecasting by 250 would cost 0.1 × 250 = 25. Nine times the penalty, which is the asymmetry MAE erases.

Failure modes, and how I catch each.

Leakage. Usually a feature computed over the whole history: "days since last order", a rolling mean, or a scaler fit on all rows. Symptom: random-split MAE of 6 against time-split MAE of 31. Re-run with a shuffled split; if the score jumps, you have leakage, not skill.

Drift between slices. Aggregate MAE 8 hides MAE 45 on the top decile of the target range, or on weekends. Slice by target decile × weekday/weekend × horizon step. Horizon matters most: step-1 error is routinely a third of step-30.

Interval miscalibration. A nominal 90% interval covering 62% of held-out actuals is worse than no interval, because someone will staff to it. Check empirical coverage per fold and a PIT histogram; it should be flat.

Baseline blindness. A model at MAE 12 that loses to seasonal naive at 11 is not a model. Print the baseline column every time.

What I report. MAE and RMSE (or pinball at the decision quantile), the baseline's same numbers, per-fold and per-slice breakdowns, empirical interval coverage, and the residual distribution rather than just its mean. R² only as context: it is scale-dependent and says nothing about what a miss costs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do you evaluate quantile predictions and prediction intervals?

Answer

What I say first. Two objects, two scores. A single quantile q̂_τ is scored with pinball loss at its own level τ. A central interval [l, u] is scored with the interval (Winkler) score, which charges width plus a penalty for each miss. Coverage alone is not a score ([−∞, ∞] covers everything) so I report coverage and width together, and read them on a reliability diagram. Then I slice both by horizon, cohort and target range, because marginal numbers hide conditional failures.

Pinball loss. For observation y and prediction q at level τ:

L_τ(y, q) = max(τ(y − q), (τ − 1)(y − q))

which is τ(y − q) when y ≥ q and (1 − τ)(q − y) when y < q. It is a proper scoring rule: its expectation is minimized by the true τ-quantile, so predicting the conditional mean at τ = 0.9 is punished, not rewarded. Average it over the evaluation set and report it against a baseline (empirical quantiles from the training window, or the previous model) as a skill score. Raw pinball values are scale-dependent and mean nothing on their own.

Interval score. For a central (1 − α) interval:

IS_α(l, u, y) = (u − l) + (2/α)(l − y)·1{y < l} + (2/α)(y − u)·1{y > u}

Width rewards sharpness; the 2/α term penalizes misses, scaled so the score stays proper. The weighted interval score (WIS) averages IS across levels with weights α_k/2 plus a median term: the standard aggregate in the COVID-19 Forecast Hub.

Worked trace. Five observations, three predicted quantiles:

Python
import numpy as np

def pinball(y, q, alpha):
    d = y - q
    return np.maximum(alpha * d, (alpha - 1) * d)

y   = np.array([10., 12.,  9., 15., 11.])
q10 = np.array([ 8.,  9.,  8., 10.,  9.])
q50 = np.array([11., 11., 10., 12., 11.])
q90 = np.array([14., 13., 12., 16., 14.])

for a, q in [(0.1, q10), (0.5, q50), (0.9, q90)]:
    print(a, pinball(y, q, a).mean())

Output: 0.1 0.26, 0.5 0.6, 0.9 0.24. Hand-check the first row: y − q is [2, 3, 1, 5, 2], all positive, so each loss is 0.1 × that = [0.2, 0.3, 0.1, 0.5, 0.2], mean 0.26. The 80% interval [q10, q90] contains all five points: empirical coverage 1.00 against a nominal 0.80, and mean width is 5.0. Over-covering at that width is the classic too-wide model: coverage passes, sharpness fails.

Diagnostics I actually plot.

diagnosticcatchesread
mean pinball per levelbias at that levelvs baseline skill score
empirical vs nominal coveragemarginal calibration0.80 nominal, 1.00 observed → too wide
mean interval widthsharpnessonly meaningful beside coverage
PIT histogram / reliability curveconditional miscalibrationU-shape = too narrow, ∩ = too wide, shift = bias
crossing countinvalid quantile setany q_lo > q_hi at a timestamp
coverage by slicehidden conditional failure90% overall, 70% on top target decile

Failure modes. Quantile crossing: a model emits q_0.1 > q_0.9 at some timestamps; count them and fix by monotone rearrangement (sorting the predicted quantiles). Marginal coverage masking conditional failure: 90% overall but 70% on the top decile of the target, which is exactly where provisioning decisions live; group-conditional conformal or per-slice reporting exposes it. Tuning coverage on the test set: select on a rolling-origin backtest, report on a held-out window. Distribution shift: rolling coverage decays; monitor with an EWMA or CUSUM on the coverage residual and recalibrate (conformal or quantile recalibration) rather than retraining blind.

Temporal dependence. Forecast errors are autocorrelated, so a binomial confidence interval on coverage is far too narrow. Use a moving-block bootstrap or a Diebold–Mariano test with HAC standard errors when comparing two models' losses; the effective sample size is much smaller than the row count.

When not to use this. If the quantile feeds a decision: provisioning at q_0.95, say: score the downstream cost, not just pinball. A model can win on pinball and lose on the decision it drives.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you evaluate a ranking or retrieval model?

Answer

Core answer (first 90 seconds). Fix the evaluation unit first: a query for search, a session for a feed. Then reproduce the exact serving path (candidate generation, eligibility filters, ranking, and the displayed cutoff) because a metric computed over a different candidate set measures a different system. Report NDCG@k as the headline for graded relevance, precision/recall@k when coverage matters, MRR when only the first hit counts. Split by query-frequency bucket and by zero-result rate, and trust the offline number only when judgment coverage is high. The ship decision comes from an online experiment, not the offline delta.

Why the metrics behave as they do. NDCG (Järvelin & Kekäläinen, 2002) discounts each result by 1/log2(rank+1): position 1 weight 1.000, position 2 0.631, position 3 0.500, position 10 0.289. The log is a stand-in for the steep drop in attention and utility as a user scans down. Worked trace, grades A=3, B=2, C=1, D=0, E=2:

rankmodel doc (grade)1/log2(r+1)contribution
1A (3)1.0003.000
2C (1)0.6310.631
3B (2)0.5001.000
4E (2)0.4310.861
5D (0)0.3870.000
DCG@55.492

Ideal order A,B,E,C,D gives IDCG@5 = 5.693, so NDCG@5 = 5.492/5.693 = 0.965. Move the irrelevant D to the top and NDCG@5 falls to 0.720: one bad top result costs more than several mediocre ones lower down. That asymmetry is the whole point of the discount.

Exposure bias, concretely. Offline labels come from clicks on results the current ranker already chose to show. Items never surfaced have no labels, and P(click | relevant) falls with position, so raw labels over-credit whatever the logging policy ranked high. Inverse propensity scoring reweights each logged impression by 1/P(shown at that position); a doubly robust estimator adds an imputation model so the estimate survives a wrong propensity. Skip this and a new ranker that surfaces different items looks worse than it is.

Failure modes and how you catch them.

  • Zero-result rate: monitor the fraction of queries with no eligible doc. A jump from 0.5% to 3% after a filter change is a candidate-generation regression, not a ranking one.
  • Judgment coverage: if only 60% of top-10 docs are judged, unjudged docs score 0 and NDCG understates. Track pooled coverage; fix by pooling judgments across systems.
  • Tail queries: head queries carry thousands of labels, tail carry none. Report NDCG per frequency bucket: a model can win on head and lose on tail.
  • Latency: set a p99 budget (say 100 ms for the ranking stage). If a heavier model pushes p99 from 120 to 200 ms, that is a guardrail breach regardless of NDCG.

Choosing the method. Offline is cheap, reproducible, zero user risk: use it to gate regressions. Interleaving compares two rankers on the same queries and typically needs an order of magnitude fewer queries than A/B, but gives only a relative winner, no absolute score. A/B is ground truth: to detect a 0.01 absolute lift on a 0.10 baseline CTR at 80% power, n ≈ 16·p(1−p)/δ² ≈ 14,400 queries per arm. Counterfactual estimators reuse logs but inherit the propensity model's errors. Decide by cost: offline for iteration, interleaving for close calls, A/B for the ship decision.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do you avoid metric leakage and test-set overuse?

Answer

The 90-second answer. Split first, along the axis that matters (time if rows have a timestamp, entity ID if rows repeat per user or patient) into train, development, and a final set you touch once. Fit every learned thing inside the training fold: scalers, imputers, target encoders, resamplers, feature selectors, calibrators, thresholds. Choose the model and the threshold on development. Evaluate on the final set once; if that number changes your design, the set is spent: get new data rather than re-reading it.

Why leakage happens. A transform that sees the whole dataset has already absorbed the test rows' distribution. Target encoding is the worst offender: encoding a category with the mean of its labels, computed before the split, hands the model a compressed copy of the target. Duplicate and near-duplicate rows do the same thing more quietly: the same user in train and test means the model has memorized the answer. Temporal leakage is the third: any feature computed from data that arrives after the label.

Why repeated testing inflates. Each evaluation on the same holdout is a noisy draw. Run 20 comparisons at α = 0.05 and the chance of at least one false "improvement" is 1 − 0.95²⁰ ≈ 0.64. You are no longer measuring the model; you are measuring the maximum of 20 noisy numbers, and the maximum is biased upward.

Arithmetic on the holdout. Accuracy's standard error is √(p(1−p)/n). At p = 0.90 and n = 2,000 that is √(0.09/2000) ≈ 0.0067, i.e. 0.67 percentage points. A 0.5-point "win" on a 2,000-row test set sits inside one standard error. Require an improvement to clear roughly 2 SE before believing it, or apply a 1-SE rule when picking among models.

Code: the leak, and the shuffle test that catches it.

Python
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.utils import shuffle

cv = StratifiedKFold(5, shuffle=True, random_state=0)

# Leaky: the scaler sees every row, including the held-out fold.
X_scaled = StandardScaler().fit_transform(X)
print(cross_val_score(LogisticRegression(), X_scaled, y, cv=cv, scoring="roc_auc").mean())

# Correct: the scaler is fit inside each fold.
pipe = Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression())])
print(cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc").mean())

# Canary: permute the labels. A clean pipeline drops to ~0.5 AUC.
y_perm = shuffle(y, random_state=0)
print(cross_val_score(pipe, X, y_perm, cv=cv, scoring="roc_auc").mean())

If the third line prints 0.7 rather than ≈0.5, something upstream of the pipeline is leaking: a precomputed feature, a duplicate join, or an ID column.

Failure modes and how to catch them.

FailureMechanismDetection
Preprocessing fit before splitScaler/encoder absorbs test distributionLabel-permutation canary stays above 0.5 AUC
Duplicate rows across splitsSame entity in train and testHash feature vectors; count cross-split collisions
Temporal leakageFeature uses post-label dataAssert max(train time) < min(test time); compare random vs time split
Threshold tuned on testThreshold is a fitted parameterLog every test evaluation; threshold must come from dev
Leaderboard overfittingMany submissions, keep the bestGap between public and private scores; fresh holdout

Trade-offs. A single stratified holdout is cheap and fine when you report one fixed model with no tuning. Nested cross-validation (inner loop selects, outer loop estimates) costs k_outer × k_inner fits, so 5×5 = 25 instead of 1, and it is the right call when n is small and you are choosing among many configurations. Repeated holdout or bootstrap resampling buys a variance estimate at similar cost. Nested CV is overkill when the dataset is large, the model is fixed, and the decision is one-shot.

Governance. A submission budget on the final set (a handful of evaluations, not unlimited) plus a written hypothesis before each run is what actually stops overuse; rate limits alone just move the peeking to a colleague's account.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How should uncertainty around model metrics be estimated?

Answer

The 90-second answer. Uncertainty belongs to the sampling design, not the metric. I name the unit that was independently sampled (user, patient, query, session, day) and build the interval over that unit, not over the rows the metric was computed on. Then I ask whether rows inside a unit are correlated, because that decides whether the cheap interval is honest. Then I match the estimator to the metric: analytic for a plain proportion, bootstrap for anything nonlinear in the predictions, paired resampling for model-to-model differences, a multiplicity correction once I start slicing.

Why the naive bootstrap lies. It resamples rows with replacement. With 10 queries per user it draws an arbitrary number of a given user's queries (sometimes six, sometimes none) so between-user variation, the thing that actually moves the metric, is averaged away instead of resampled. The cluster bootstrap draws users with replacement and keeps every row of a drawn user, so each replicate differs by who is in it, which is how next month's data will differ too.

A worked example. Four users, two queries each, per-user accuracy 1, 1, 0, 0. Pooled accuracy is 4/8 = 0.50. Python 3 with NumPy:

Python
import numpy as np
from itertools import product

per_user = np.array([1.0, 1.0, 0.0, 0.0])   # 4 users
rows = np.repeat(per_user, 2)               # 8 rows: 1,1,1,1,0,0,0,0
p = rows.mean()                             # 0.50

naive_se = np.sqrt(p * (1 - p) / len(rows)) # rows treated as independent

# Cluster bootstrap: resample users with replacement, keep both rows.
# Enumerate all 4**4 = 256 resamples exactly, so there is no RNG.
reps = [np.mean([per_user[i] for i in draw])
        for draw in product(range(4), repeat=4)]
cluster_se = np.std(reps)                   # population SD over 256 replicates

print(f"p = {p:.2f}")                       # p = 0.50
print(f"naive SE   = {naive_se:.4f}")       # naive SE   = 0.1768
print(f"cluster SE = {cluster_se:.4f}")     # cluster SE = 0.2500
print(f"ratio      = {cluster_se / naive_se:.3f}")  # ratio      = 1.414

The 256 replicates collapse to five values: a replicate's accuracy is the fraction of the four drawn users who are correct:

correct users drawnreplicate accuracyresamplesprobability
00.00160.0625
10.25640.2500
20.50960.3750
30.75640.2500
41.00160.0625

Variance = 0.0625, SE = 0.250. The naive SE is sqrt(0.25/8) = 0.177. Same data, same point estimate: the interval is 41% wider once the user is the resampling unit. Here rho = 1 (a user is entirely right or entirely wrong), and DEFF = 1 + (2-1)*1 = 2, matching the sqrt(2) ratio.

Sizing the correction. DEFF = 1 + (m - 1) * rho for m rows per cluster and intracluster correlation rho. 500 users, 10 queries each, 5,000 rows, accuracy 0.80, rho = 0.05: DEFF = 1 + 9*0.05 = 1.45, so the SE is sqrt(1.45) = 1.20x the binomial one. Binomial SE = sqrt(0.80*0.20/5000) = 0.0057, 95% interval [0.789, 0.811], width 0.022. Cluster-adjusted SE = 0.0068, interval [0.787, 0.813], width 0.027: 20% wider on identical data. At rho = 0.20 it widens 67%. The temporal case is the same arithmetic: 30 days at rho = 0.05 gives DEFF = 2.45 and an SE 1.57x too small, which is why a block bootstrap with block length near the correlation length is the right resampler for a drifting metric.

Where the normal model breaks. Wilson assumes independent Bernoulli draws at constant p. That holds for one accuracy number and breaks in four places. Correlated rows make it too narrow, as above. AUC, F1 and precision-at-fixed-recall are ratios of two random quantities, so the normal approximation on p is the wrong model and DeLong's test or a bootstrap is the right one. Small event counts break the approximation. Tail quantiles have no closed form: for p99 latency over 10,000 samples, the binomial exact interval for the quantile's rank is 9,900 ± 1.96*sqrt(10,000*0.01*0.99) = 9,900 ± 20, spanning roughly the 80th to the 120th largest observation. Two services separated by one order statistic are not distinguishable at that n.

Model-to-model. Resample the same units for both models. Resampling rows separately keeps each model's interval dominated by the unit-level difficulty in the sample, and that shared component is exactly what should cancel; the paired bootstrap leaves the interval scaling with the variance of the difference.

What the interval will not show. Population drift under a tight interval bites hardest: six weekly readings of 0.80 ± 0.011 look stable while the locale mix moves from 20% to 55% of traffic and the per-locale metric stays flat. The pooled mean is stable by construction, so nothing in the interval shows it. Plot slice composition beside the metric and report per period, not per run. Label noise sets a ceiling: a 300-item audit finding 3% wrong labels means no honest accuracy estimate exceeds about 0.97, and an interval ending at 0.985 is over-claimed; report the audit's disagreement rate beside the metric and re-run on the clean subset. Thirty slices at 95% gives 30*0.05 = 1.5 expected false discoveries; Benjamini-Hochberg at q = 0.10 or Bonferroni at 0.05/30 = 0.0017 fixes that, at the cost that a real but small lift stops clearing the bar. Twelve positives in a 13,000-row slice is a support problem, not an interval problem: put n and the event count beside every number and say "insufficient events" instead of widening the interval to hide it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do you compare two models fairly?

Answer

The 90-second answer. Freeze the comparison protocol before you look at a single result, then compare the two models on the same evaluation rows as paired predictions. A difference of two independent point estimates throws away the pairing and overstates the uncertainty. Report the effect size with a confidence interval, check calibration at the operating point, and only call a winner when the interval excludes the difference you actually care about and the operational gates (latency, cost, error counts) pass.

What "same" has to mean. Same eligible rows (assert the row-ID sets are equal, not just the counts), same labels, same split, same preprocessing fit inside the training fold only, same metric implementation, same threshold-selection rule, same baselines. Hyperparameter search stays inside development; the test set evaluates a locked procedure. If the two models were scored on different test sets, you cannot compare them fairly: that is a stop condition, not a caveat.

Worked check (hypothetical numbers). 5,000-row test set. Model A accuracy 0.842, model B 0.831: a 55-row gap. Build the paired correctness table: both correct 3,900; A correct / B wrong 310; A wrong / B correct 255; both wrong 535. Sums to 5,000, A correct 4,210, B correct 4,155. McNemar with continuity correction on the discordant pairs:

(|310 - 255| - 1)^2 / (310 + 255) = 54^2 / 565 = 2916 / 565 = 5.16

Chi-square, 1 df: 5.16 gives p ≈ 0.023. Significant at 0.05, not at 0.01. That is the honest read: a real but modest edge, and the paired test is what lets you say it at all. For two AUCs on the same rows, DeLong's test is the paired analogue.

Calibration and the operating point. Accuracy hides the threshold. Pick the threshold on validation, then report the confusion counts at that threshold on test. Plot a reliability diagram (10–15 equal-width bins) and report Expected Calibration Error and the Brier score; if the better-ranked model is miscalibrated, Platt scaling or isotonic regression on validation data fixes the probabilities without changing the ranking.

Failure modes, with detection and cost.

failuredetectioncost
Preprocessing fit on all rows (scaler, target encoding)CV score far above held-out; assert fit only on the train foldoffline metric inflated, model degrades in prod
Split leakage: same patient/user in train and testgroup-overlap check on IDsAUC can drop from ~0.91 to ~0.78 on a true holdout
Threshold tuned on testlog where the threshold was chosenoptimistic operating point, wrong error mix
Peeking / many comparisonscount evaluations20 comparisons at α=0.05 gives ~64% chance of a false positive (1 − 0.95^20)
Metric mismatch (macro vs micro F1)unit test on a fixed toy inputwrong winner on imbalanced classes

Trade-offs. Paired tests need the same rows, so they do not work across differently-sampled evaluations. Decide the minimum meaningful difference before running: say 0.5% accuracy or a set cost per 1,000 predictions, so a statistically significant but operationally trivial gap does not win. If the offline difference is real and the gates pass, a shadow or canary deployment, or a randomized experiment, is what confirms downstream impact; the offline comparison only earns the right to run it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you evaluate metrics across demographic or operational slices?

Answer

The first 90 seconds

Slicing is a hunt for the failures the aggregate hides. Before I look at any numbers I fix three things, because once you have seen the numbers you will pick whichever flatters you: the slice list, the minimum support, and the metric the gate reads. Assumptions I state out loud: a fixed-threshold classifier, a labeled holdout the model never trained on, and the slice attribute available at eval time -- usually joined in from a warehouse, often absent at serving, which changes what you can monitor live.

Per slice I report support n, prevalence, precision and recall at the shipped threshold, a 95% interval, and the delta against the aggregate. Recall over AUC: AUC is threshold-free and hides the cut-point regression that actually harms users. The aggregate comparator is mandatory, because a slice number alone is uninterpretable. A point metric publishes only above 100 positives and 100 negatives in the slice; below that I publish the interval and refuse to gate on it.

Why small slices are unstable

A proportion's standard error goes as sqrt(p(1-p)/n), so interval width shrinks like 1/sqrt(n). Region D: 25 labeled rows, 10 positives, 8 caught, TPR 0.800. Aggregate: 5000 rows, 4550 positives, TPR 0.910.

slicenpositivesTPR95% Wilson
aggregate500045500.910[0.902, 0.918]
region D25100.800[0.490, 0.943]

The 11-point gap sits inside the noise. A two-proportion power calculation -- alpha 0.05 two-sided, 80% power, Cohen's h about 0.32 for 0.910 vs 0.800 -- needs roughly 78 positives per slice; at 10% prevalence that is about 780 labeled rows.

Python
# python 3.11, stdlib only
import math

def wilson(k, n, z=1.96):
    if n == 0:
        return (0.0, 1.0)
    p = k / n
    d = 1 + z*z/n
    c = p + z*z/(2*n)
    h = z * math.sqrt(p*(1-p)/n + z*z/(4*n*n))
    return ((c - h)/d, (c + h)/d)

wilson(8, 10)       # -> (0.490, 0.943)
wilson(4550, 5000)  # -> (0.902, 0.918)

Traced for wilson(8, 10): p = 0.8; zz = 3.8416; d = 1 + 0.38416 = 1.38416; c = 0.8 + 0.19208 = 0.99208; the sqrt argument is 0.80.2/10 + 3.8416/400 = 0.016 + 0.009604 = 0.025604, root 0.16001; h = 1.96*0.16001 = 0.31362. Bounds: (0.99208 - 0.31362)/1.38416 = 0.490 and (0.99208 + 0.31362)/1.38416 = 0.943. For the aggregate the same function gives root 0.004052, h = 0.007942, hence 0.902 and 0.918.

Failure modes

  1. Underpowered point estimates gating a release. Detection: split the holdout in half and recompute per slice; if a slice's metric moves more than its own interval width between halves, it is underpowered. Cost: a gate that flips state every retrain teaches the team to click through it.

  2. Sensitive attribute missing not at random. Detection: outcome prevalence in the "unknown" bucket versus the known rows. 12% unknown at 2.3x the base rate means dropping nulls describes only the people who filled in the form. Report "unknown" as its own slice.

  3. Proxy or leaked slices. A slice built on a field downstream of the label, or on ZIP code as a race proxy, measures the label rather than the population. Detection: walk the feature lineage for any path from the slice field to the target, then recompute with the field ablated.

  4. The "other" bucket. Sort slices ascending by the gated metric and read what landed there -- that is where a failing subgroup goes to hide. A 0.5%-of-traffic group with a 30-point recall gap is small traffic and, if it is a protected group, the entire legal exposure.

Where the values enter

With unequal base rates you cannot have group-wise calibration and equal TPR and FPR at the same time except in degenerate cases (Chouldechova 2017; Kleinberg, Mullainathan and Raghavan 2016). So the constraint is a product and legal call made before the eval, not a metric I select afterward. What the eval contributes is the trade-off curve -- minority-slice recall as the global threshold sweeps -- so the reviewer sees the price of each constraint. Intersectional slices find the real failures and hit the support floor fastest; with 30 slices at alpha 0.05 you expect about 1.5 false flags if they were independent, so pre-register the list and screen with Benjamini-Hochberg at q = 0.10 instead of treating each cell as its own gate.

Keep the sensitive attribute in a separate table joined only by the offline eval job, keyed on hashed ids, never in the feature store -- a group attribute in the feature vector is both a leakage path and a compliance problem. Tooling: fairlearn's MetricFrame with sensitive_features and control_features gives the intersectional table and the group_sizes column you print beside every metric. Monitor slice support, not just slice metrics: a slice that grew 5x since launch is a new population carrying an old metric.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How do you evaluate a model with group fairness metrics (demographic parity, equalized odds, predictive parity) and what trade-offs do they force?

Answer

These three metrics answer different questions, and when base rates differ you cannot satisfy them at once. So the first move is to ask which error is worse, not which metric sounds fairest.

With A the group, Ŷ the prediction, Y the label:

metricconstraintwhat it leaves unconstrained
demographic parityP(Ŷ=1 | A=0) = P(Ŷ=1 | A=1)Y entirely: a constant predictor satisfies it
equalized oddsP(Ŷ=1 | Y=y, A=0) = P(Ŷ=1 | Y=y, A=1), y ∈ {0,1}PPV
predictive parityP(Y=1 | Ŷ=1, A=0) = P(Y=1 | Ŷ=1, A=1)how TPR and FPR are split

Equal opportunity is equalized odds restricted to the y=1 row.

The conflict is arithmetic. Two groups, prevalences 0.5 and 0.2, a score with TPR 0.8 and FPR 0.1 in both: equalized odds holds exactly:

PPV_A = 0.50.8 / (0.50.8 + 0.50.1) = 0.40 / 0.45 = 0.889 PPV_B = 0.20.8 / (0.20.8 + 0.80.1) = 0.16 / 0.24 = 0.667

Same TPR, same FPR, PPV differs by 22 points. Chouldechova's result is the general form: with unequal prevalence, predictive parity plus equal FPR forces unequal FNR. Kleinberg et al. hit the same wall from the other side: calibration within groups, balance for the positive class and balance for the negative class cannot all hold unless base rates are equal or the classifier is perfect.

Going the other direction is worse. To hold PPV at 0.75 for group B at FPR 0.02 you need TPR 0.24: you cut TPR from 0.8 to 0.24 in the low-prevalence group to make a positive prediction mean the same thing in both. That is the trade-off in one number, and it is why "just equalize PPV" is usually wrong when the decision confers a benefit.

What I'd actually do:

  1. Report per-group confusion counts, not just rates. Forty positives in a group gives a 95% interval of about ±12 points on TPR; a gap inside that is noise.
  2. Choose the metric from the harm model. Equal opportunity when a false negative is the harm: denying a qualified applicant, missing a disease. Predictive parity when the meaning of a positive has to be portable: a risk score read in a hearing, a fraud flag. Demographic parity when the label itself is suspect or the decision is a resource allocation.
  3. Trace the cost. Fairlearn's ThresholdOptimizer implements Hardt et al.'s post-processing, group-specific randomized thresholds, and returns the accuracy-fairness frontier. I'd plot it and hand the choice to whoever owns the policy, because picking a point on that curve is a policy decision, not an engineering one.
  4. Check the label. Equalized odds on a biased Y, arrests standing in for crime, launders the bias into a fairness guarantee.

Failure modes: the protected attribute is a proxy for a feature the model already uses, so dropping A changes nothing; the constraint is tuned on the same split it is reported on; and marginal groups pass while intersectional subgroups fail. Kearns et al.'s fairness gerrymandering.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you evaluate a model when labels are delayed?

Answer

Assumptions I'd state first. Three things decide the method. Is the delay bounded, a 30-day attribution window, or unbounded, like a chargeback that can arrive at day 120? Is the delay independent of the outcome? It usually isn't: high-intent users convert in hours, low-intent ones in weeks. And do I have a randomized holdout? If the model's own action suppresses the label, you stop bidding after a conversion, no estimator recovers the counterfactual.

Core answer. A prediction cohort is only comparable to another cohort at the same maturity. I never score a 3-day-old cohort against a 30-day-old one, and I never fill unresolved cases with 0: that biases AUC down and drags calibration toward the base rate. I report provisional and mature cohorts side by side, and I backfill every metric by (prediction_id, model_version) so a cohort's numbers are recomputed as labels land rather than frozen at first read.

The delay curve. From historical labelled data I estimate the fraction of eventual positives observed by day d. Illustrative numbers for a 30-day window:

days since predictionfraction of positives observed
10.40
30.55
70.72
140.88
301.00

A day-3 cohort of 1,000,000 predictions shows 11,000 conversions: 1.10%. The mature rate is 2.00%. Dividing by the day-3 CDF: 11,000 / 0.55 = 20,000, i.e. 2.00%. Without that correction the cohort reads as a 45% regression that never happened.

Where that correction breaks. Divide-by-CDF assumes delay is independent of the prediction. When it isn't, the estimate is biased and you need one of two things: inverse propensity weighting on the delay. The delayed-feedback formulation Chapelle and colleagues used for display advertising at Criteo, or a survival model, Kaplan-Meier for the delay distribution and Cox for how covariates shift it. lifelines and scikit-survival both do this in Python. If the decision can wait, waiting for maturity beats any correction.

Failure modes and how I'd catch them. Unresolved-as-negative: AUC drops on every fresh cohort and recovers by day 30. Catch it by plotting AUC against cohort age. Comparing cohorts of different ages: catch it by refusing to render a metric without its maturity. Delay correlated with outcome: the CDF correction over- or under-shoots. Catch it by holding back a fully mature cohort and checking the corrected estimate against it. Selective labels from the model's own interventions: catch it with a small randomized holdout that keeps labels observable. Silent label-join drops: monitor join coverage per cohort; coverage falling below the historical arrival curve means late labels are being discarded upstream.

Leading indicators. Score distribution drift, feature freshness, override rate and queue depth are safety monitors: they tell you something broke now. They don't substitute for outcomes, and I wouldn't ship a model decision on them alone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How does selective feedback bias production evaluation?

Answer

Core answer (first 90 seconds).

Selective feedback means the model's own decision determines which outcomes you ever get to see. If the approval model denies an applicant, you never observe whether they would have repaid. If the alert-triage model suppresses an alert, no analyst ever labels it. The logged labels are therefore a sample from the intervened population, not the population you care about, and the naive average over logged labels estimates the wrong quantity: the outcome rate under the logging policy, on the subset it chose to act on. The bias usually runs optimistic: the logging policy acted where it was confident, so the labels you do have come from the easy cases.

Concretely: 1,000 applicants, the logging policy approves 200, and 180 of those repay. The naive "repayment rate" is 90%. But the number you want is what happens under the candidate policy, which approves 400, and the extra 200 are exactly the applicants the old policy rejected, for whom you have no labels at all.

The fix, and what it costs.

Log the propensity (the probability the logging policy took the action it took, given the features) at serving time, and inverse propensity scoring reweights what you did observe:

V̂_IPS = (1/n) Σ (π'(a_i|x_i) / π(a_i|x_i)) · r_i

Take a simplified case where both policies approve at a constant rate: 0.2 under the logging policy, 0.4 under the candidate. Every logged record gets weight 2, and V̂_IPS = 2 × (180/1000) = 0.36. The honest estimate of the population repayment rate under the candidate policy is 36%, not 90%. That gap is the bias, made visible.

Doubly robust is the version I would actually ship: V̂_DR = (1/n) Σ [ m(x_i) + (π'/π)(r_i − m(x_i)) ], where m(x) is a reward model. It is consistent if either the propensities are right or m is right, which matters because m is fit on the selected population and is biased exactly where you need it most.

Failure modes, with detection.

Propensity collapse. Weights blow up when π(a|x) is small. Take 100 logged records: 50 at propensity 0.5, 50 at 0.05, target 0.5. Weights are 1 and 10. Effective sample size is (Σw)²/Σw² = 550²/5050 ≈ 60: 100 records behaving like 60. Drop the small propensity to 0.01 and it gets worse fast. Detect by monitoring the propensity histogram and per-slice ESS; alert when ESS falls below roughly a third of n. Cost: propensity logging has to sit in the serving path, which is a schema and storage change, and a deterministic rule-based logging policy has no propensities at all.

No overlap. If the logging policy never took an action, no estimator can score it. Off-policy methods answer questions inside the logging policy's support and nothing outside it. Detect by checking coverage per action and per slice, and report zero-coverage slices as unestimated rather than imputing them.

Feedback loops. Denying an applicant changes their future behaviour, so the logging distribution drifts and the propensities you logged last quarter no longer describe this quarter. Detect by holding out a small randomized audit slice and comparing its direct estimate against the off-policy estimate; divergence means drift.

Reward-model extrapolation. m(x) is trained on selected data, so DR's correction term is doing all the work in the tails. Check m's calibration on the audit slice before trusting DR there.

When not to use it. If exploration is unethical or illegal, you cannot deny credit to measure default, you cannot randomize, and you should report bounds, not point estimates. Consent, fairness and appeal constraints cap how much exploration you can buy, and that cap is a real limit on how tight your estimate can be.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How should offline metrics be connected to business outcomes?

Answer

The short answer

An offline metric ranks candidates; it never proves the business improved, because it can't see the counterfactual. So I make the chain explicit, score → threshold → action → user behavior → business outcome, and then I test the last link with a randomized experiment. The offline metric's job is to keep bad candidates out of the experiment, not to justify shipping.

Why each link breaks

I assume the offline metric is a ranking metric evaluated per query at a fixed cutoff (say nDCG@10), not row-level accuracy: row-level accuracy ignores query membership and order and will happily rank a model that's worse for users.

  • score → threshold. The offline score distribution has to match serving. Train/serve skew, a new query mix, or a tokenizer change shifts it, and the threshold you tuned offline is now wrong. I track population stability on the score; PSI above ~0.2 is my rule of thumb to stop and look.
  • threshold → action. The model's output has to change what the user sees. If a business rule, a diversity re-ranker, or a cache overrides the top-k, the change is a no-op. I log the change rate: the fraction of requests where the new model alters the top-k. If that's under ~5%, the experiment is underpowered no matter how good the offline number is.
  • action → behavior. Users have to respond. Position bias and novelty inflate early clicks. I keep a holdback cohort and watch week-over-week decay.
  • behavior → outcome. The behavior has to move the business number. Clicks up, conversion flat is the classic break: the proxy moved, the outcome didn't.

How I validate the proxy

Across past experiments I compute the rank correlation between the offline metric delta and the online outcome delta. If it's near zero, the offline metric is a bad proxy and I stop using it to gate. If it's decent, I still only use it to filter.

Sizing the online test

Say baseline conversion is 3% and I want to detect a 2% relative lift (0.06 pp). Using n ≈ 16·p(1−p)/δ² for 80% power at 95% two-sided: 16 × 0.03 × 0.97 / (0.0006)² ≈ 1.3M sessions per arm. That's the number that decides whether the experiment is worth running at all, and it's why I want CUPED-style variance reduction (using pre-period behavior as a covariate, typically a 30–50% variance cut) before I commit.

Guardrails and failure modes

The primary metric is one number; guardrails are the veto. I track p99 latency, complaint rate, and quality/fairness slices per cohort, and I pre-register the overall evaluation criterion so I'm not picking the winner after the fact. Two failure modes I've seen: optimizing a gamed proxy (clicks from a clickbait re-ranker), and delayed effects where the 2-week test looks fine and the 8-week retention doesn't. Rollback stays available, and metric definitions and attribution windows are versioned so a definition change doesn't get read as a lift.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

A production model's aggregate AUC is stable but complaints rise. How do you investigate?

Answer

Core answer (first 90 seconds). AUC is a rank statistic: the probability a random positive outranks a random negative. It is invariant to monotone score transforms, blind to the deployed threshold, blind to calibration, and blind to class mix. Complaints are about decisions at threshold t. So the first move is not "is the model worse" but "recompute the confusion matrix at t, sliced by cohort and time." If precision at t fell while AUC held, the ranking is intact and the problem is prevalence, score shift relative to t, or calibration.

Worked example. Same model, same AUC, different decisions.

PeriodLabelsScoresAUCpreds @ t=0.5TPFPPrecision@0.5
P11,1,0,00.9, 0.8, 0.4, 0.31.001,1,0,0201.00
P21,1,1,0,0,00.9, 0.8, 0.7, 0.6, 0.4, 0.31.001,1,1,1,0,0310.75

Every positive outranks every negative in both periods, so AUC = 1.00 in both. At t = 0.5 precision falls from 1.00 to 0.75 because three positives and one negative now sit above the boundary. The ordering did not change; the decision did.

Code (checked against scikit-learn 1.4):

Python
import numpy as np
from sklearn.metrics import roc_auc_score, precision_score, brier_score_loss

t = 0.5
periods = {
    "P1": (np.array([1, 1, 0, 0]),       np.array([0.9, 0.8, 0.4, 0.3])),
    "P2": (np.array([1, 1, 1, 0, 0, 0]), np.array([0.9, 0.8, 0.7, 0.6, 0.4, 0.3])),
}

for name, (y, s) in periods.items():
    pred = (s >= t).astype(int)
    print(name,
          "AUC", round(roc_auc_score(y, s), 3),
          "precision@0.5", round(precision_score(y, pred), 3),
          "Brier", round(brier_score_loss(y, s), 3))

Output:

P1 AUC 1.0 precision@0.5 1.0 Brier 0.075
P2 AUC 1.0 precision@0.5 0.75 Brier 0.125

Brier rising from 0.075 to 0.125 while AUC stays flat is the signature of a score-distribution shift: the scores moved, the ordering did not.

Diagnostic ladder.

  1. Slice precision@t, recall@t and complaint rate per 10,000 decisions by product, region, device, tenure and policy cohort, over time. The comparison that matters is precision@t per cohort, not AUC.
  2. Separate prevalence from ranking: reweight the current window to the reference window's prevalence and recompute AUC. Reweighted AUC drops → ranking changed. Flat → prevalence or score shift relative to t.
  3. Check calibration with brier_score_loss and calibration_curve. If 0.7 no longer means 70%, any business rule reading scores as probabilities generates complaints with ranking intact.

Failure modes, each with a different fix.

  • Label delay: complaints arrive before labels mature, so the "drop" is an artifact. Detect by plotting precision@t against label-maturity lag.
  • Complaint bias: one cohort complains more. Normalize by cohort volume before believing the trend.
  • Simpson's paradox: aggregate AUC flat, one cohort's AUC down. Detect with per-cohort AUC, not the pooled number.
  • Serving parity: a feature missing at serving, model falls back to a default. Detect by comparing training-time and serving-time feature distributions.
  • Policy change: the cost of a false positive rose, so identical precision feels worse. Detect by checking the threshold's cost matrix against the current one.

Fixes. Precision@t down, ranking intact → raise t or recalibrate. Ranking down in a cohort → roll back the model. Serving parity broken → fix the pipeline. Policy changed → re-derive t from the new cost matrix.

Contain first. If harm is live, roll back the threshold or model, then canary the fix on fresh traffic. Monitor precision@t, Brier, and complaints per 10,000 decisions by cohort. Keep decision IDs and appeals for audit.

Decision criterion: AUC flat + precision@t down → threshold, prevalence, or calibration. AUC down in a cohort → ranking. Calibration off → recalibrate. Serving mismatch → pipeline.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

How do you choose evaluation metrics for a new ML product?

Answer

Core answer (first 90 seconds)

A metric is a decision rule, so I start from the decision, not the model. Three questions: what is one prediction. A transaction, a session, a user-day? What action does a positive trigger: block, review, rank, email? And what does a false positive cost versus a false negative? If the product owner can't give me the third as a number, I ask for one: "a blocked legitimate transaction costs a support ticket and about $40 of goodwill; a missed fraud costs $300." That ratio, not accuracy, sets the threshold. Then I predeclare one primary metric that matches the action and the base rate, before I look at any test result.

Choosing the primary metric

The base rate decides the family. Take fraud at 0.5% positives: 1M transactions a day, 5,000 frauds. A model that predicts "never fraud" scores 99.5% accuracy and catches nothing, so accuracy is out. ROC-AUC is also misleading at that skew: it's dominated by the 995,000 easy negatives. I use PR-AUC (average precision) as the ranking metric and precision@k as the operating metric, where k is the review queue size.

Arithmetic: if the queue is 200 a day and 60 of the 200 flagged are fraud, precision@200 = 30%, recall = 60/5,000 = 1.2%. Now the conversation is concrete: is 1.2% recall worth 140 analyst-hours a day? If not, we change k or the model, not the metric.

MetricUse whenMisleads when
Accuracyclasses balanced, costs symmetricbase rate below ~10%
ROC-AUCranking across all thresholds, balanced-ishheavy skew; looks fine at 0.5% positives
PR-AUC / average precisionrare positives, ranking mattersyou only ever act on top-k
Precision@kfixed capacity (review queue, top of feed)k is unstable day to day
Calibration (ECE, Brier)you multiply probabilities by costyou only need a ranking
Business metric (revenue, retention)final gatetoo slow and noisy to iterate on

Guardrails and diagnostics

A primary metric alone gets gamed, so I add guardrails that must not regress: for a ranking model, coverage across cohorts (no eval slice below 100 positives), latency p99, and a fairness metric such as equal-opportunity difference. Diagnostics (per-slice PR-AUC, a calibration curve) explain movement but don't gate the launch.

Failure modes I check for

  • Leakage: a feature computed after the label event. Classic case: "number of chargebacks on this card" as a fraud feature, which is only known once the fraud has happened. Offline AUC 0.98, online 0.55.
  • Metric gaming: optimizing click-through when the goal is 30-day retention. CTR rises, retention stays flat.
  • Offline/online divergence: offline AUC 0.92 with no online lift, usually from a feedback loop (the model only sees outcomes for what it showed) or position bias.
  • Threshold drift: threshold tuned on last quarter's base rate; the rate shifts 0.5% to 0.9% and precision collapses.

Locking it down

Split mirrors deployment: time-based, not random, if there's any temporal signal. Freeze preprocessing, calibration, and threshold before the final test. Then a controlled rollout, say a 5% holdout, and compare the business metric, not the offline one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design the evaluation system for a high-stakes classifier.

Answer

Core answer

The evaluation system is a predeclared rule that maps model outputs to a decision, plus the evidence that the rule holds on data the model never touched. I fix four things before training: the decision and its cost, the operating point, the guardrails, and the locked test set.

Concrete case: a sepsis early-warning classifier that pages a rapid-response team. The decision is binary, page or don't, and the cost is asymmetric. A missed deterioration can be a death; a false page burns about 20 minutes of a nurse's time and, repeated, causes alert fatigue that suppresses real responses.

So I evaluate at a fixed alert budget, not on a free-floating ranking metric. Take 100,000 admissions a year and 2% sepsis prevalence: 2,000 cases. I cap alerts at 8% of admissions, 8,000 pages, because that is what the floor can absorb. At sensitivity 0.80 that catches 1,600 true positives, so PPV = 1,600 / 8,000 = 0.20. Four pages per true case. That number, not AUROC, is what the ward feels.

Why the operating point, not AUROC

AUROC is threshold-free and, at 2% prevalence, flatters a model: a 0.90 AUROC can still give PPV near 0.10 at the deployed threshold. AUPRC tracks the rare positive better, but the honest metric is PPV and sensitivity at the alert budget you can actually staff. Use AUROC only for coarse model comparison before a threshold is fixed; once it is fixed, AUROC is the wrong lens.

The scorecard

dimensionmetricfloor
sensitivityrecall at 8% alert rate≥ 0.75
precisionPPV at the same point≥ 0.15
calibrationexpected calibration error≤ 0.03
subgroupmax sensitivity gap across age/sex/site≤ 0.05
latencyp99 score latency≤ 200 ms

Calibration matters because the alert carries a probability to the clinician; a model that ranks well but is overconfident at 0.6 gets ignored.

Splits and leakage

Nested development: an outer loop for model selection, an inner loop for hyperparameters, so no selection touches the test set. The test set is locked and access-controlled, and every read is logged. Splits are by patient and by admission time, not random rows: a random split leaks the same patient's later labs into training. Every feature must be derivable from data available at the scoring timestamp; I re-derive features from a snapshot to catch leakage.

Failure modes and detection

  • Silent distribution shift: monitor per-slice sensitivity weekly against matured outcomes; a 0.05 drop on any site triggers review.
  • Feedback loop: only paged cases get adjudicated labels, so the labeled set is biased toward alerts. Detect by auditing a random 1% of non-alerted cases.
  • Threshold drift after a pipeline change: canary the new version on 5% of traffic and compare PPV before promoting.

When not to use this

If the decision is reversible and cheap (a nudge, a queue reorder) skip the locked test and guardrail apparatus; a shadow deployment and a weekly metric review is enough. The full system earns its cost only when a wrong decision is hard to reverse.

Curated: · Written: · Reviewed:

Difficulty: Hard