---
title: Classical machine learning
url: https://gurkanozkan.ai/learn/topics/classical-ml/
markdown: https://gurkanozkan.ai/learn/topics/classical-ml.md
kind: topic
tracks:
  - ML engineering
  - Research
  - Applied LLM
json: https://gurkanozkan.ai/api/learn/topics/classical-ml.json
---

# Classical machine learning

Tabular models, forecasting and classic supervised learning still power fraud, credit, pricing, logistics and many components around LLMs (routers, classifiers, rankers). Interviewers test whether you can pick a model and a validation scheme that fit the data's structure, reason about bias and variance, regularisation, ensembles, calibration and thresholds, and translate metrics into business cost. Gradient-boosted trees remain the default for medium-sized tabular data; expect to justify that choice, to derive things such as L1 sparsity or MAP estimation at the whiteboard, and to explain why random k-fold is wrong for transactions over time.

## 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.

### 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?

**Solution**

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.


### 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?

**Solution**

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.

**Solution**

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

- **Jun 2026: 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. [Source](https://scikit-learn.org/stable/whats_new/v1.9.html)
- **Dec 2025: 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. [Source](https://scikit-learn.org/stable/auto_examples/release_highlights/plot_release_highlights_1_8_0.html)
- **Nov 2025: 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. [Source](https://arxiv.org/abs/2511.08667)
- **Oct 2025: 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. [Source](https://arxiv.org/abs/2510.15821)
- **Jun 2025: 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. [Source](https://arxiv.org/abs/2506.16791)

## 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.

## Reading

- [An Introduction to Statistical Learning](https://www.statlearning.com/) (Book, 600 min, Intro): Free textbook (R and Python editions) covering regression, classification, resampling, trees, SVMs and unsupervised learning.
- [Cross-validation: evaluating estimator performance (scikit-learn)](https://scikit-learn.org/stable/modules/cross_validation.html) (Docs, 30 min, Core): Grouped and time-series splitters and why i.i.d. k-fold fails on dependent data.
- [Probability calibration (scikit-learn)](https://scikit-learn.org/stable/modules/calibration.html) (Docs, 25 min, Core): Platt, isotonic and temperature scaling with their data requirements and effects on ranking.
- [Permutation feature importance (scikit-learn)](https://scikit-learn.org/stable/modules/permutation_importance.html) (Docs, 20 min, Core): How permutation importance works and why impurity-based importance is biased.
- [XGBoost: A Scalable Tree Boosting System](https://arxiv.org/abs/1603.02754) (Paper, 60 min, Deep): The regularised second-order boosting objective and the systems tricks behind the default tabular model.
- [A Unified Approach to Interpreting Model Predictions](https://arxiv.org/abs/1705.07874) (Paper, 50 min, Deep): The SHAP paper: additive feature attributions grounded in Shapley values.
- [Forecasting: Principles and Practice (3rd ed)](https://otexts.com/fpp3/) (Book, 240 min, Core): Free text on time-series validation, forecast accuracy measures (MASE, quantiles) and baselines.
- [TabArena: A Living Benchmark for Machine Learning on Tabular Data](https://arxiv.org/abs/2506.16791) (Paper, 60 min, Core): Current 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.](https://gurkanozkan.ai/learn/questions/mle-bagging-vs-boosting-05.md)
- [Why does an L1 penalty give sparse weights while L2 shrinks them smoothly? When would you choose each, and what does elastic net add?](https://gurkanozkan.ai/learn/questions/mle-l1-vs-l2-regularisation-03.md)
- [A stakeholder wants to know which features drive your fraud random forest. Compare impurity importance, permutation importance and SHAP, and their pitfalls.](https://gurkanozkan.ai/learn/questions/mle-feature-importance-in-tree-ensembles-06.md)
- [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?](https://gurkanozkan.ai/learn/questions/mle-validation-schemes-for-temporal-or-grouped-data-07.md)
- [A fraud model outputs scores. How do you choose the decision threshold, and which metrics do you report?](https://gurkanozkan.ai/learn/questions/mle-choosing-a-decision-threshold-by-cost-22.md)
- [For food-delivery ETAs, compare MAE, RMSE, MAPE and quantile (pinball) loss. Late arrivals hurt more than early ones; how do you reflect that?](https://gurkanozkan.ai/learn/questions/mle-loss-and-metric-choice-for-eta-prediction-26.md)
- [How would you evaluate a SKU-level grocery demand forecast across thousands of products with intermittent demand?](https://gurkanozkan.ai/learn/questions/mle-evaluating-demand-forecasts-27.md)
- [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…](https://gurkanozkan.ai/learn/questions/research-precision-recall-imbalanced-019.md)
- [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…](https://gurkanozkan.ai/learn/questions/research-svm-vs-logistic-kernels-022.md)
- [Implement k-means from scratch with NumPy, then adapt it to data that arrives as a stream you cannot store.](https://gurkanozkan.ai/learn/questions/research-kmeans-then-streaming-085.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-cml-01.md)
- [For weekly demand forecasting across 20,000 products with promotions and prices as covariates, compare a classical stack (seasonal baselines, ETS, gradient…](https://gurkanozkan.ai/learn/questions/recent-a-cml-02.md)
- [Why does L1 regularisation push weights exactly to zero while L2 only shrinks them? Give a geometric and a gradient-based explanation.](https://gurkanozkan.ai/learn/questions/research-why-l1-gives-sparsity-013.md)
- [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…](https://gurkanozkan.ai/learn/questions/research-over-and-underfitting-021.md)
- [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?](https://gurkanozkan.ai/learn/questions/research-cross-validation-and-leakage-027.md)
- [What does a Bayesian network encode, how do you read conditional independences off the graph, and how does "explaining away" arise?](https://gurkanozkan.ai/learn/questions/research-bayesian-networks-028.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
