Module deck
Evaluation, statistics and data flashcards
Reviewing needs JavaScript. You can read every card in the list below.
Loading your cards...
Back to the module52 cards in this deck
Read all 52 cards as a list
Evaluation, leakage and imbalance: validation design, metrics, thresholds and rare classes
- Front
- Which splitter for which data?
- Back
- Independent rows: k-fold. Rare class: stratified k-fold (every fold keeps about the same class mix). Several rows per patient, user or device: group k-fold (no group on both sides). Time order: forward-chaining, train on the past and test on the next block, with an optional gap. Use the test set once, after every choice is made.
- Front
- Why can cross-validation still mislead you?
- Back
- Choosing the best of many configurations on the same folds makes the winner's score optimistic, so keep a test set for one final look or use nested cross-validation. Small data also gives wide error bars: Varoquaux saw roughly 10 points of uncertainty at about 100 samples in neuroimaging, and the standard error across folds underestimates it.
- Front
- Name the main kinds of leakage and one fix each.
- Back
- Target (a feature known only after the outcome): fix a prediction time and audit features. Preprocessing before the split: fit inside the training fold with a pipeline. Shared entities or duplicates: group k-fold, de-duplicate. Temporal (random split of time data): forward-chaining. Resampling before the split: resample the training fold only.
- Front
- How big can a preprocessing leak be?
- Back
- In the lesson's script, with 100 rows of noise and 2,000 noise features, selecting 10 features on all rows gave a test accuracy of 0.817 and selecting on the training rows only gave 0.492 (chance). The scikit-learn docs show 0.76 against about 0.5 with 200 samples and 10,000 noise features. Put every fitted step in a Pipeline.
- Front
- What are the red flags for a leak, and the cheap checks?
- Back
- Flags: a score too good for the problem, one feature carrying most of the importance, a big gap between cross-validation and a later holdout. Checks: test rows that exactly duplicate training rows, group ids on both sides of a split, and for every feature the question of when it becomes known. In the script, row-level CV on patient data gave 0.944 against 0.490 for group CV.
- Front
- Why does 99.8% accuracy tell you little with 0.2% positives?
- Back
- A model that never flags anything scores 99.8% and finds nothing. Use the confusion matrix, precision (TP over flagged), recall (TP over real positives), F1 (their harmonic mean), and a cost. In the lesson's example a model with lower accuracy and F1 but higher recall was cheaper (12,100 against 26,250 at 5,000 per miss and 50 per false alarm).
- Front
- ROC-AUC versus PR-AUC on rare positives?
- Back
- ROC-AUC is the chance a random positive outranks a random negative, so adding more negatives of the same kind barely moves it (it does not change in expectation). Average precision depends on the positive rate. Same ranker in the script: ROC-AUC 0.903 against 0.911 but AP 0.910 against 0.091 when negatives went from 100 to 49,900. A constant score gets an AP equal to the positive rate.
- Front
- How do you pick a threshold from costs?
- Back
- For calibrated probabilities, predict positive when p exceeds C_FP over (C_FP plus C_FN). A miss of 5,000 and a false alarm of 50 give 0.0099, and in the script that cost 14.54 per row against 191.23 at 0.5, at 20% precision. If capacity is limited, choose the threshold that matches the alert volume. Tune it on validation data, not on the training data.
- Front
- What is calibration and how do you check it?
- Back
- Among cases scored near 0.8, about 80% should be positive. Check with reliability bins, expected calibration error, log loss or Brier score. It is separate from ranking: doubling the logits left ROC-AUC at 0.8346 and moved ECE from 0.011 to 0.093. Fix with Platt sigmoid, isotonic (more than about 1,000 samples) or temperature scaling, fitted on held-out data.
- Front
- MAE, RMSE, R-squared and MAPE: when each?
- Back
- MAE is the typical miss (best constant is the median). RMSE squares errors so big misses dominate (errors 1, 1, 1, 1, 20: MAE 4.8, RMSE 8.99). R-squared compares with predicting the mean. MAPE is unstable near zero: an actual of 0.1 predicted as 1.1 is a 1000% error.
- Front
- In what order do you treat class imbalance?
- Back
- Baseline and a suitable metric, stratified splits with the test set at the natural rate, class weights, tune the threshold on validation, resample only inside training folds if needed, recalibrate, then consider anomaly framing or more labels. Balanced class weights are n over (classes times class count): 0.5051 and 50.0 for 99 negatives and 1 positive.
- Front
- Why must resampling and SMOTE happen inside the fold?
- Back
- Copies or interpolated points of a minority row would sit in both training and validation, and the validation rate stops matching real traffic. In the script, duplicating first gave a balanced accuracy of 0.972 on noise and doing it inside the folds gave 0.495. SMOTE interpolates between neighbours, so its points may be unrealistic and it needs a variant for categorical data.
- Front
- What do weights and resampling do to probabilities?
- Back
- They keep the ranking but shift the probabilities: weighting positives by w multiplies the odds by w, so a true 0.01 becomes 0.500 at w = 99. Recalibrate on held-out data at the natural rate before using the score as a probability or in a cost-based threshold.
- Front
- What do baselines and error analysis add?
- Back
- A metric means little without a baseline: DummyClassifier most_frequent, a constant score (AP equal to the positive rate), the base-rate log loss, a simple model, and the current rule. Then slice: 9,000 rows at 95% and 1,000 at 70% make 92.5% overall. Read the worst errors, group them by cause and fix the biggest group first.
Statistics and experimentation: intervals, tests, power, A/B tests and fair model comparison
- Front
- What is the standard error of a sample mean, and what does quadrupling n do?
- Back
- It is sigma / sqrt(n): the spread of the sample mean across repeated samples. Quadrupling the data halves the noise. The shape of the sampling distribution is Gaussian only for large n: with skewed data and n = 5, only 0.1% of means fell below the mean minus 1.96 SE and 4.4% fell above the mean plus 1.96 SE.
- Front
- What does a 95% confidence interval mean?
- Back
- The procedure that built it contains the true value in about 95% of repeated experiments. It is not a 95% probability that the parameter is in the one interval you computed, and it is not a range for single observations.
- Front
- Bias versus variance of an estimator: when does a biased one win?
- Back
- Mean squared error is bias squared plus variance. For a mean of 0.5 from 10 draws with sd 1, the sample mean had an error of 0.1003 and 0.8 times the mean had 0.0743: a bias of -0.1 bought a larger cut in variance. Dividing squared deviations by n averages 0.798 for a true variance of 1 at n = 5, so use n - 1.
- Front
- When do you use the bootstrap, and when does it fail you?
- Back
- When no formula exists for the statistic (median, AUC, ratio): resample with replacement, compute the statistic, read the percentiles. It does not rescue small or heavy-tailed samples: on lognormal data with n = 15 both the normal-approximation and the percentile intervals covered the true mean only about 80% of the time, and 96% of the misses were below the true mean.
- Front
- State what a p-value is and three things it is not.
- Back
- The probability, assuming no effect, of data at least as extreme as observed. It is not the probability that the null is true, not the size of the effect and not proof of importance. A large p-value from a small test is inconclusive, not evidence of no effect.
- Front
- Which test for which data?
- Back
- Two conversion rates: two-proportion z-test with the pooled error. Two means: t-test (Welch if variances differ). Counts against a design (SRM): chi-square goodness of fit, with observed and expected counts at least 5. Small or odd data, or any statistic: permutation test, exact when every split can be listed, otherwise (extreme + 1) / (B + 1).
- Front
- Type I error, type II error, power: define each.
- Back
- Type I: rejecting a true null, probability alpha. Type II: keeping a false null, probability beta. Power is 1 - beta, the chance of detecting a real effect of the assumed size. Under a true null the p-value is uniform: 2,000 A/A tests gave 4.1% below 0.05 and 49.5% below 0.5.
- Front
- How do you size an A/B test, and what does halving the lift cost?
- Back
- Fix the metric, baseline, minimum effect, alpha and power. For two proportions n = (z_alpha/2 + z_power)^2 (p1 q1 + p2 q2) / (p1 - p2)^2 per arm. At a 10% baseline: 3,839 for 12%, 14,749 for 11%, 57,760 for 10.5%. Halving the lift quadruples n. A shortcut is n = 16 sigma^2 / delta^2.
- Front
- Bonferroni versus Benjamini-Hochberg?
- Back
- Bonferroni tests each of m hypotheses at alpha / m and controls the chance of any false positive; it is strict. BH controls the expected share of false discoveries and rejects more. With p = 0.001, 0.012, 0.018, 0.030, 0.45 Bonferroni rejects 1 and BH rejects 4 at q = 0.05. With 20 true nulls the chance of at least one p < 0.05 is 0.642.
- Front
- Why is peeking a problem and what replaces it?
- Back
- Every look is another chance to cross the threshold. In 1,000 simulated A/A tests with up to 10 looks the false-positive rate was 0.058 at the planned end and 0.219 when stopping at the first significant look. Use a fixed horizon, or a sequential method built for continuous monitoring.
- Front
- What is a sample ratio mismatch and what do you do?
- Back
- The arm sizes differ from the design by more than chance allows: check with a chi-square test on the counts. 50,500 against 49,500 gives chi-square 10.0 (p = 0.0016); 520 against 480 gives 1.6 (p = 0.206). When it fires, find the assignment or logging bug first and do not read the treatment effect.
- Front
- What goes wrong if you randomise by user but analyse by page view?
- Back
- Views from one user are correlated, so the standard error is too small by a design effect 1 + (m - 1) rho. With m = 20 views and rho = 0.0909 it is 2.73, and 21.4% of A/A tests came out significant at 5%. Analyse at the level you randomised.
- Front
- The offline metric improved and the A/B test shows nothing. What do you check?
- Back
- In order: power for the expected lift, then metric mismatch (offline metric is not what users respond to), then selected or stale offline data, distribution shift, a training-serving bug and novelty. Keep guardrails in every test.
- Front
- Why can a correlation not prove that X causes Y?
- Back
- A confounder can drive both. With a hidden Z behind X and Y, the correlation was 0.502 although X had no effect; assigning X at random gave -0.008. Randomisation is the clean fix. Without it, designs such as matching or difference-in-differences need stated assumptions.
- Front
- Why compare two models with a paired test?
- Back
- They are scored on the same items, so errors overlap. On 1,000 constructed items with accuracies 0.770 and 0.798, McNemar on the disagreements (29 and 57) gave p = 0.0036 while the unpaired test gave p = 0.128. Report an interval for the gain. McNemar uses one training set, so it ignores training-set variability.
- Front
- Why is a plain t-test on cross-validation or repeated splits too optimistic?
- Back
- Training sets overlap, so scores are positively correlated and the variance is underestimated. The Nadeau-Bengio statistic uses (1/k + n_test / n_train) s^2 under the root. On ten constructed gaps from 90/10 splits it cut t from 8.95 to 6.16. Dietterich found the random-split t-test has a high type I error rate.
- Front
- Work the base-rate problem: 1% prevalence, 90% sensitivity, 10% false-positive rate.
- Back
- Use natural frequencies for 10,000 people: 100 sick, 90 test positive; 9,900 healthy, 990 test positive. P(sick | positive) = 90 / 1,080 = 0.0833. With 99% and 5% it is 0.1667; at 10% prevalence it is 0.5. Rare condition, mostly false alarms.
Data, features and production ML: preprocessing, encodings, point-in-time features, skew, drift and operations
- Front
- What are MCAR, MAR and MNAR, and which one can the observed data repair?
- Back
- MCAR: missingness depends on nothing, so the observed rows are a fair sample. MAR: it depends on other observed columns, so imputing within groups of those columns repairs the bias (observed mean 47.58, group-wise fill 50.00, true 50.06). MNAR: it depends on the missing value itself, and the observed data cannot fully repair it (48.36 after the same fill).
- Front
- Why add a missing indicator next to an imputer?
- Back
- Missingness is often a signal. In the script a lab value was missing for 70% of healthy and 20% of sick patients: disease rate 0.109 where missing, 0.538 where measured. A filled column hides that. The indicator keeps it. SimpleImputer(add_indicator=True) adds one.
- Front
- What goes wrong when you mean-impute a column?
- Back
- The mean of the observed values stays wrong if the missingness is MAR or MNAR (47.58 against a true 50.06), and the spread shrinks even under MCAR: sd 8.35 against a true 9.94 with about 29% filled. The model also sees no trace that a value was filled, unless you add an indicator.
- Front
- State the rule for fitting preprocessing, and what breaks if you ignore it.
- Back
- Learn every statistic (fill value, mean, category list, encoding) on training rows only, and apply it unchanged elsewhere. Fitting on train and test hid a real shift: a test mean of 1.529 looked like 0.617 after scaling. A pipeline makes the rule automatic inside cross-validation.
- Front
- One outlier in a column: what does standard scaling do, and what are the alternatives?
- Back
- One value of 1,000 among 99 values with sd 2 pushed the standard deviation to 98.49 and shrank the scaled spread of the other values from 1.000 to 0.020. Median and IQR scaling kept it at 0.794. Also clip, or log-transform a skewed feature (skewness 5.15 became 0.02). Trees do not need scaling.
- Front
- Which encoding for which categorical feature?
- Back
- Few unordered levels: one-hot. Real order: ordinal. Many levels with a supervised signal: target encoding, out-of-fold and smoothed. Huge or open vocabularies: hashing (500 categories in 256 buckets still left 438 sharing a bucket) or learned embeddings. Cyclical numbers such as the hour: sin and cos.
- Front
- Why does target encoding leak, and what is the cure?
- Back
- A row's own label sits inside its own encoding if it is fitted and applied on the same rows. With labels independent of the category, the in-sample AUC was 0.770 and the out-of-fold AUC 0.501. Encode each fold from the other folds, use the full-train encoding for test and live rows, and give unseen levels the prior. Leave-one-out is not safe: on one constant level its training AUC was 0.000 against 0.473 for 5-fold.
- Front
- Write the smoothed target encoding and say what the smoothing does.
- Back
- (sum of targets in the level + m x overall mean) / (rows in the level + m). A level with few rows is pulled to the overall mean. With overall mean 0.3220 and m = 10, a one-row level with target 1 became 0.384 (raw 1.000) and a 100-row level at 0.800 became 0.757. It is a safeguard for rare levels, not a leakage fix.
- Front
- When does a feature cross help?
- Back
- When the effect exists only in a combination and the model is additive. With y positive when x1 times x2 is above 0, the best sign rule on x1 scored 0.500 and on x2 0.504, while the cross scored 0.952. Trees and networks learn crosses themselves. Crosses of high-cardinality features explode in width.
- Front
- State the point-in-time rule and two ways to break it.
- Back
- A feature for a prediction at time t may use only information that existed at t. Break it with a window that reaches past t, or by joining the latest value instead of the value as of t. Counting 7 days past t raised churn AUC from 0.773 to 0.921, from information that does not exist at prediction time.
- Front
- How does a point-in-time join work?
- Back
- For each event (key, time) take the latest feature row with the same key and a time not after the event, and ignore it if a TTL says it is too old. Rows (time 1, 3), (5, 4), (9, 10): an event at 8 gets 4, an event at 0 gets nothing, an event at 100 gets 10 or nothing with a TTL of 3. Rolling features use only earlier values.
- Front
- What is training-serving skew and how do you defend against it?
- Back
- A difference between performance in training and in serving, caused by different handling of data in the two pipelines, a change in the data, or a feedback loop. Defences: reuse code, log the features you served and compare, golden tests, monitoring. A 0 instead of the median for nulls cut precision from 0.831 to 0.556.
- Front
- What does a Pipeline with a ColumnTransformer buy you, and what does it not?
- Back
- One fitted object holds preprocessing and model, so cross-validation refits imputers, scalers and encoders in each fold and the saved object is the served one. By default unnamed columns are dropped (remainder='drop'). It does not cover features computed outside it, such as SQL joins and windows.
- Front
- Name the three kinds of drift and where each shows.
- Back
- Covariate (data) drift: P(X) changes with P(y | X) fixed, seen in input distributions with PSI or KS. Label shift: P(y) changes with P(X | y) fixed, hinted by the predicted positive rate (P(X) also moves, so input PSI can fire too). Concept drift: P(y | X) changes, seen only in labelled outcomes. Real changes can mix. Inputs PSI 0.0003 with accuracy falling from 1.000 to 0.659 is concept drift.
- Front
- Compute PSI and name its pitfalls.
- Back
- PSI = sum over bins of (actual share - expected share) x ln(actual / expected). Shares (0.5, 0.5) against (0.3, 0.7) give 0.1695. Pitfalls: empty bins need a floor (a new category gave 0.708 or 1.170 for floors of 1e-4 or 1e-6), bins change the value (0.2060, 0.2417, 0.2669 for 5, 10, 20 bins), and small samples add noise: about 0.095 at 100 rows with no drift.
- Front
- What does the KS statistic measure and what is its large-sample problem?
- Back
- The largest gap between two empirical CDFs, with no bins. With 100,000 rows each side, a mean shift of 0.02 gave KS 0.0076, above the approximate 5% critical value 0.0061, while PSI was 0.00033. A test can flag a shift too small to matter, so pair it with a size threshold.
- Front
- How do you monitor a model with delayed labels?
- Back
- Watch data quality, feature and score drift now; report true metrics by cohort once labels mature; compare cohorts of the same age. With a mean delay of 20 days, a 14-day-old cohort had only 0.510 of its positives labelled (rate 0.0253 against 0.0496).
- Front
- Compare retraining triggers.
- Back
- Schedule, drift threshold, performance drop on matured labels, or enough new labelled data. In the toy drift run: never 0.609 mean accuracy, every 10 weeks 0.908 with 3 retrains (worst week 0.673), accuracy trigger 0.952 with 15 retrains (worst week 0.854). Cost of retraining against cost of staleness decides.
- Front
- Describe a safe rollout and the feedback-loop trap.
- Back
- Offline validation, shadow mode (score but do not act), canary with guardrails, ramp, with rollback and a fallback. Feedback loop: if only approved applicants have outcomes, a retrained model never learns about the rejected. Keep an exploration or hold-out slice where decisions do not depend on the model.
- Front
- What do you record to reproduce a model, and why?
- Back
- Code version, a snapshot or hash of the training data, feature definitions, library versions, hyperparameters and seeds, stored with the model. A hash of a dataset changed when one cell changed. It lets you answer what changed and restore the previous model.
- Front
- In what order do you debug a model that works in the notebook and fails in production?
- Back
- 1 Inputs valid (schema, nulls, units, ranges). 2 Skew: served against training features for the same case. 3 Leakage in the original evaluation. 4 Drift (PSI per feature). 5 Label or definition mismatch. 6 Silent fallbacks, timeouts, wrong artifact. 7 Only then a real concept change: retrain or redesign.