Contents
Key concepts
Bias, variance and capacity
For squared loss, expected test error decomposes into bias², variance and irreducible noise. Low training error with a large, persistent gap to validation error signals variance (overfitting); high error on both signals bias. Learning curves against training-set size tell you whether more data will help. Regularisation, early stopping and ensembling trade a little bias for a larger cut in variance.
Linear models and regularisation
L1 (lasso) yields exact zeros because its constraint region has corners on the axes and its subgradient pulls with constant force λ; L2 (ridge) shrinks in proportion to the weight and stabilises correlated features. Elastic net mixes both and keeps groups of correlated features. In Bayesian terms L2 is MAP estimation with a Gaussian prior and L1 with a Laplace prior. Standardise features before penalising; unregularised logistic regression diverges on separable data.
Trees, bagging and boosting
Bagging (random forests) trains deep trees on bootstrap samples with feature subsampling and averages them, mainly reducing variance; out-of-bag samples give a free validation estimate. Boosting (XGBoost, LightGBM, CatBoost) adds shallow trees sequentially, each fitting the negative gradient of the loss, and mainly reduces bias; XGBoost uses a second-order (gradient and Hessian) approximation. Key boosting knobs: learning rate × number of trees, depth or leaves, minimum child weight, row and column subsampling, L1/L2 on leaf weights and early stopping on a validation set. Tabular foundation models such as TabPFN now rival tuned GBDTs on small and medium datasets through in-context learning (TabPFN-2.5 handles up to 50,000 rows), while GBDTs remain strong contenders on practical tabular datasets (TabArena, 2025).
SVMs, kernels and logistic regression
A linear SVM minimises hinge loss and maximises the margin; its solution depends only on support vectors and its scores are not probabilities (Platt scaling calibrates them). Logistic regression minimises log loss and outputs log-odds. The kernel trick replaces inner products with k(x, x′), giving non-linear boundaries, but working with the n × n kernel matrix makes training time grow at least quadratically with n. Logistic regression can be kernelised too.
Validation that matches the data
K-fold assumes independent, identically distributed rows. For temporal data use out-of-time splits and rolling-origin backtests, with a gap when labels mature late; for repeated entities use GroupKFold so a customer never appears on both sides. Fit every preprocessing step (scalers, encoders, imputers, resampling) inside the training fold, ideally with a pipeline object.
Flow · 3 stepsValidation that matches the data's structure
- Match the split k-fold assumes independent, identically distributed rows; temporal data uses out-of-time splits with a gap; repeated entities use GroupKFold.
- Fit preprocessing in the fold Fit every preprocessing step (scalers, encoders, imputers, resampling) inside the training fold, ideally with a pipeline object.
- Evaluate and repeat Evaluate on the held-out fold, then repeat across folds; a customer never appears on both sides.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Match the split | k-fold assumes independent, identically distributed rows; temporal data uses out-of-time splits with a gap; repeated entities use GroupKFold. |
| 2 | Fit preprocessing in the fold | Fit every preprocessing step (scalers, encoders, imputers, resampling) inside the training fold, ideally with a pipeline object. |
| 3 | Evaluate and repeat | Evaluate on the held-out fold, then repeat across folds; a customer never appears on both sides. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Tabular data | Input | rows, time, entity IDs |
| Choose split | Split | k-fold / out-of-time / GroupKFold |
| Fit preprocessing in fold | Fit | scalers, encoders, imputers, resampling |
| Fit model | Fit | inside the training fold |
| Evaluate held-out fold | Evaluate | out-of-time or grouped |
Source: This page's text
Metrics, thresholds and calibration
Precision = TP/(TP+FP), recall = TP/(TP+FN). Under heavy imbalance ROC-AUC can look excellent while precision is tiny, so report PR-AUC and precision or recall at the operating point. Choose thresholds from error costs, not 0.5. Calibrate scores with Platt scaling, isotonic regression (needs roughly 1,000+ calibration samples) or temperature scaling and check with reliability diagrams or the Brier score. For regression, MAE targets the median, RMSE the mean, pinball loss a chosen quantile; MAPE breaks near zero, so forecasting uses WAPE or MASE.
Feature importance and explanation
Impurity (MDI) importance is computed on training data and is biased towards high-cardinality and continuous features. Permutation importance on held-out data is model-agnostic, but correlated features share or mask importance. SHAP gives local, additive attributions, exact and fast for trees (TreeSHAP). None of these is causal, and regulated settings need explanations a customer can act on, such as reason codes.
Unsupervised and probabilistic tools
PCA finds orthogonal directions of maximal variance: the eigenvectors of the covariance matrix, computed in practice from the SVD of the centred data; choose components by explained variance or downstream performance. K-means (Lloyd’s algorithm, k-means++ seeding) finds local optima and assumes roughly spherical clusters; mini-batch updates handle streams. Bayesian networks encode conditional independences, and “explaining away” arises at colliders.
Worked examples
Choosing a fraud threshold by expected cost
A card issuer scores 1,000,000 transactions a day with a 0.2% fraud rate. Missed fraud costs £120 on average; a false decline costs £8 in friction and churn. Threshold A gives recall 80% at a false-positive rate (FPR) of 0.5%; threshold B gives recall 90% at FPR 2%. Which is better, and what is the cost-optimal threshold if scores are calibrated probabilities?
Positives = 0.002 × 1,000,000 = 2,000; negatives = 998,000.
| Threshold A | Threshold B | |
|---|---|---|
| Fraud caught | 0.80 × 2,000 = 1,600 | 0.90 × 2,000 = 1,800 |
| Fraud missed × £120 | 400 × 120 = £48,000 | 200 × 120 = £24,000 |
| False declines × £8 | 0.005 × 998,000 = 4,990 → £39,920 | 0.02 × 998,000 = 19,960 → £159,680 |
| Total daily cost | £87,920 | £183,680 |
| Precision | 1,600 / 6,590 = 24.3% | 1,800 / 21,760 = 8.3% |
A is cheaper by about £96k a day despite the lower recall: B’s extra 200 frauds caught save £24,000 but its extra 14,970 false declines cost £119,760.
Optimal threshold. Decline when the expected loss of approving exceeds that of declining: p × 120 > (1 − p) × 8 ⇒ p > 8 / (120 + 8) = 0.0625. This only holds if the scores are calibrated, so check calibration on recent held-out data first.
In practice add a middle tier (step-up authentication for, say, 0.06 < p < 0.3, costing perhaps £1 in friction), weight recall by transaction value, report alert volume per day, and re-tune when the fraud base rate shifts.
CalculatorFraud threshold cost choice
- Total daily cost
- £87,920
- Precision
- 24.3%
- Optimal threshold
- 6.25%
Total daily cost = Transactions per day × Fraud rate (fraction) × (1 − Recall) × Missed fraud cost + Transactions per day × (1 − Fraud rate (fraction)) × False-positive rate × False decline cost = £87,920
Precision = Transactions per day × Fraud rate (fraction) × Recall ÷ (Transactions per day × Fraud rate (fraction) × Recall + Transactions per day × (1 − Fraud rate (fraction)) × False-positive rate) = 24.3%
Optimal threshold = False decline cost ÷ (Missed fraud cost + False decline cost) = 6.25%
| Case | Transactions per day | Fraud rate (fraction) | Missed fraud cost (£) | False decline cost (£) | Recall | False-positive rate | Total daily cost | Precision | Optimal threshold |
|---|---|---|---|---|---|---|---|---|---|
| Threshold A | 1,000,000 | 0.002 | 120 | 8 | 0.8 | 0.005 | £87,920 | 24.3% | 6.25% |
| Threshold B | 1,000,000 | 0.002 | 120 | 8 | 0.9 | 0.02 | £183,680 | 8.3% | 6.25% |
Why ROC-AUC flatters a rare-event model
A screening model runs on 1,000,000 cases with 0.1% positives. At one threshold it has a true-positive rate (TPR) of 0.90 and an FPR of 0.01, a point that looks excellent on a ROC curve. What does the review team actually see, and what would it take to reach 50% precision?
Positives = 1,000; negatives = 999,000.
- TP = 0.90 × 1,000 = 900
- FP = 0.01 × 999,000 = 9,990
- Precision = 900 / (900 + 9,990) = 8.3%: about 11 false alerts for every true one.
To reach 50% precision with TP = 900 you need FP ≈ 900, i.e. FPR ≈ 900 / 999,000 ≈ 0.09%, a tenfold cut that is barely visible on a ROC plot. At FPR 0.1% you get FP = 999 and precision = 900 / 1,899 = 47%.
ROC curves divide FP by the huge negative count, hiding the alert burden; precision does not. So for rare events report PR-AUC, precision at the reviewers’ daily capacity (precision@k) and recall at a fixed FPR, and choose the threshold from costs and capacity.
L1 versus L2 shrinkage on an orthonormal design
With orthonormal features, ordinary least squares gives coefficients β̂ = (0.8, 0.3). Compute the lasso solution for ½‖y − Xβ‖² + λ‖β‖₁ and the ridge solution for ½‖y − Xβ‖² + (λ/2)‖β‖², both with λ = 0.5, and explain the difference.
With XᵀX = I the problems separate per coordinate.
Lasso uses soft-thresholding: βⱼ = sign(β̂ⱼ) × max(|β̂ⱼ| − λ, 0)
- β₁ = 0.8 − 0.5 = 0.3
- β₂ = max(0.3 − 0.5, 0) = 0 (exactly zero)
Ridge uses proportional shrinkage: βⱼ = β̂ⱼ / (1 + λ)
- β₁ = 0.8 / 1.5 = 0.533
- β₂ = 0.3 / 1.5 = 0.2 (smaller, never zero)
Why. The L1 penalty has a constant-magnitude subgradient λ × sign(β), so any coefficient whose evidence |β̂| is below λ is pinned at zero; the L2 gradient λβ fades as β shrinks, so it never reaches zero. Geometrically, the L1 ball’s corners lie on the axes, so the loss contours usually touch it there.
When to use which. L1 for feature selection in high-dimensional sparse problems; L2 for correlated features and stability; elastic net when correlated groups should be kept or dropped together. Standardise features first, or the penalty punishes features merely for their units.
What changed recently
scikit-learn 1.9: callbacks and threshold tooling
scikit-learn 1.9 added an experimental callback API (progress bars, per-iteration scoring), a metrics.metric_at_thresholds helper that computes a metric across all thresholds, and deprecated the probability parameter of SVC and NuSVC in favour of CalibratedClassifierCV. The library is steering users to treat decision thresholds and calibration as explicit, validated steps, which is what interviewers want to hear in fraud or risk questions.
scikit-learn 1.8: GPU arrays, free-threading, temperature scaling
scikit-learn 1.8 widened experimental GPU support through the Array API, supported free-threaded Python 3.14 and added temperature scaling as a calibration method. Classical pipelines can now run parts of preprocessing and models on GPU arrays and scale across threads, and calibration options beyond Platt and isotonic are standard.
TabPFN-2.5 pushes tabular foundation models to 50k rows
Building on TabPFN v2 (Nature, January 2025), TabPFN-2.5 handles up to 50,000 rows and 2,000 features, reports matching an AutoGluon ensemble tuned for four hours, and can be distilled into an MLP or tree ensemble for cheaper serving. A strong small-to-medium tabular baseline set now includes an in-context foundation model alongside tuned gradient boosting, with its inference-cost caveats.
Chronos-2: zero-shot forecasting with covariates
Amazon’s Chronos-2 extends pretrained forecasting from univariate series to multivariate and covariate-informed forecasting, using group attention to share information across related series, and reports state-of-the-art results on fev-bench and GIFT-Eval. Forecasting questions now expect you to compare such models with classical baselines through rolling-origin backtests.
TabArena: a living benchmark for tabular ML
TabArena, a continuously maintained benchmark, found that gradient-boosted trees remain strong on practical datasets, deep models catch up with larger time budgets and ensembling, foundation models excel on small data, and validation and ensembling choices move rankings a lot. It replaces the 2022 ‘trees always win’ summary with a more conditional answer.
Pitfalls
- Random k-fold on temporal or grouped data, or fitting scalers, encoders or SMOTE on the full data before splitting.
- Defaulting to a 0.5 threshold, or optimising F1 when error costs are asymmetric.
- Reporting ROC-AUC or accuracy alone on a 1:1,000 problem.
- Saying boosting mainly reduces variance, or that random forests cannot overfit.
- Reading impurity importance as causal, or dropping one of two correlated features because permutation importance looked low for both.
- Optimising MAPE when targets can be near zero, or evaluating forecasts on sales truncated by stock-outs.
How interviewers probe it
- Why gradient-boosted trees rather than a neural network here? Then: when would you choose something else (huge data with learned embeddings, multimodal inputs, very small data, strict interpretability)?
- Whiteboard derivations: L1 sparsity, MLE versus MAP with priors, PCA via SVD, the logistic-regression gradient.
- Turning metrics into money: threshold choice, value-weighted recall, tiered actions and alert capacity.
- Design the validation for two years of transactions with customer IDs and a 60-day label delay.
- Coding: implement k-means with NumPy, then adapt it to a stream you cannot store.
- LLM-adjacent: build a calibrated classifier on top of LLM log-probabilities, or a router that decides which model answers.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Contrast bagging and boosting: what error each reduces, how they are trained, and their failure modes.
Model answer, written in a candidate's voice
- Bagging: independent bootstrap-sample models, averaged/voted; RF adds random feature subsampling; mainly reduces variance.
- Boosting: sequential additive learners fit residuals or gradients; mainly reduces bias.
- Failure modes: bagging leaves systematic bias/underfit; boosting overfits noise and is sensitive to labels, outliers, and hyperparameters.
- Bagging is robust and easy to parallelise; boosting is sequential and hyperparameter-sensitive.
- Practical defaults: GBDT for tabular data; RF as a strong baseline.
Why does an L1 penalty give sparse weights while L2 shrinks them smoothly? When would you choose each, and what does elastic net add?
Model answer, written in a candidate's voice
- Geometry: L1’s diamond constraint has corners on the axes, so the optimum often lands at zero; L2’s ball constraint is smooth and rarely touches an axis exactly.
- Subgradient: L1 applies a roughly constant pull towards zero, while L2’s pull is proportional to the weight, so small weights shrink slowly and large weights are pulled harder.
- Bayesian view: L1 is MAP with a Laplace prior, L2 with a Gaussian prior.
- Use cases: L1 for feature selection and sparse high-dimensional problems; L2 for correlated features, stability, and shrinkage without hard zeros.
- Elastic net mixes L1 and L2, keeps correlated feature groups together, and is more stable than pure L1.
- Standardise features before penalising: both penalties are scale-dependent.
A stakeholder wants to know which features drive your fraud random forest. Compare impurity importance, permutation importance and SHAP, and their pitfalls.
Model answer, written in a candidate's voice
- MDI is fast but training-set and biased towards high-cardinality/continuous features; not enough alone.
- Permutation importance on held-out data is model-agnostic but correlated features share or hide importance.
- SHAP gives local additive attributions; TreeSHAP is exact for trees but costly and still correlation-sensitive.
- Use held-out data, stability checks, and global plus local views rather than a single ranking.
- Importance is not causation; tailor to audience with plain-language reason codes and documented limits.
You have finished this topic.
Reading
- An Introduction to Statistical LearningFree textbook (R and Python editions) covering regression, classification, resampling, trees, SVMs and unsupervised learning.
- Cross-validation: evaluating estimator performance (scikit-learn)Grouped and time-series splitters and why i.i.d. k-fold fails on dependent data.
- Probability calibration (scikit-learn)Platt, isotonic and temperature scaling with their data requirements and effects on ranking.
- Permutation feature importance (scikit-learn)How permutation importance works and why impurity-based importance is biased.
- XGBoost: A Scalable Tree Boosting SystemThe regularised second-order boosting objective and the systems tricks behind the default tabular model.
- A Unified Approach to Interpreting Model PredictionsThe SHAP paper: additive feature attributions grounded in Shapley values.
- Forecasting: Principles and Practice (3rd ed)Free text on time-series validation, forecast accuracy measures (MASE, quantiles) and baselines.
- TabArena: A Living Benchmark for Machine Learning on Tabular DataCurrent evidence on trees, deep models and tabular foundation models, and how validation and ensembling change the ranking.
Practise this topic
- Contrast bagging and boosting: what error each reduces, how they are trained, and their failure modes.
- Why does an L1 penalty give sparse weights while L2 shrinks them smoothly? When would you choose each, and what does elastic net add?
- A stakeholder wants to know which features drive your fraud random forest. Compare impurity importance, permutation importance and SHAP, and their pitfalls.
- You have two years of card transactions with customer IDs. How do you split into train/validation/test and run cross-validation, and why not random k-fold?
- A fraud model outputs scores. How do you choose the decision threshold, and which metrics do you report?
- For food-delivery ETAs, compare MAE, RMSE, MAPE and quantile (pinball) loss. Late arrivals hurt more than early ones; how do you reflect that?
- How would you evaluate a SKU-level grocery demand forecast across thousands of products with intermittent demand?
- Define precision and recall, explain the trade-off, and say which you would prioritise for (a) screening for a rare disease and (b) flagging content for a small human-review team. When is ROC-AUC misleading?
- Compare a linear SVM with logistic regression (loss, outputs, behaviour on separable data) and explain how the kernel trick lets an SVM learn non-linear boundaries.
- Implement k-means from scratch with NumPy, then adapt it to data that arrives as a stream you cannot store.
- A colleague proposes replacing your tuned gradient-boosting model for a 6,000-row credit-risk dataset with a tabular foundation model such as TabPFN. How do these models work, when would you expect them to win, and how would you evaluate the switch?
- For weekly demand forecasting across 20,000 products with promotions and prices as covariates, compare a classical stack (seasonal baselines, ETS, gradient boosting on lag features) with a pretrained time-series foundation model such as Chronos-2 used zero-shot. How would you decide, and how would you evaluate?
- Why does L1 regularisation push weights exactly to zero while L2 only shrinks them? Give a geometric and a gradient-based explanation.
- How do you tell whether a model is overfitting or underfitting, and what would you try in each case? How does “double descent” complicate the classic bias–variance picture?
- How does k-fold cross-validation work, when is it the wrong tool, and what are three ways data leakage can silently inflate a validation score?
- What does a Bayesian network encode, how do you read conditional independences off the graph, and how does “explaining away” arise?