Classical ML

Linear and logistic regression, naive Bayes, trees, random forests and gradient-boosted trees (XGBoost, LightGBM, CatBoost), SVMs, nearest neighbours, clustering, anomaly detection, PCA and hyperparameter search, with the dated evidence on when they still beat deep learning on tables. Every model runs live in the page, written to match scikit-learn and checked against it. A child page of Topic: ml-fundamentals; data as of 3 October 2026. Reading: 29 min, plus 8 in closed details.

The idea in one screen

A classical model is a fixed shape fitted to a table of features: a weighted sum draws a straight boundary, a tree draws an axis-aligned staircase, and a sum of hundreds of shallow trees draws almost any boundary while still cutting along the features one at a time, which is why boosted trees were the default on tables for twenty years, until tabular foundation models overtook them on small and medium tables in 2025 (section 4).

You need: log-loss and the hinge loss (Loss functions); eigenvectors and the SVD for PCA (Linear algebra for ML). Penalties are on Regularisation, and how to score a classifier is on Evaluation metrics; this page links them rather than repeating them.

bias, variance
error from a shape too rigid for the data, against error from a fit that changes a lot when a few training rows change
bagging, boosting
averaging many models fitted to resampled rows (cuts variance), against adding models in sequence, each fitting what is left (cuts bias)
margin, support vectors
the empty band an SVM keeps between the classes, and the training points that touch or enter it
kernel
a similarity that acts as a dot product in a feature space never built
out-of-bag (OOB)
the rows a bagged tree never saw, used as free validation
inertia
k-means' objective: the sum of squared distances from each point to its centre
Same points, three shapes: the line cannot enclose the ring, the staircase roughly can, the sum of trees does. On the default data (two noisy concentric circles, scikit-learn make_circles) logistic regression gets 50.0% of the 60 held-out points right, no better than a coin; a depth-3 tree 88.3%; gradient boosting with 100 depth-2 trees 98.3%. On the real tumours the line is already enough: logistic regression 90.6% held out, boosting 90.1%. The shape has to match the data, not be as flexible as possible.

Shading is the model's probability of the blue class; the solid line is where it decides. Computed live by this page's own models, which reproduce scikit-learn (the check is under the Boundary lab, where seven models can be set side by side); the quoted numbers are in src/check/hero_numbers.json.

MethodHow it decidesAssumesStrong whenWeak when
Linear, logistic regressiona weighted sum of the featureseffects add up (on the log-odds scale for logistic)few rows, many features, interpretation matters; a baseline alwaysinteractions and thresholds the features do not encode
Naive BayesBayes' rule, features independent given the classconditional independencetext, very little data, speedcorrelated features: probabilities come out overconfident
Decision treea sequence of yes/no questions on one feature at a timeaxis-aligned, piecewise-constant structurereadability, mixed feature typesalone: high variance, staircase boundaries
Random forestaverage of many decorrelated deep treesas a treea strong model with almost no tuning; free out-of-bag errorsmooth trends, extrapolation
Gradient boostingshallow trees added one by one, each fitting what is leftas a treetabular data, especially large tables on CPUneeds early stopping and some tuning
SVMthe widest margin between classes, in a kernel's feature spacea kernel that matches the data's geometrysmall and medium data, many featurestens of thousands of rows and more; probabilities
kNNvote or mean of the k closest training pointsa distance that means somethinglow dimensions, lots of data, no training timehigh dimensions, unscaled features, slow queries
Every task and its canonical methods (the map of sections)
ParadigmTaskCanonical methodsSection
SupervisedRegression (numeric target)linear and polynomial regression, ridge, lasso, elastic net, trees, gradient boosting1, 3
SupervisedClassification (categorical target)logistic regression, naive Bayes, SVM, kNN, trees and their ensembles1 to 6
UnsupervisedClusteringk-means, hierarchical, DBSCAN, Gaussian mixtures fitted by EM7
UnsupervisedAnomaly detectionisolation forest, one-class SVM, density or reconstruction thresholds8
UnsupervisedDimensionality reductionPCA, t-SNE, UMAP, autoencoders9

The comparison-level summary is on the parent, Topic: ml-fundamentals (Reading tab, "Classical ML: still the default on tables"); this page owns the detail.

1 · Linear models and naive Bayes

Linear regression predicts ŷ = wTx + b, fitted by least squares; the closed form w = (XTX)−1XTy is the maximum-likelihood fit under Gaussian noise (Loss functions). Polynomial regression is the same model on powers and products of the features, still linear in the weights. Ridge (L2), lasso (L1, some weights exactly zero) and elastic net (both) add a penalty; the geometry is on Regularisation.

Logistic regression is a linear model, a sigmoid and binary cross entropy: p(y = 1 | x) = σ(wTx + b). The weights act additively on the log-odds, so the boundary is a hyperplane: the straight line in the hero's first panel, which cannot enclose a ring unless the features are transformed first (circles in the lab, against an RBF SVM). Softmax regression is the multiclass version, one weight vector per class. scikit-learn's LogisticRegression is L2-penalised by default with C = 1, minimising ½||w||2 + CΣ log-loss (user guide): a "plain" logistic regression in scikit-learn shrinks its weights.

Naive Bayes applies Bayes' rule assuming the features independent given the class: p(y | x) ∝ p(y) ∏j p(xj | y). Each factor is estimated alone (word frequencies per class for text, a Gaussian per feature for numbers), so training is one counting pass. The assumption is almost never true, yet it is a strong cheap baseline for text: on short snippets it beat SVMs, and NBSVM (an SVM on naive Bayes log-count ratios) was a strong text baseline for years (Wang and Manning 2012). The generative model reaches its best error with fewer examples, though logistic regression ends lower with enough data (Ng and Jordan 2002). What breaks is the probability, and the picture shows why.

The same evidence counted twice looks twice as strong. One word has likelihood ratio 3 between the classes, priors even: the posterior is 3 / (3 + 1) = 75%. Add a near-copy of the feature ("price" and "prices") and naive Bayes multiplies the ratio again.
1 copy, 3 : 175.0%
2 copies, 9 : 190.0%
3 copies, 27 : 196.4%

Posterior = 3m / (3m + 1) for m copies derived, illustrative ratio. Correlated features double-count evidence, so naive Bayes probabilities come out overconfident; recalibrate before using them. The calibration animation on Evaluation metrics does this to a real naive Bayes model.

2 · Decision trees

A tree asks one yes/no question about one feature ("is mean radius ≤ 0.26?", in standardised units) and predicts, in each leaf, the majority class or mean target of the training points that reach it. It is grown greedily, CART style (Breiman, Friedman, Olshen and Stone 1984): at each node try every feature and every threshold between neighbouring distinct values (scikit-learn uses the midpoint) and keep the split that lowers the children's weighted impurity most.

Gini = 1 − Σk pk2   entropy = −Σk pk log2 pk
gain = I(parent) − (nL/n) I(left) − (nR/n) I(right)
pk
share of class k among the node's training points; for regression, I is the variance of the targets (squared error)

Fig. 1 grows one on real tumours: 398 training tumours from the Wisconsin breast cancer data, two features (mean radius across, mean texture in depth, both standardised). Every leaf is a column over its box of the plane, as tall as its share of malignant tumours, which is its prediction (blue malignant, orange benign); each tumour rides on its leaf.

  1. Depth 0: one leaf. Before any question every tumour gets the same prediction, the training share of malignant tumours, 37%; Gini impurity 1 − p2 − (1 − p)2 = 0.467. Calling everything benign scores 62.6% on the test tumours.
  2. Depth 1: the best single question. Every midpoint of both features is tried; mean radius ≤ 0.26 lowers the weighted Gini most, to 0.187. The points drop through the cut: the small-radius leaf falls to 13% malignant, the other rises to 94%. One question gets 88.3% of unseen tumours right.
  3. Depth 2: each leaf asks its own question. The same greedy rule runs again on each leaf's own points only: 4 leaves, training 89.7%, test 87.7%.
  4. Depth 3: a staircase appears. 8 leaves, all boxes with edges parallel to the axes: training 90.7%, test 87.1%.
  5. Depth 4: the best test score. 14 leaves; training 92.7%, test 89.5%, the peak of the run.
  6. Depth 6: fitting the noise. 28 leaves, many holding a handful of tumours: training rises to 95.5%, test falls to 87.7%.
  7. No depth limit: every leaf pure. The tree splits until each leaf holds one class: 55 leaves, 100.0% of training tumours right and 86.0% of test tumours. The thin towers and flat tiles are single tumours: it has memorised them.

Depth decides between bias and variance

Unlimited, a tree fits any training set exactly, and its predictions change a lot when a few points change (high variance); depth, a minimum leaf size or cost-complexity pruning hold it back. The chart is Fig. 1's run: test accuracy peaks at depth 4 and falls as the tree memorises.

Greedy means one step ahead: a split useless alone but making the next one perfect can be missed at depth 1 (XOR in the lab; the hero's XOR data shows the depth-3 tree at 55% held out). Trees need no feature scaling (only the order of values matters), handle mixed types and read as rules. Axis-aligned staircases are a weakness on a diagonal boundary and, on tables, a strength: rotating a table's features hurts trees and helps nothing, because real tabular features carry meaning one at a time (Grinsztajn et al., section 4).

Test accuracy peaks at depth 4 and falls as the tree memorises. The tree of Fig. 1 at every depth: 398 training tumours, 171 held out; the marked depth follows Fig. 1's step.
Checked against scikit-learn, and the data

Defaults reproduce scikit-learn's DecisionTreeClassifier(max_depth = d, random_state = 0) independently: identical predictions on a 41 × 41 grid at every depth, and the same accuracies (recompute.py: depth 4 best on test at 89.5%; no limit 55 leaves, 100% training, 86.0% test; predicting "benign" for all scores 62.6%). Data: UCI Breast Cancer Wisconsin (Diagnostic), 569 tumours, 70/30 stratified split.

3 · Ensembles: bagging cuts variance, boosting cuts bias

Bagging (bootstrap aggregating) trains many models, each on a bootstrap sample of the rows (n draws with replacement, which leaves out about 1 − (1 − 1/n)n ≈ 1/e ≈ 36.8% of the rows), and averages or votes (Breiman 1996). Averaging B models of variance σ2 and pairwise correlation ρ leaves ρσ2 + (1 − ρ)σ2/B: more trees remove the second term, only less correlated trees reduce the first (ESL eq. 15.1). A random forest lowers ρ by letting each split consider only a random subset of the features (Breiman 2001; √p for classification is usual; scikit-learn's regressor defaults to all features since version 1.1, which is plain bagging, docs). The rows a tree never saw give an out-of-bag error for free (the lab shows it). Forests are close to tuning-free: across six algorithms on 38 OpenML datasets, random forest (ranger) gained least from tuning, 0.006 AUC against 0.042 for SVMs (Probst, Boulesteix and Bischl 2019, Table 2).

Gradient boosting (Friedman 2001) treats the ensemble's predictions F as the parameters and takes gradient steps in function space: each new tree fits the negative gradient of the loss with respect to F, exactly the residual y − F(x) for squared error, and is added with a small learning rate ν (shrinkage). Each shallow tree is high-bias and low-variance; the sum drives bias down stage by stage and eventually fits the noise, so the number of stages is set by early stopping on held-out data. AdaBoost is the same idea with the exponential loss (Friedman, Hastie and Tibshirani 2000), which is why it suffers under label noise (Loss functions, "the margin").

Fig. 2 is the same real curve three ways: head acceleration in simulated motorcycle crashes against time after impact (Silverman 1985, the mcycle data), 133 readings, every fourth held out (green). The front plate holds the readings and the ensemble's curve (blue); the plates behind hold its trees. One tree overfits, a forest never gets worse with more trees, boosting is best near 20 stages and then rises.

  1. One tree on a bootstrap sample. A full-depth regression tree grown on the 100 training readings drawn with replacement; its staircase (orange, on the plate behind) chases single readings, and a forest of one is that tree. Held-out error 1169 g².
  2. Three trees. Each plate holds a tree grown on its own bootstrap sample; they disagree most where readings are sparse. Their predictions stream forward into the average, already smoother: 1080.
  3. Ten trees. (Six plates are drawn.) Averaging cuts variance; no single tree is this smooth: 860.
  4. Fifty trees. The average barely moves any more: 798.
  5. Two hundred trees. Held-out 803, training 204: past about 50 trees the average barely moves, and the small wobble is noise on 33 held-out readings. More trees never make a forest worse; they only stop helping.
Checked against scikit-learn, and the data

The tree and boosting reproduce scikit-learn independently (DecisionTreeRegressor and GradientBoostingRegressor(learning_rate = 0.3, max_depth = 2): predictions identical to 10−13, training error at every stage identical). Held-out errors in recompute.py: best single tree at depth 4 (711 g²) against 905 unlimited; boosting best near 20 stages (716) rising to 888 at 200; scikit-learn's own forests (5 seeds) settle between 807 and 821 from 50 trees on and never rise. The forest here draws its own bootstrap samples, so its numbers differ slightly from scikit-learn's; each of its trees is identical to scikit-learn's on the same sample. With only 33 held-out readings (variance 2,828 g²) a difference of a few dozen is noise. Data: MASS::mcycle.

XGBoost, LightGBM, CatBoost: what each added

XGBoost (Chen and Guestrin 2016) makes each step a second-order (Newton) step, using the loss's first and second derivatives, with a charge γ per leaf and an L2 shrink λ on leaf values; it also added column and row subsampling, a sparsity-aware split finder for missing values, and a weighted quantile sketch for approximate splits.

XGBoost's objective, leaf weight and split gain (and why Huber is a poor fit: a correction)

With gi, hi the first and second derivatives of the loss at the current prediction and G, H their sums over a leaf:

obj ≈ Σi [gi f(xi) + ½ hi f(xi)2] + γT + ½λ Σ w2   w* = −G / (H + λ)
gain = ½ [GL2/(HL + λ) + GR2/(HR + λ) − (GL + GR)2/(HL + HR + λ)] − γ
T
number of leaves; γ charges each new leaf, λ shrinks leaf values (XGBoost defaults: λ = 1, γ = 0, learning rate 0.3, depth 6, parameters)
w*
the best value of a leaf; for log-loss with λ = 0 it is Σ(y − p) / Σp(1 − p), the leaf update scikit-learn's gradient boosting classifier also uses and this page's lab runs. Worked by hand on Calculus and optimisation for ML

So the loss needs usable curvature: the Huber loss has second derivative 0 beyond its threshold, leaves full of large errors get H ≈ 0, and the step is set by λ alone. Correction to the old pageIt said XGBoost prefers twice-differentiable losses "like log-cosh over Huber". The direction is right, but XGBoost ships its own answer: the objective reg:pseudohubererror, "a twice differentiable alternative to absolute loss", with huber_slope as its threshold, alongside reg:absoluteerror and reg:quantileerror, which use smooth approximations (XGBoost parameters, read 3 October 2026). Log-cosh is not a built-in objective.

LightGBM (Ke et al. 2017) bins each feature into a histogram (255 bins by default) so the split search runs over bins, not rows, and grows trees leaf-wise instead of level by level (the figure).

LightGBM also samples rows by gradient size (GOSS: keep the large-gradient rows, subsample the rest) and bundles mutually exclusive sparse features (EFB); it reported training up to over 20 times faster than conventional gradient boosting at the same accuracy. CatBoost (Prokhorenkova et al. 2018) encodes categorical features by ordered target statistics and uses ordered boosting: each row's gradient comes from a model that has not seen that row, removing a target leak ("prediction shift") that plain boosting has; its trees are oblivious (the same split at every node of a level). Its defaults are strong: on TabArena the default CatBoost is the best untuned tree model (section 4).

Same three splits, two growth orders: level-wise fills a depth, leaf-wise spends every split where the gain is largest. Numbers on nodes are the order of the splits; both trees end with four leaves.
1 2 3 depth 2, balanced

Level-wise (XGBoost's default grow_policy, depthwise, capped by max_depth = 6): every node of a level is split, even where the gain is small.

1 2 3 gain too small:left as a leaf depth 3, unbalanced

Leaf-wise (LightGBM, capped by num_leaves = 31 by default): lower loss for the same number of leaves, deeper trees, so it overfits small data sooner unless num_leaves or min_data_in_leaf are limited.

Defaults: XGBoost parameters (grow_policy, max_depth) and LightGBM parameters (num_leaves, max_bin 255). XGBoost's hist method can also grow loss-guided (leaf-wise). Schematic, not a fitted tree.

4 · Do boosted trees still win on tables?

Until 2024, yes, with a caveat about size; on the dated evidence it is now "on large tables and on CPUs, yes; on small and medium ones, no". The case for trees was made by Grinsztajn, Oyallon and Varoquaux (2022, 45 datasets of about 10K rows): neural networks are biased to overly smooth functions, are hurt by uninformative features, and are rotation-invariant while tabular features are not; each reason was tested. Then a transformer pretrained on millions of synthetic tables, TabPFN v2, reported beating tuned ensembles on up to 10,000 samples in one forward pass (Nature, January 2025), and the living TabArena leaderboard now ranks such foundation models first.

The four studies, quoted (2022 to 2025)
StudyDataFinding
Grinsztajn, Oyallon and Varoquaux, July 202245 datasets, "medium-sized data (~10K samples)", 20,000 compute hours of hyperparameter search per learner"Tree-based models remain state-of-the-art on medium-sized data (~10K samples) even without accounting for their superior speed." Three reasons, each tested: neural networks are biased to overly smooth functions, are hurt by uninformative features, and are rotation-invariant while tabular features are not.
McElfresh et al., May 2023 (NeurIPS 2023)19 algorithms, 176 datasetsThe "NN vs. GBDT" debate is overemphasised: on many datasets the gap is negligible, or light tuning of a boosted tree matters more than the choice of family. TabPFN (v1) was the best on average despite being limited to 3,000 training samples.
Hollmann et al. (TabPFN v2), Nature, 8 January 2025a transformer pretrained on millions of synthetic tables; predicts in one forward pass"Outperforms all previous methods on datasets with up to 10,000 samples by a wide margin"; "In 2.8 s, TabPFN outperforms an ensemble of the strongest baselines tuned for 4 h in a classification setting." reported by its authors
Erickson et al. (TabArena), June 2025, v4 November 202551 curated datasets, living leaderboard"While gradient-boosted trees are still strong contenders on practical tabular datasets, we observe that deep learning methods have caught up under larger time budgets with ensembling. At the same time, foundation models excel on smaller datasets."

The leaderboard on 2 October 2026 (TabArena v0.1.9.4), with the sibling benchmark BeyondArena (142 datasets, temporal and grouped splits as well as random ones, bucketed by training rows). Scores are Elo ratings from pairwise comparisons on each dataset's metric (ROC AUC, log-loss or RMSE), anchored so that a default random forest scores 1000 on TabArena; a gap of 400 means a 10 to 1 expected win rate; whiskers are bootstrap 95% intervals (TabArena leaderboard, CSV files read 3 October 2026). Pick a size bucket in the chart: boosted trees climb as the tables grow.

Correction to the old page
It said XGBoost, LightGBM and CatBoost "remain the strongest defaults on tabular data, still generally beating deep learning there (2026)". On TabArena's 51 datasets the top 15 entries are tabular foundation models, the best boosted tree (LightGBM, tuned and ensembled) is 20th with Elo 1430 against 1965 for the leader, and on BeyondArena's tiny, small and medium buckets the leaders are again foundation models. What survives: on BeyondArena's 22 tables of 100,001 to 1,000,000 rows, tuned and ensembled RealMLP (1321, a tuned MLP) leads, with LightGBM (1228), CatBoost (1207) and XGBoost (1196), all tuned and ensembled, inside overlapping intervals; boosted trees are the strongest family that runs on a CPU; and CatBoost's default trains in about 6 seconds per 1,000 rows with no GPU. Grinsztajn et al.'s 2022 conclusion was right for the models of 2022.

In practice: on a table of up to about 100,000 rows with a GPU and a licence that allows it, try a tabular foundation model first; it needs no tuning. Otherwise, and always as the baseline to beat, a boosted tree with early stopping (CatBoost's defaults, or LightGBM with a modest search). A random forest is the model that needs least care. Where the split is temporal or grouped, use BeyondArena's matching subset, not the random-split ranking.

How to read it, and its sources

Shown: the top 8 entries, the best entry of every family, and the default random forest for reference (TabArena anchors it at 1000; BeyondArena's scale is anchored separately, so its numbers are not comparable with TabArena's). "Tuned + ensembled" means 200 configurations tuned and the best ones ensembled under the same budget for every model; training times are medians per 1,000 rows, on GPU for foundation models. Models only; whole AutoML systems are ranked separately. Many of the newest foundation models (September 2026 entries) are described only by their leaderboard links here, and several carry non-commercial licences, flagged per row. The maintainers also develop some of the ranked models and say so on the site.

5 · Support vector machines, in brief

A support vector machine (Cortes and Vapnik 1995) looks for the separating hyperplane with the widest margin: the band, of width 2/||w|| between the lines where the score wTx + b equals ±1, that it keeps clear of training points. Real data are rarely separable, so the soft margin lets points into the band at a price set by C:

min ½||w||2 + C Σi max(0, 1 − yi(wTxi + b))   yi ∈ {−1, +1}
max(0, 1 − m)
the hinge loss on the margin m = y·f(x): zero once a point is beyond its side's margin line; compared with logistic and exponential losses on Loss functions ("One axis for every classification loss: the margin")
C
the inverse of the L2 penalty's strength: small C, wide margin and many violations; large C, every violation expensive

The solution depends only on the points on or inside the margin, the support vectors: in the dual every other point has weight αi = 0, and the score is f(x) = Σ αiyi K(xi, x) + b with 0 ≤ αi ≤ C. Because only dot products appear, the kernel trick swaps in a kernel K, a dot product in a feature space never built: the RBF kernel exp(−γ||x − x′||2) corresponds to an infinite-dimensional one, the polynomial kernel (xTx′ + c)d to all monomials up to degree d. γ sets how far one point's influence reaches; scikit-learn's default, "scale", is 1/(number of features × variance of X).

Fig. 3 draws the margin as C grows, without and with a kernel: 140 training points from two interleaved moons (60 more held out). The surface is the SVM's score f(x) as a height (capped at ±2.5); it crosses the floor along the decision line, f = 0. The glass plates are f = +1 and f = −1, so the dashed lines are the margin; every point rides at its own score, and the lit points are the support vectors.

  1. C = 0.01: the score as a tilted plane. A linear SVM's score wTx + b is a plane; the margin is where it runs between the plates, 2/||w|| wide. Violations are cheap, so the solver buys a gentle slope, a wide margin (3.12) and lets most points inside it: 110 of 140 are support vectors. The rest could be deleted without changing the answer.
  2. C = 0.1: violations cost more. The plane steepens and the margin narrows to 1.78; 66 points still sit inside it.
  3. C = 1, scikit-learn's default. Margin 1.29, 54 support vectors, 81.4% of training points right: the best straight line.
  4. C = 100: no C fixes the shape. Margin 1.24, training 82.1%, test 86.7%. The moons are not linearly separable, so a larger C only makes the plane steeper; the kernel, not C, fixes a wrong boundary shape.
Checked against scikit-learn, and the data

Defaults reproduce scikit-learn's SVC independently (recompute.py): linear kernel, C from 0.01 to 1: support vectors 110 → 54, margin width 3.12 → 1.29, training accuracy stuck at 81.4%; RBF kernel at C = 1: 55 support vectors, 93.6% training and 93.3% test accuracy. Decision values agree with libsvm to within 0.013 everywhere (both solvers stop at tolerance 10−3). Data: scikit-learn make_moons(200, noise = 0.25, random_state = 0), standardised.

Correction to the old page
It said SVMs scale poorly "past ~10^5 samples". For kernel SVMs the practical limit is lower: scikit-learn's SVC reference says the fit time "scales at least quadratically with the number of samples and may be impractical beyond tens of thousands of samples" (SVC). Linear SVMs have no such limit.

SVM scores are not probabilities: the hinge loss is minimised by the sign of the true class probability and nothing more (Bartlett et al., on Loss functions). They remain strong on small and medium data with many features, and are the most tuning-sensitive of six algorithms in Probst et al., so they need the search of section 10.

Cost, probabilities and the solver (scikit-learn and libsvm details)

The scikit-learn guide puts libsvm's training cost "between O(nfeatures × nsamples2) and O(nfeatures × nsamples3)", while the linear solver in LinearSVC "can scale almost linearly to millions of samples" (SVM user guide). scikit-learn's probability=True fits Platt scaling, "logistic regression on the SVM's scores, fit by an additional cross-validation on the training data", which is expensive and can disagree with the decision function (user guide, after Platt 1999). The page's SVM is the same solver family as libsvm: sequential minimal optimisation, which changes two αs at a time, with libsvm's second-order rule for choosing the pair (Fan, Chen and Lin 2005).

6 · Nearest neighbours

k nearest neighbours has no training step: it stores the training set and returns the majority class (or mean target) of the k closest points. k = 1 reproduces every training label (zero training error, a jagged boundary); a large k smooths towards the overall majority (both in the lab). Because everything rests on distances, feature scaling is mandatory: a feature measured in thousands swamps one measured in fractions (the same reason PCA needs standardising, section 9). A naive query compares against all n stored points, O(nd) per query; tree indexes help in a few dimensions and approximate nearest-neighbour indexes such as HNSW (Malkov and Yashunin 2016) in many. The same machinery, on learned embeddings, is vector retrieval (Topic: rag-and-retrieval).

In high dimensions, distances stop discriminating. Under broad conditions the ratio of the nearest to the farthest distance from a query tends to 1 as dimension grows (Beyer et al. 1999), so "nearest" stops meaning "similar". That is the curse of dimensionality for kNN; it bites least where the data lie near a low-dimensional surface, which is why kNN works on good embeddings.

Distance concentration: by 1,000 dimensions the nearest point is almost as far as the farthest. 500 points drawn uniformly in the unit cube of each dimension, 20 query points; the curve is the mean ratio of each query's nearest to its farthest distance. A seeded simulation illustrative, computed live.
Four clusterers on the same points: a bad start traps k-means, k-means++ escapes it, and only DBSCAN follows the moons. Start with k-means from a random start on six blobs (this start ends in a worse local minimum), then switch to k-means++, the mixture and DBSCAN, or to the real Old Faithful eruptions.

Checked against scikit-learn, and the data

. Lloyd's iterations from given centres reproduce scikit-learn's KMeans(init = centres, algorithm = "lloyd") to 10−15; the mixture reproduces GaussianMixture(covariance_type = "full", reg_covar = 10−6) from the same start after 1, 5 and 30 iterations to 10−15; DBSCAN's labels are identical to scikit-learn's on the moons and blobs (src/check/check_ml.mjs). Restart counts are computed live.

7 · Clustering

k-means alternates two steps: assign each point to its nearest centre, then move each centre to the mean of its points. Each step can only lower the inertia, so it always stops, but at a local minimum that depends on the start. k-means++ picks each new starting centre with probability proportional to its squared distance from the nearest centre already chosen; its expected inertia is within a factor O(log k) of the optimum before any iteration (Arthur and Vassilvitskii 2007). scikit-learn uses a greedy variant that tries 2 + ⌊ln k⌋ candidates per centre and keeps the best (KMeans); the page uses the plain rule. k-means assumes round clusters of similar size; the same card switches to the methods that do not.

The figure runs each method in four steps on the same points; switch the method on the card.

  1. Start: k random points as centres. Lloyd's algorithm needs starting centres; here they are k data points picked uniformly at random. Bad luck here (two centres in one cluster) is never undone, only refined.
  2. Iteration 1: assign, then move. Each point joins its nearest centre (colour), then each centre moves to the mean of its points (dashed path). Both steps can only lower the inertia, so the loop always stops.
  3. Keep iterating. The same two steps repeat (played through here); the centres move less each time.
  4. Converged. No point changed cluster, so the centres stopped: a local minimum of the inertia. Whether it is the best one depends on the start: the 100 restarts under the figure.
The four clusterers side by side (k-means, hierarchical, DBSCAN, Gaussian mixtures)
MethodOne-linerWatch out
k-meansalternate: assign each point to its nearest centre, move each centre to the mean of its points; minimises the within-cluster sum of squares (inertia)you choose k (elbow or silhouette); assumes round clusters of similar size; depends on the start (use k-means++ and several restarts)
Hierarchical (agglomerative)start with every point alone and repeatedly merge the two closest clusters by a linkage: single (closest pair), complete (farthest pair), average, or Ward (smallest increase in variance); cut the dendrogram at the level you wantthe pairwise distances alone take O(n2) memory and the classic algorithm O(n3) time (O(n2) for single linkage, Sibson 1973); the linkage changes the answer
DBSCANdensity: points with at least minPts neighbours within eps are core points; clusters are what core points reach; the rest is noise (Ester et al. 1996)finds any shape and needs no k, but one eps must suit every cluster's density
Gaussian mixture + EMsoft clustering: each cluster a Gaussian with its own weight, mean and covariance; EM alternates responsibilities (E) and parameter updates (M) (Dempster, Laird and Rubin 1977)local optima; k still chosen (BIC helps); covariances can collapse onto a single point without regularisation
An isolated eruption is fenced off in a handful of random cuts; one in the dense cluster takes many. 272 real Old Faithful eruptions (eruption length against waiting time, both standardised). Each split takes a random feature and a random cut between the box's smallest and largest point; orange follows the box holding A, blue the box holding B.

Seeded and computed live illustrative. The drawn tree uses all 272 eruptions and grows until each point is alone; the score uses 100 trees on random samples of 256 rows, Liu et al.'s defaults, and adds c(m) for a leaf still holding m > 1 identical points (16 eruptions repeat exactly). Data: datasets::faithful.

8 · Anomaly detection

Anomalies are rare, so this is usually unsupervised: model what normal looks like and flag what does not fit. Isolation forest (Liu, Ting and Zhou 2008) inverts the usual question: instead of measuring how far a point is from the rest, it counts how many random cuts it takes to fence the point off alone. A point that is few and different is isolated in few cuts.

  1. Start: every eruption in one box. A (5.1 min eruption, 96 min wait) and B (4.3 min eruption, 82 min wait) are the eruptions the forest scores most and least anomalous. Each split picks one of the two features at random and cuts at a random value between the box's smallest and largest point.
  2. Split 1. We follow the side of every cut that holds A (orange) and the side that holds B (blue).
  3. A is alone after 3 splits. Random cuts land in empty space far more often near a point that is few and different, so its box empties fast.
  4. B's box keeps shrinking. In the dense cluster each cut removes only some of B's neighbours.
  5. B is alone after 19 splits. The cuts since the last step are played through.
  6. Over 100 trees: the score. Averaged over 100 trees on samples of 256: E[h(A)] = 4.7 and E[h(B)] = 14.3, against c(256) = 10.24, so s(A) = 0.73, above 0.5, and s(B) = 0.38, well below it.
s(x) = 2−E[h(x)] / c(n)   c(n) = 2H(n − 1) − 2(n − 1)/n
h(x)
the number of cuts to isolate x, averaged over the trees
c(n)
the average path length of an unsuccessful search in a binary search tree of n points (H the harmonic number, about ln i + 0.5772): 10.24 for n = 256. s near 1 is anomalous, well below 0.5 normal

It needs no distances, so it scales to large, high-dimensional data. Evaluate with precision and recall, not accuracy or ROC alone: with 1 anomaly in 1,000, "nothing is anomalous" is 99.9% accurate, and a small false positive rate still swamps the true alarms (the threshold lab on Evaluation metrics shows this on real scores with rare positives).

The other detectors (one-class SVM, density and reconstruction thresholds, LOF)

The alternatives model normal directly: a one-class SVM (Schölkopf et al. 2001) separates the data from the origin in kernel space with a fraction ν of outliers allowed; density and reconstruction thresholds flag low likelihood under a fitted density (a Gaussian mixture, section 7) or a large reconstruction error from PCA or an autoencoder (section 9); the local outlier factor compares a point's local density with its neighbours' (Breunig et al. 2000).

9 · Fewer dimensions: PCA, t-SNE, UMAP

PCA finds the orthogonal directions of greatest variance: the eigenvectors of the covariance matrix, ordered by eigenvalue, equivalently the right singular vectors of the centred data matrix (scikit-learn computes it by SVD; the projection and the SVD are on Linear algebra for ML). Projecting on the first m keeps the most variance any m-dimensional linear projection can, and the eigenvalue shares are the "explained variance".

Fig. 4 runs it on three real measurements of 178 wines (flavanoids, total phenols and OD280/OD315, the three that weigh most in the first component of all 13, each standardised); the colours are the three cultivars.

  1. The cloud. The three measurements rise and fall together (correlations 0.70 to 0.86), so the cloud is a tilted cigar, not a ball.
  2. PC1: the direction of greatest spread. The eigenvector of the covariance matrix with the largest eigenvalue, drawn three standard deviations each way. Projecting on it keeps 85.7% of the variance, more than any other single direction can.
  3. PC2: the most of what is left. Orthogonal to PC1, 10.3%. The glass plate spanned by PC1 and PC2 is the plane that fits the cloud best.
  4. PC3: what the plane misses. 4.0%, the short arrow: how thick the cloud is across the plane.
  5. Turn the cloud onto its components. PCA is a rotation: multiplying each standardised wine by the matrix whose rows are the components turns PC1, PC2 and PC3 into the axes. Nothing is lost yet; every distance is unchanged.
  6. Drop PC3. Each wine falls onto the plane; seen from above it is the usual 2-D PCA picture, keeping 96.0% of the variance. Dropping the last components is the whole reduction.

Scale decides what PCA finds

It is linear, and it is not scale-invariant: on raw data the feature with the largest numbers wins. Predict: on 13 wine measurements, how much variance does the first component of the raw data explain?

The same 178 wines, raw and standardised: scaling decides what PCA finds. 13 chemical measurements of wines from three cultivars (colours). Left: share of variance per component, with the cumulative line; right: every wine projected on the first two components (each axis scaled to unit spread for display).

Defaults reproduce scikit-learn's PCA independently: raw, PC1 explains 99.81%, almost all of it proline (variance 98,610 against 203 for magnesium and under 12 for the other eleven); standardised, PC1 36.2% and PC2 19.2%, and the three cultivars separate. Explained-variance ratios agree to 10−15 (src/check). Data: UCI Wine via scikit-learn's load_wine.

t-SNE (van der Maaten and Hinton 2008) and UMAP (McInnes, Healy and Melville 2018) are nonlinear embeddings for pictures: they keep each point's neighbours close and give up on everything else. In their plots, cluster sizes and the distances between clusters mean little, and a perplexity or neighbour count changes the picture (Wattenberg, Viégas and Johnson 2016, with live examples). Use them to look, never as features for a model or as evidence of cluster structure on their own. Autoencoders are the nonlinear, learned version of PCA: a network squeezed through a narrow layer and trained to reconstruct its input (a linear autoencoder with squared error learns the same subspace as PCA).

Correction to the old page
It said UMAP "is faster and preserves more global structure". Faster, usually, yes. But the better global structure was traced to initialisation: UMAP starts from a spectral embedding and t-SNE implementations from a random one; with the same informative initialisation, t-SNE preserves global structure as well as UMAP, and UMAP from a random start loses it (Kobak and Linderman 2021, "Initialization is critical for preserving global data structure in both t-SNE and UMAP").

10 · Hyperparameter search

MethodIdeaWhen
Grid searchevery combination of a few values per hyperparameterone or two hyperparameters, cheap models
Random searchsample configurations at random from the rangesusually beats grid at equal budget, because the few hyperparameters that matter get many distinct values instead of few (Bergstra and Bengio 2012)
Bayesian optimisationfit a surrogate of score against configuration (a Gaussian process, Snoek, Larochelle and Adams 2012, or a tree-structured Parzen estimator, Bergstra et al. 2011) and choose the next trial by expected improvementexpensive trials; Optuna (Akiba et al. 2019) and Hyperopt default to TPE
Successive halving, Hyperband, ASHAstart many configurations on a small budget, keep the best fraction, give survivors more (Jamieson and Talwalkar 2016; Hyperband runs several such brackets, Li et al. 2018; ASHA promotes asynchronously across many workers, Li et al. 2020)deep learning and boosting, where a partly trained run already says something

Bergstra and Bengio's argument is geometric. With 9 trials on a 3 × 3 grid, each hyperparameter gets only 3 distinct values; 9 random trials give 9 of each. When only some hyperparameters matter, which they found to be the usual case, a grid wastes most trials on the ones that do not. Random search also has a budget rule that needs no knowledge of the surface: with n independent trials, the chance that at least one lands in the best 5% of the space is 1 − 0.95n, which passes 95% at n = 60 (1 − 0.9560 = 0.954) derived.

On this surface every method ends within the cross-validation noise of the best cell; searching harder than that noise only fits the validation folds (Cawley and Talbot 2010): report a held-out score, or nest the search inside an outer cross-validation.

What the surface shows, honestly (grid luck, idle hyperparameters, Bayesian optimisation)

Here both hyperparameters matter about equally (each explains about 35% of the variance of accuracy across the box, recompute.py), so Bergstra and Bengio's low-effective-dimension case does not hold, and a 2-D grid is not reliably worse: a 4 × 4 grid happens to land on 99.00%, a 5 × 5 grid only on 98.83%, which is luck of alignment. Add hyperparameters that do nothing (a cache size, a tolerance far below the noise) and the grid collapses: 27 trials on a 3 × 3 × 3 grid test only 9 distinct (C, gamma) pairs and reach 98.39%, while random search with the same 27 trials always gets 27 distinct pairs. Bayesian optimisation reaches the ridge in fewer trials on median.

Three searches on a real response surface: all reach the bright ridge; the grid collapses once idle hyperparameters are added. The colour is the measured 5-fold cross-validated accuracy of an RBF SVM on scikit-learn's 1,797 handwritten digits, at every one of 41 × 37 settings of C and gamma on the libsvm guide's recommended ranges (C from 2−5 to 215, gamma from 2−15 to 23; Hsu, Chang and Lin). A trial reads one cell. Orange dots are trials, the ring the latest, the blue square the best so far.

Checked against scikit-learn, and the data

The surface was computed offline with scikit-learn (src/data/svm_surface.py, 1,517 settings × 5 folds): best 99.11% at C = 2, gamma = 2−3; 20.9% of the box reaches 98.5%. Bayesian optimisation is this page's own: a Gaussian process with a squared-exponential kernel (length-scale 0.15 on the unit square, fixed, not fitted), standardised scores, expected improvement with ξ = 0.01, 3 random starting trials; its paths match a NumPy re-implementation step for step (recompute.py, src/check). Real searches would not see the surface in advance; here it is precomputed so every method reads the same numbers.

Common mistakes

Most of this page's mistakes are shown where they happen (a tree without a depth limit, boosting without early stopping, one k-means start, reading clusters off t-SNE). Three are not:

Scaling, imputing or selecting features on the whole dataset before splitting
The test fold then leaks into training statistics. Fit every preprocessing step inside the cross-validation loop (a scikit-learn Pipeline does this). Trees need no scaling; kNN, SVMs, k-means, PCA and penalised linear models do.
Reading SVM scores, naive Bayes or boosted-tree outputs as calibrated probabilities
SVM scores carry only the decision; naive Bayes double-counts correlated evidence; boosted trees drift with the number of stages. Calibrate on held-out data (Platt or isotonic) when the probability is used.
Assuming "boosted trees always win on tables" (or the opposite) from a single benchmark
The answer depends on table size, the split (random, temporal, grouped), the tuning budget and the hardware; check the matching subset of a maintained benchmark, with its date (section 4). Use several restarts with k-means++ (scikit-learn's n_init) for the same reason one benchmark is not enough: one run is one draw.