Cheat sheet · Module 4
Cheat sheet: evaluation, statistics and data
Machine Learning · Cheat sheet · Evaluation, statistics and data
The pattern: every number is one draw from a distribution you cannot see, and every input is part of a contract between training and production. Evaluation is a rehearsal of deployment: the model sees only what it will know at prediction time, the unit that is independent in the real world is independent in the split, the metric rewards what the business rewards, and the decision rule is the one that will be used. When a score looks too good, ask which of the four the rehearsal broke. Statistics then says how far to trust the score, and the data layer keeps the inputs honest after launch.
Splits (lesson 1): the first “yes” picks the splitter, because time or group structure must be respected even when a class is also rare.
- Ordered in time: train on the past and test on later blocks (forward-chaining), skipping rows with
gapwhen a label or feature is computed over a window that reaches ahead of the row’s timestamp. Several rows per person, device or patient: group k-fold. One class rare and rows independent: stratified k-fold. Otherwise plain k-fold. KFoldandStratifiedKFolddo not shuffle by default. For independent rows passshuffle=Truewith a fixedrandom_state; never shuffle time-ordered data. The scikit-learn page warns that stratification can artificially shrink the spread of the metric across folds.- The test set is looked at once, after every choice is made. The best cross-validation score among many configurations is optimistic for the same reason; nested cross-validation avoids the circularity of tuning and scoring on the same folds. With around 100 samples, error bars of about ±10 points were reported in neuroimaging, and the standard error across folds underestimates them, so report a spread.
Leakage: information that would not exist at prediction time getting into model building. The score looks wonderful and the damage shows in production.
| Kind | Tell-tale sign | Prevention |
|---|---|---|
| Target | One feature dominates; suspiciously good | Fix a prediction time, audit every feature against it |
| Preprocessing before the split | Cross-validation beats the true holdout | Fit scalers, imputers, encoders and selectors inside each training fold (pipeline) |
| Shared entities, duplicates | Row-level CV far above group CV | Group k-fold; remove or group duplicates |
| Temporal | Performance collapses on the next period | Forward-chaining; point-in-time features |
| Resampling before the split | Minority recall unrealistically high | Resample the training fold only; the validation fold keeps the natural rate |
- Measured on pure noise: selecting 10 of 2,000 features on all 100 rows gave test accuracy 0.817, against 0.492 when selecting on training rows only. Patients on both sides gave 0.944 for row-level folds against 0.490 for group folds. A random split on a random walk gave an absolute error of 0.84 against 2.61 for forward-chaining. Duplicating first gave balanced accuracy 0.972 against 0.495 when resampling inside the folds.
- Cheap checks: exact duplicates between train and test, group ids on both sides, and “when does this feature become known?” for every feature.
Metrics (lesson 1): , , is their harmonic mean, and with larger weights recall more. Balanced accuracy is the average recall over the classes.
- Fraud, 10,000 transactions and 20 fraud: flag 40 catching 15 gives accuracy 0.9970, precision 0.375, recall 0.75; flag 60 catching 18 gives accuracy 0.9956, precision 0.300, recall 0.90. Accuracy and both prefer the first model, but with a miss at 5,000 and a false alarm at 50 the second is cheaper (26,250 against 12,100). A model that never flags has accuracy 0.998 and recall 0. No metric is best in general; match the cost of each error.
- ROC-AUC is the probability that a random positive outranks a random negative; it barely moves when you add negatives of the same kind (0.903 with 100 negatives, 0.911 with 49,900). Average precision falls with prevalence (0.910 to 0.091) and precision at a fixed threshold collapses (0.830 to 0.010). A constant score gets an AP equal to the positive rate, so AP is not comparable across datasets with different rates. ROC-AUC is not wrong; it answers “how well does it rank?”.
- Log loss and the Brier score judge the probabilities themselves, and both mix calibration with discrimination. Regression: MAE is the loss whose best constant is the median, RMSE (squared error, the mean) lets large misses dominate, compares with predicting the mean, and MAPE blows up near zero actuals.
Calibration and thresholds
- Calibrated: among cases scored near 0.8, about 80% are positive. (equal-width bins; the number of bins changes the value). Doubling every logit left ROC-AUC at 0.8346 and raised ECE from 0.011 to 0.093; halving restored it. Temperature scaling is one fitted parameter; fit calibrators on data the classifier was not trained on. Platt sigmoid suits small samples or an under-confident model; isotonic regression overfits small data, so the documentation’s rule of thumb is to use it with more than about 1,000 samples, and it can introduce ties that change ROC-AUC.
- Positives weighted by multiply the odds by : , so with a true 0.01 comes out as 0.500. Downsampling the negatives by 25 turns a 99 to 1 split into 20.2% positives. Ranking metrics are unaffected; probabilities are, so recalibrate before quoting a risk or using a cost-based cut.
- Threshold: predict positive when for calibrated . With costs 5,000 and 50 that is 0.0099, and the cheapest policy had 20% precision and 99% recall. The default 0.5 is hard-coded in libraries. With a review capacity limit, pick the cut that gives the alert volume. Never tune the threshold on the data that trained the classifier.
Imbalance, in order: baseline and metric (PR-AUC, recall at fixed precision, or expected cost; natural rate in the test set), stratified splits, class weights (balanced is : 0.5051 and 50.0 for 99 against 1), threshold from costs, resample the training fold only, recalibrate, then anomaly framing or more labels.
- SMOTE interpolates between a minority sample and a near minority neighbour. Caveats: synthetic points are not real observations, it may connect inliers and outliers, plain SMOTE cannot handle categorical features. Whether resampling beats class weights is an experiment.
- Report every metric beside a baseline (
DummyClassifier:most_frequent,stratified,constant; log loss of predicting the base rate 0.002 is 0.0144). Error analysis: slice by segment, read the worst errors, group by cause, fix the biggest group. 9,000 rows at 95% and 1,000 at 70% average to 92.5%.
Estimates and intervals (lesson 2): , so quadrupling the data halves the noise. : divisor makes the variance estimator unbiased (the standard deviation is still biased low), and a shrunken mean can have lower MSE when the true mean is small relative to the noise.
- A 95% interval is a statement about the procedure over repeated experiments. For the one you computed, the truth is inside or not. Analytic: (a t quantile for small samples). Bootstrap: resample with replacement, read the percentiles; it fits statistics with no formula (median, AUC) and is not a repair for small samples.
- Coverage of nominal 95% over 400 repeats: normal 0.920 (normal approximation) and 0.910 (bootstrap); lognormal 0.800 and 0.805; lognormal 0.865 and 0.858, with nearly all misses below the true mean. SciPy’s bootstrap defaults to BCa, whose endpoints can be undefined for degenerate resamples.
Tests and p-values: the p-value is the chance of data this extreme if were true. It is not the probability that is true, not an effect size, and a threshold crossing alone should not carry a conclusion (ASA statement). Under a true it is uniform on 0 to 1.
- Two rates: pooled two-proportion z-test. 1,000 of 10,000 against 1,090 of 10,000 gives , ; the same rates on a fifth of the traffic give . The effect did not change, the evidence did. Report the interval beside the p-value. Chi-square goodness of fit: rule of thumb, every observed and expected count at least 5. SciPy’s
ttest_indassumes equal variances unlessequal_var=False(Welch). - Permutation test: shuffle the labels. Randomised: , never exactly zero; if reaches the number of distinct permutations SciPy runs the exact test. Convention: this course counts for two-sided, while
scipy.stats.permutation_testdoubles the smaller one-sided p-value; they agree for a symmetric null and differ on skewed data (0.0280 against 0.0396 in the lesson’s example), so say which rule you used. - If 10% of ideas truly work, power is 0.80 and alpha 0.05, then 80 of 125 significant results are real (0.640).
Power and sample size: Type I is a false positive (probability ), type II a false negative (), power is .
- per arm, with z values 1.96 and 0.84 (exact quantiles were used for the counts). The effect is squared: halving the lift quadruples the cost. Baseline 0.10: target 0.120 needs 3,839, 0.110 needs 14,749, 0.105 needs 57,760. Shortcut (14,400 against 14,749).
- A baseline 0.30 against 0.35 needs 1,374 per arm. With 500 per arm the power is 0.394, so a non-significant result is “inconclusive”, not “no effect”.
Many comparisons: 20 independent true nulls give chance of at least one .
- Bonferroni tests each at and controls the family-wise error rate; strict, loses power as grows. Benjamini-Hochberg controls the false discovery rate: adjusted , reject those at most . Its guarantee is FDR at most for independent tests or tests with positive regression dependence; Benjamini-Yekutieli is the more conservative variant for arbitrary dependence.
- 100 tests with 80 true nulls and 20 real effects: no correction 3.83 false and 17.15 true discoveries per 100 tests; Bonferroni 0.05 and 6.52; BH 0.55 and 12.30. A single launch decision calls for family-wise control; screening many candidates tolerates a few false leads. Best fix: one primary metric named before the test. Gelman and Loken: analysis choices made after seeing the data count as comparisons too.
A/B tests on ML systems: randomisation is what supports a causal claim. Order: one primary metric, guardrails, minimum effect, unit, sample size, run to the planned end, then check arm sizes before reading any result.
- Unit of randomisation should match the unit of analysis. Views clustered within users inflate the variance by (2.73 for , ), which predicts a 0.235 false-positive rate; the simulation gave 0.214. Interference (marketplaces, social networks, shared learners) calls for cluster randomisation or switchbacks, at a cost in power.
- Sample ratio mismatch: with degrees of freedom. 520 against 480 gives but 5,200 against 4,800 gives . Many teams alarm only at a strict threshold such as 0.001. When it fires, do not read the effect.
- Peeking: stopping at the first significant look of 10 gave a 0.219 false-positive rate against 0.058 for a single test at the end. Use a fixed horizon or a sequential method. Novelty and primacy effects: run whole weekly cycles and watch the effect over time.
- Offline up, online flat: check power first, then metric mismatch, stale or selected logged data, distribution shift, serving bugs, novelty. Keep guardrail metrics. Simpson’s paradox: with random assignment the mixes match in expectation, so a reversal points to broken assignment, pooled ramp-up periods or an observational comparison.
Comparing models, Bayes, causation
- Two scores on one test set are paired: only items where the models disagree carry information. McNemar: . It uses one training set, so it can over-reject when the variation due to training data is large. Cross-validation scores overlap in training data and are positively correlated; Nadeau-Bengio adds the test-to-train size ratio to in the variance factor. Several models over many datasets: Wilcoxon signed-ranks for two, Friedman with post-hoc tests for more.
- Bayes’ rule in natural frequencies: 1% prevalence, 90% sensitivity, 10% false positives gives 90 of 1,080 positives sick, and a rarer condition means mostly false alarms; the same fact as precision under imbalance. Minimising cross-entropy is maximum likelihood; a Gaussian prior gives an L2 penalty and a Laplace prior gives L1.
- A flat-prior posterior probability that B beats A (0.925) and a z-test p-value (0.1529) answer different questions; the closeness of to the one-sided p-value is not a general identity.
- A hidden variable driving both and gives correlation 0.502 with no effect; random assignment of gives -0.008. A model that predicts an outcome does not tell you what happens if you intervene on a feature.
Data quality and missing values (lesson 3): check schema, null rates, ranges and units, duplicates and the category list at training and again at serving, and fail loudly. Labels can be noisy (10% flipped makes a perfect model score 0.902), defined differently in production, or late.
- MCAR depends on nothing, MAR on observed columns, MNAR on the missing value itself. True mean 50.06: MCAR observed 50.09; MAR observed 47.58 but 50.00 imputed by group of an observed column; MNAR observed 46.97 and 48.36 by group. Mean imputation shrinks the spread (sd 8.35 against 9.94). You cannot tell MAR from MNAR from the observed data alone.
- A 0/1 missing indicator keeps the signal that missingness often carries (disease rate 0.109 where missing, 0.538 where measured). Trees such as XGBoost and histogram boosting route NaN themselves; linear models, neural networks and distance-based models need an imputer.
- Every imputer mean, scaler and category list is learned from training rows only. Fitted on train and test together, a test shift of 1.529 against -0.030 looked like 0.617.
Scaling, skew, encoding
- Scaling matters for distances and gradients (regularised linear models, k-NN, SVMs, neural networks), not for trees. One outlier of 1,000 among 99 values (mean 10, sd 2) squeezed standardised ordinary values to sd 0.020; median and interquartile range kept sd 0.794. Logs took skewness from 5.15 to 0.02. Power and quantile transforms are statistics too, so learn them on training rows.
- One-hot: width grows with levels. Ordinal invents an order on nominal levels. Hashing keeps width fixed at the cost of collisions (500 categories in 256 buckets used 219 buckets, 438 shared). Embeddings need data per level and cannot represent an unseen level meaningfully. An unseen level is a row of zeros with
handle_unknown="ignore". Hour of day as . - Target encoding pulls rare levels toward the prior. Fitted and applied on the same rows it contains the label; use out-of-fold encoding, and in scikit-learn
fit_transformon training data, sincefit(X, y).transform(X)is not the same. Smoothing is a safeguard for rare levels, not a fix for leakage. Leave-one-out still leaks: falls as rises. The CatBoost paper addresses this family of problems. - A feature cross helps linear models, which are additive; trees and neural networks can learn interactions themselves. A cross of two high-cardinality features brings back the hashing question.
Point-in-time, skew, pipelines
- A feature for a prediction at time may use only information that existed at . Two ways to break it: a window that reaches past , and a join to the latest value of a profile. A point-in-time join returns the latest value at or before the event time, with an optional TTL; a past-only rolling window at position uses values before . For
[3, 5, 4, 10]with window 3 the past-only mean is[None, 3.0, 4.0, 4.0]. Also beware a nightly batch not ready at request time and values corrected later in the warehouse. - Training-serving skew has three causes (Google’s guide): handling differs between pipelines, the data changes between training and serving, a feedback loop. Defences in order: reuse code (rule 32), log what you served (rule 29), golden tests, monitoring. Missing values served as 0 instead of the training median moved precision from 0.831 to 0.556 with the model unchanged.
- A
Pipelinekeeps preprocessing and model in one fitted object, so cross-validation refits every step per fold;ColumnTransformerdrops unlisted columns by default. It does not cover features computed outside it (SQL joins, windows). A feature store defines each feature once and serves it for point-in-time training tables and low-latency lookup; it costs another system, a latency budget and a shared contract, and a small team may prefer a shared library and logging.
Drift
| Type | What changes | Where it shows |
|---|---|---|
| Data (covariate) | , with fixed | Input distributions: PSI, KS, null rates |
| Label (prior) shift | , with fixed | Predicted-positive rate against the expected base rate |
| Concept | Labelled outcomes only |
Under label shift also moves, so input PSI can fire; the kinds are definitions, not clean diagnoses. Responses differ: data drift may need nothing or new data for the new region, a pipeline bug needs a fix and no retraining, concept drift needs new labels and retraining.
- , never negative, zero only when every share matches, symmetric. Shares (0.5, 0.5) against (0.3, 0.7) give 0.1695. Floor empty bins: a new category with 10% of rows gave 0.708 at and 1.170 at .
- Reading: below 0.1 stable, 0.1 to 0.25 watch, above 0.25 major shift. These are common practice, not a derived law. The no-drift floor is about : with 50,000 reference rows and 10 bins the mean PSI was 0.0950 for 100 current rows (95th percentile 0.2029), 0.0087 for 1,000 and 0.0011 for 10,000. Bin choice moves it (0.2060, 0.2417, 0.2669 for 5, 10, 20 bins), and PSI sees one marginal at a time.
- KS needs no bins and assumes continuous data. A mean shift of 0.02 with 100,000 rows per side gave PSI 0.00033 but KS 0.0076, above the approximate critical value 0.0061, so significance is not importance. A spread change with the mean fixed was seen by both (PSI 0.1979, KS 0.1029).
- Monitor four layers, cheapest first: data quality, feature drift, score drift, performance once labels arrive. Report true metrics by prediction-date cohort and judge only cohorts whose labels have matured. At 30 days 0.779 of positives are labelled, at 60 days 0.949, at 90 days 0.990.
Retraining, rollout, versioning, debugging
- Retraining triggers: a schedule, a drift threshold, a performance drop on matured labels, enough new labelled data. Each trades cost against staleness; in the toy simulation the trigger policy beat the schedule on accuracy and cost more retrains. Rollout: offline validation, shadow (scores live traffic, nothing acts on it), canary with guardrails, ramp, one-step rollback and a fallback.
- Feedback loops and selective labels: a lender that approves only high scorers never sees outcomes for the rest, so keep an exploration or hold-out slice where decisions are not model-driven.
- Version the code, the data snapshot (or its hash), feature definitions, library versions, hyperparameters and seeds, stored with the model in a registry.
- Debug in order, cheapest first: valid inputs; skew (served against training features for the same case); leakage in the original evaluation; drift per feature across time windows; label or definition mismatch; silent fallbacks, timeouts, wrong artifact version; only then a real concept change.
Choosing a remedy
| Symptom | First check | Likely fix |
|---|---|---|
| Score too good for the problem | Duplicates, group ids across the split, feature timestamps, importance concentrated in one feature | Pipeline per fold, group or forward-chaining split, prediction-time audit |
| High accuracy, rare positives | Baseline, confusion matrix, PR-AUC | Cost-based threshold, class weights, resample inside the folds |
| Probabilities used as risk after weighting or resampling | Reliability bins, ECE | Refit a calibrator on natural-rate data the model did not train on |
| Two models differ by a point | Same items? Paired interval | McNemar or a paired interval, corrected resampled t for repeated splits |
| Many metrics, one “winner” | How many comparisons were made | One primary metric, Bonferroni or BH by cost of a false lead |
| Experiment arms off the design ratio | Chi-square on arm counts | Pause the read-out and trace the assignment and logging path |
| High-cardinality category | Rare levels, unseen levels | Out-of-fold smoothed target encoding or hashing |
| Fine offline, poor live | Valid inputs, served against training features | One shared feature definition, logging, golden tests |
| Input PSI quiet, accuracy falling | Labelled cohorts of equal age | Concept drift: new labels, retrain |
| Newest cohort looks better than older ones | Share of labels matured | Compare same-age cohorts |
Quick answers
- Is 99.8% accuracy good? Compared with what? Ask for the base rate, a baseline and the cost of each error.
- ROC-AUC or PR-AUC on rare positives? ROC-AUC answers how well the model ranks and barely moves with prevalence; PR-AUC and precision at a threshold show the cost of false alarms.
- Is a 95% interval a 95% chance the parameter is inside? No, it describes the procedure over repeated experiments.
- Does a non-significant result mean no effect? No, check the power; a small test is inconclusive.
- Bonferroni or Benjamini-Hochberg? Family-wise control for a single decision, false discovery rate for screening; BH assumes independence or positive dependence.
- Why does the SRM check come before the effect? Broken assignment or logging may also bias the metric.
- Does leave-one-out target encoding fix leakage? No, the row’s own label still shifts its value.
- Is PSI above 0.25 always a problem? The cut-offs are conventions; sample size and bin choice move the value.
Traps
“99% accuracy means a good model” · “ROC-AUC is wrong for imbalanced data” · “0.5 is always the right cut” · fitting the scaler, selector or resampler before the split · shuffling time-ordered data · reporting the best cross-validation score as the estimate · weighted probabilities shown as risks · “p = 0.03 is a 97% chance the effect is real” · “p above 0.05 means no effect” · stopping at the first significant look · page-view-level tests on user-level assignment · reading the effect after an SRM alarm · comparing two scores on one test set as if independent · mean imputation without an indicator · target encoding without folds · treating the PSI cut-offs as laws · judging recent cohorts before their labels mature · retraining before checking inputs and skew.