AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·148

Classical Machine Learning

The algorithms that still win on tabular data and the ideas every deep model inherits: the supervised learning setup and train/validation/test splits, linear regression from normal equations and gradient descent, logistic regression and the sigmoid, regularisation (ridge, lasso, elastic net), the bias-variance trade-off with under- and overfitting, k-nearest neighbours and the curse of dimensionality, Naive Bayes for text, decision trees with Gini and entropy splits, random forests and bagging, gradient boosting from residuals up to XGBoost, LightGBM and CatBoost, support vector machines with margins and kernels, k-means, DBSCAN and hierarchical clustering, PCA in practice, cross-validation, feature engineering and scikit-learn pipelines, with from-scratch implementations and equivalents in R, Julia, Rust, Go, Java and C++.

32 topics · ~30 min read · 34-question quiz
Updated Suggest a correction

Start here: the algorithms that still win on tables

Most business data is tabular: rows (orders, customers, patients) and columns (features). On tables, classical machine learning, meaning linear models, nearest neighbours, support vector machines, decision trees and especially ensembles of trees, is fast, strong and often better than deep learning. Every model also teaches an idea deep learning inherits: losses, regularisation, kernels, ensembling.

Always beat a baseline, and always cross-validate

Breast-cancer diagnosis (569 patients, 30 measurements), scored with 5-fold cross-validation: train on four fifths, test on the fifth, rotate, and report the mean and spread:

Text
majority class (always predict "benign")   62.7%
logistic regression, unscaled              95.6% ± 1.6
logistic regression + scaling              97.9% ± 1.4
k-NN unscaled                              93.2% ± 1.9
k-NN + scaling                             96.5% ± 2.1
SVM (RBF kernel) + scaling                 97.7% ± 0.7
decision tree                              92.6% ± 2.2
random forest                              95.8% ± 1.7
XGBoost (gradient-boosted trees)           97.7% ± 0.9

Three lessons. The baseline says 62.7% is free, so "95% accurate" means less than it sounds. Scaling features (to mean 0, spread 1) helped every distance- or gradient-based model, because the raw features ranged from fractions to thousands; trees don't care about scale. And the top four are within each other's error bars: on 569 rows you can't honestly crown a winner, so pick the simplest model that's as good (here, scaled logistic regression).

Regularisation: keeping models from overreacting

Logistic regression with different penalty strengths (C = 1/λ; small C means a strong penalty on large weights):

Text
C = 0.001   CV 89.1%   total |weights| 1.6     (too constrained: underfits)
C = 0.1     CV 97.5%   total |weights| 9.3
C = 1       CV 97.9%   total |weights| 18.2    (best)
C = 1000    CV 95.3%   total |weights| 186.9   (barely constrained: overfits)

The penalty trades fit for simplicity. Too strong and the model can't express the pattern; too weak and it fits noise with huge weights. Choosing it by cross-validation is the standard practice, and the same idea reappears as weight decay in neural networks.

Not every problem is that predictable

Diabetes progression (442 patients, 10 measurements), regression scored by R² (1 = perfect, 0 = no better than predicting the mean):

Text
linear regression  R² 0.489 ± 0.090
ridge (α = 1)      R² 0.420 ± 0.051
random forest      R² 0.427 ± 0.100
XGBoost            R² 0.438 ± 0.113

Every model explained under half the variation, and plain linear regression did as well as anything. With 442 rows and 10 noisy measurements, the data, not the algorithm, set the limit.

How deep to go in classical machine learning

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Name the main algorithms and the problems they fit
L2 Build scikit-learn pipelines with preprocessing, cross-validation and a baseline
L3 Explain linear models, regularisation, kernels, trees, bagging and boosting from their losses
L4 Diagnose leakage, scaling mistakes, overfitting and tuning errors; read error bars honestly
L5 Choose models and features for a tabular product problem with cost and interpretability in mind
L6 Run tabular ML at scale with feature stores, retraining and monitoring

The supervised learning setup

We have examples (xᵢ, yᵢ) drawn from an unknown distribution. We choose a model family (lines, trees, networks), a loss measuring prediction error, and an optimisation procedure that picks the member of the family with low loss on the training data. The real goal is low loss on new data from the same distribution: generalisation.

  • Regression: y is a number (price, demand, latency).
  • Classification: y is a category (spam/not, digit 0–9); binary, multi-class or multi-label.
  • Features (x): the numeric representation of each example; for tabular data, columns; for text and images, engineered or learned representations.

Train, validation, test

train (≈70%): fit parameters validation test learn weights, tree splits tune hyperparamsearly stopping final score,used once split by time / user / group when examples are related (chapter 150)
Splitting data three ways. The model learns parameters on the training set; hyperparameters and model choices are compared on the validation set (or with cross-validation on the training set); the test set is used once, at the end, to estimate performance on unseen data. Looking at the test set during development leaks information and makes the final estimate optimistic.
  • Parameters are learned (weights, split thresholds). Hyperparameters are chosen by you (learning rate, tree depth, k, regularisation strength).
  • Split before any preprocessing that learns from data (scaling, imputation, encoding) and fit those transforms on the training set only; otherwise statistics of the validation/test set leak in. Pipelines (below) enforce this.
  • For time series, split by time (train on the past, test on the future). For users, patients or sessions, split by group so the same entity isn't on both sides.

Linear regression

Model and loss

ŷ = w · x + b = Σⱼ wⱼxⱼ + b. Loss: mean squared error MSE = (1/n) Σ (yᵢ − ŷᵢ)², which is Gaussian maximum likelihood (chapter 147).

Closed form: normal equations

Stack inputs into a design matrix X (n × d, with a column of ones for b). Minimising ‖Xw − y‖² by setting the gradient 2Xᵀ(Xw − y) to zero gives:

XᵀX w = Xᵀy → w = (XᵀX)⁻¹Xᵀy

Geometrically this is the projection of y onto the column space of X (chapter 145). In practice solve with QR or SVD (np.linalg.lstsq), never by inverting XᵀX (ill-conditioned when features are correlated). Cost O(nd² + d³): fine for thousands of features; for millions, use gradient descent.

Gradient descent

∇_w MSE = (2/n) Xᵀ(Xw − y). Iterate w ← w − η∇. Features on very different scales make the loss surface elongated (chapter 146's zig-zag), so standardise features first.

Python
import numpy as np
rng = np.random.default_rng(0)
n = 200
X = rng.normal(size=(n, 2))
y = 3.0 * X[:, 0] - 2.0 * X[:, 1] + 5.0 + rng.normal(scale=0.5, size=n)

Xb = np.c_[np.ones(n), X]                           # add bias column
w_closed, *_ = np.linalg.lstsq(Xb, y, rcond=None)   # ≈ [5.0, 3.0, -2.0]

w = np.zeros(3)
for _ in range(500):
    grad = (2 / n) * Xb.T @ (Xb @ w - y)
    w -= 0.1 * grad
np.allclose(w, w_closed, atol=1e-3)                 # True: both reach the same solution

Assumptions behind the classic statistical interpretation (for confidence intervals on coefficients): linear relationship, independent errors, constant error variance, no perfect collinearity. For prediction alone, linearity in features is what matters, and features can be nonlinear transforms (polynomials, logs, splines, interactions): "linear" means linear in the parameters.

Logistic regression

From linear scores to probabilities

For binary classification, squash a linear score into (0, 1) with the sigmoid: p = σ(w · x + b) = 1/(1 + e^−(w·x+b)). The score z = w · x + b is the log-odds (logit): log(p/(1 − p)) = z, so each coefficient wⱼ is the change in log-odds per unit of xⱼ.

  • Decision boundary: p = 0.5 ⇔ z = 0: a hyperplane. Logistic regression is a linear classifier.
  • Loss: binary cross-entropy (log loss), the Bernoulli negative log-likelihood. Convex, so gradient descent finds the global optimum. Gradient: (1/n) Xᵀ(p − y): the same shape as linear regression's.
  • Multi-class: softmax regression (multinomial logistic) with one weight vector per class and categorical cross-entropy: literally the final layer of every neural classifier and of every LLM (over a vocabulary).
  • The threshold 0.5 isn't sacred: choose it from costs of false positives vs false negatives (chapter 149).
Python
def sigmoid(z): return 1 / (1 + np.exp(-z))

def fit_logreg(X, y, lr=0.1, steps=2000, l2=0.0):
    Xb = np.c_[np.ones(len(X)), X]
    w = np.zeros(Xb.shape[1])
    for _ in range(steps):
        p = sigmoid(Xb @ w)
        grad = Xb.T @ (p - y) / len(y) + l2 * np.r_[0, w[1:]]   # don't regularise the bias
        w -= lr * grad
    return w

X = rng.normal(size=(500, 2))
y = (X[:, 0] + 2 * X[:, 1] + 0.3 * rng.normal(size=500) > 0).astype(float)
w = fit_logreg(X, y)
pred = sigmoid(np.c_[np.ones(500), X] @ w) > 0.5
(pred == y).mean()                     # ≈ 0.95; w[2]/w[1] ≈ 2, matching the true boundary

Regularisation

Models with many parameters can fit noise. Regularisation adds a penalty that prefers simpler solutions:

Method Penalty added to loss Effect Bayesian view
Ridge (L2) λ Σ wⱼ² Shrinks all weights smoothly; stabilises correlated features; closed form w = (XᵀX + λI)⁻¹Xᵀy Gaussian prior
Lasso (L1) λ Σ |wⱼ| Drives some weights exactly to 0: feature selection Laplace prior
Elastic net Mix of L1 and L2 Selection that's stable with correlated features —
w₁w₂ L2: contact off-axis w₁w₂ L1: contact at corner, w₁ = 0
Why L1 gives sparse solutions and L2 does not. The ellipses are contours of the data loss around its unconstrained minimum; the shaded shape is the set of weights within the penalty budget. The L2 ball is round, so the first contact point is generally off the axes and both weights stay non-zero. The L1 diamond has corners on the axes, so contact usually happens at a corner, setting one weight exactly to zero.

Other regularisers: early stopping, fewer features, tree depth limits, dropout and weight decay in networks (chapter 151), data augmentation, and simply more data.

Bias, variance, under- and overfitting

  • Underfitting (high bias): the model is too simple to capture the pattern; training error and validation error are both high. Fix: richer model, better features, less regularisation.
  • Overfitting (high variance): the model memorises training noise; training error is low but validation error is high. Fix: more data, regularisation, simpler model, ensembling, augmentation.
  • The expected squared error of a predictor decomposes as bias² + variance + irreducible noise.
model complexity →error train validation sweet spot underfithigh bias overfit: high variance
Underfitting and overfitting as model complexity grows. Training error keeps falling as the model becomes more flexible, while validation error first falls and then rises once the model starts fitting noise. The sweet spot is where validation error is lowest. Very large modern networks can show a second descent beyond the interpolation point, but the classic picture still guides model selection.

Learning curves (error vs training-set size) diagnose which problem you have: if train and validation errors converge at a high value, more data won't help (bias); if a large gap remains, more data will (variance).

k-nearest neighbours

The simplest learner: store the training set; to predict, find the k closest training points (Euclidean, cosine, Manhattan distance) and take a majority vote (classification) or average (regression).

  • Non-parametric and lazy: no training, all cost at prediction time O(nd) per query unless an index is used (KD-trees, ball trees; approximate nearest-neighbour indexes like HNSW for large/high-dimensional data: chapter 160).
  • k small → jagged boundaries, high variance; k large → smooth, high bias.
  • Scale features: distance is dominated by the largest-scale feature otherwise.
  • Curse of dimensionality: in high dimensions, distances between random points concentrate (everything is roughly equally far), so "nearest" loses meaning unless the data lies on a lower-dimensional structure. This is why we learn embeddings where distance means similarity, and k-NN over embeddings is the retrieval step of RAG (chapter 161).
Python
def knn_predict(X_train, y_train, X_query, k=5):
    d = ((X_query[:, None, :] - X_train[None, :, :]) ** 2).sum(-1)   # pairwise squared distances
    idx = np.argpartition(d, k, axis=1)[:, :k]                       # k nearest, unsorted
    return np.array([np.bincount(y_train[i].astype(int)).argmax() for i in idx])

Naive Bayes

Apply Bayes' theorem with the "naive" assumption that features are conditionally independent given the class (chapter 147):

P(c | x) ∝ P(c) Πⱼ P(xⱼ | c)

  • Multinomial NB for word counts, Bernoulli NB for word presence, Gaussian NB for continuous features.
  • Work in log space (sum of logs) and use Laplace (add-one) smoothing so an unseen word doesn't zero out a class.
  • Extremely fast to train (counting), works with little data, strong baseline for text classification (spam filters). Probabilities are poorly calibrated because the independence assumption double-counts correlated evidence.
Python
from collections import Counter
import math

train = [("win cash prize now", "spam"), ("cheap prize claim now", "spam"),
         ("meeting at noon", "ham"), ("lunch at noon tomorrow", "ham")]
vocab = {w for t, _ in train for w in t.split()}
classes = {c for _, c in train}
prior = {c: sum(1 for _, k in train if k == c) / len(train) for c in classes}
counts = {c: Counter(w for t, k in train if k == c for w in t.split()) for c in classes}
total = {c: sum(counts[c].values()) for c in classes}

def predict(text):
    scores = {}
    for c in classes:
        s = math.log(prior[c])
        for w in text.split():
            s += math.log((counts[c][w] + 1) / (total[c] + len(vocab)))   # Laplace smoothing
        scores[c] = s
    return max(scores, key=scores.get)

predict("claim your cash prize"), predict("noon meeting tomorrow")   # ('spam', 'ham')

Decision trees

A tree asks a sequence of yes/no questions about features ("income > 50k?") and predicts at the leaves. Trees are learned greedily: at each node, try every feature and threshold, pick the split that most reduces impurity, recurse.

  • Gini impurity: G = 1 − Σₖ pₖ². Entropy: H = −Σₖ pₖ log₂ pₖ. Pure node → 0. Information gain = parent impurity − weighted child impurity.
  • Regression trees minimise variance (MSE) in the children; leaves predict the mean.
  • Stop by max depth, min samples per leaf, or min gain; or grow fully and prune (cost-complexity pruning).
income > 50k? years employed > 5? debt ratio < 0.4? no yes approve64% of 120 reject85% of 310 approve92% of 400 reject70% of 170 yesnoyesno
A small decision tree for loan approval. Each internal node tests one feature against a threshold; each leaf predicts the majority class of the training examples that reach it. The tree carves the feature space into axis-aligned rectangles, which is why single trees are interpretable but have jagged boundaries and high variance.
Python
def gini(y):
    _, c = np.unique(y, return_counts=True); p = c / c.sum()
    return 1 - np.sum(p ** 2)

def best_split(X, y):
    best = (None, None, gini(y))                     # feature, threshold, impurity
    for j in range(X.shape[1]):
        for t in np.unique(X[:, j]):
            left = X[:, j] <= t
            if left.all() or (~left).all(): continue
            imp = left.mean() * gini(y[left]) + (~left).mean() * gini(y[~left])
            if imp < best[2]: best = (j, t, imp)
    return best

def build(X, y, depth=0, max_depth=3, min_leaf=5):
    j, t, imp = best_split(X, y)
    if depth == max_depth or j is None or len(y) < 2 * min_leaf:
        return {"leaf": np.bincount(y.astype(int)).argmax()}
    m = X[:, j] <= t
    return {"f": j, "t": t, "l": build(X[m], y[m], depth + 1, max_depth, min_leaf),
            "r": build(X[~m], y[~m], depth + 1, max_depth, min_leaf)}

def predict_one(node, x):
    while "leaf" not in node:
        node = node["l"] if x[node["f"]] <= node["t"] else node["r"]
    return node["leaf"]

Strengths: handle mixed feature types, no scaling needed, capture interactions and nonlinearity, interpretable when small. Weakness: a single tree is unstable (high variance): small data changes give a different tree. Ensembles fix that.

Ensembles: random forests

Bagging (bootstrap aggregating): train many models on bootstrap resamples and average them. Averaging B models with variance σ² and pairwise correlation ρ gives variance ρσ² + (1 − ρ)σ²/B: averaging reduces variance, more so when models are decorrelated.

Random forests (Leo Breiman, 2001) decorrelate trees further by considering only a random subset of features at each split (√d for classification is a common default).

  • Robust defaults, little tuning, hard to overfit by adding trees.
  • Out-of-bag (OOB) error: each tree didn't see about 37% of examples; evaluating on those gives a free validation estimate.
  • Feature importance: impurity decrease (biased toward high-cardinality features) or permutation importance (shuffle a feature, measure the drop: more reliable). SHAP values give per-prediction attributions.

Ensembles: gradient boosting

Boosting builds models sequentially, each correcting the previous ensemble's errors.

Gradient boosting (Jerome Friedman, 2001): start with a constant prediction; repeatedly fit a small tree to the negative gradient of the loss with respect to the current predictions (for MSE, simply the residuals), and add it scaled by a learning rate (shrinkage):

F_m(x) = F_{m−1}(x) + η · h_m(x), h_m fitted to −∂L/∂F_{m−1}

It is gradient descent in function space.

F₀ = mean residualsy − F₀ tree h₁ F₁ = F₀ + ηh₁ … F_M repeat: fit next tree to new residuals each tree is weak (depth 3–8); the sum is strong η = 0.01–0.3 · stop when validation loss stops improving
Gradient boosting as successive residual fitting. The first model predicts the mean; each new shallow tree is trained on what the ensemble still gets wrong, and its scaled prediction is added. Training error falls steadily; the learning rate and the number of trees, chosen with early stopping on validation data, control overfitting.
Python
from sklearn.tree import DecisionTreeRegressor

def gbm_fit(X, y, n_trees=100, lr=0.1, depth=3):
    f0 = y.mean(); pred = np.full(len(y), f0); trees = []
    for _ in range(n_trees):
        residual = y - pred                       # negative gradient of ½(y − F)²
        t = DecisionTreeRegressor(max_depth=depth).fit(X, residual)
        pred += lr * t.predict(X); trees.append(t)
    return f0, trees

def gbm_predict(model, X, lr=0.1):
    f0, trees = model
    return f0 + lr * sum(t.predict(X) for t in trees)

Xr = rng.uniform(-3, 3, size=(400, 1)); yr = np.sin(Xr[:, 0]) * 2 + rng.normal(scale=0.2, size=400)
m = gbm_fit(Xr, yr)
np.sqrt(np.mean((gbm_predict(m, Xr) - yr) ** 2))     # training RMSE ≈ 0.15: slightly below the 0.2 noise, so it is starting to fit noise

Production libraries add a lot:

Library Distinctive features
XGBoost (Tianqi Chen, 2014) Second-order (Newton) steps using gradient and Hessian, explicit regularisation on leaf weights, sparsity-aware splits for missing values, histogram method, GPU training
LightGBM (Microsoft) Leaf-wise growth, histogram binning, gradient-based one-side sampling: very fast on large data
CatBoost (Yandex) Ordered target statistics for categorical features without leakage, symmetric trees, strong defaults
scikit-learn HistGradientBoosting LightGBM-style, built in, native missing-value and categorical support

Key hyperparameters: number of trees with early stopping, learning rate, max depth / leaves, min child weight, row and column subsampling, L1/L2 on leaves.

Support vector machines

An SVM finds the separating hyperplane with the maximum margin: the largest distance to the nearest training points of either class (the support vectors). Only those points determine the boundary.

  • Hard margin: minimise ‖w‖² subject to yᵢ(w · xᵢ + b) ≥ 1 (a constrained problem solved via Lagrange multipliers/KKT, chapter 146).
  • Soft margin: allow violations with slack, penalty C. Equivalent to minimising hinge loss max(0, 1 − y·f(x)) + λ‖w‖². Large C → fit training data tightly; small C → wider margin, more regularisation.
  • Kernel trick: the dual formulation only uses dot products xᵢ · xⱼ; replace them with a kernel k(xᵢ, xⱼ) = φ(xᵢ) · φ(xⱼ) to get a linear separator in a (possibly infinite-dimensional) feature space without computing φ. RBF kernel exp(−γ‖x − x′‖²), polynomial kernels.
  • Cost: kernel SVMs scale roughly O(n²)–O(n³) in examples: great for small/medium data, impractical for millions (linear SVMs scale fine).
2/‖w‖ — boundary- - marginsbold: supportvectors
A maximum-margin classifier. The solid line separates the two classes; the dashed lines mark the margin on each side. Points lying on the margin are the support vectors, and only they determine the boundary. A kernel lets the same idea draw curved boundaries by separating linearly in a transformed feature space.

Unsupervised learning: clustering

k-means

Partition data into k clusters minimising within-cluster squared distance (inertia).

  1. Initialise k centroids (k-means++: spread them out probabilistically, far better than random).
  2. Assign each point to the nearest centroid.
  3. Move each centroid to the mean of its points.
  4. Repeat until assignments stop changing.

Converges to a local optimum (run several initialisations). Assumes roughly spherical, similar-size clusters; sensitive to scale and outliers. Choose k with the elbow of inertia vs k or the silhouette score.

Python
def kmeans(X, k, iters=100, seed=0):
    r = np.random.default_rng(seed)
    C = X[r.choice(len(X), 1)]                                   # k-means++ initialisation
    while len(C) < k:
        d2 = ((X[:, None] - C[None]) ** 2).sum(-1).min(1)
        C = np.vstack([C, X[r.choice(len(X), p=d2 / d2.sum())]])
    for _ in range(iters):
        labels = ((X[:, None] - C[None]) ** 2).sum(-1).argmin(1)
        newC = np.array([X[labels == j].mean(0) for j in range(k)])
        if np.allclose(newC, C): break
        C = newC
    return C, labels

centres = np.array([[0, 0], [5, 5], [0, 6]])
Xc = np.vstack([c + rng.normal(scale=0.7, size=(100, 2)) for c in centres])
def inertia(X, C, labels): return ((X - C[labels]) ** 2).sum()
runs = [kmeans(Xc, 3, seed=s) for s in range(10)]             # several restarts, keep the best
C, labels = min(runs, key=lambda r: inertia(Xc, *r))
np.round(C[np.argsort(C[:, 0] + C[:, 1])], 1)                   # ≈ the three true centres

Other clustering methods

Method Idea When
Hierarchical (agglomerative) Repeatedly merge the closest clusters; a dendrogram shows all levels Small data, unknown k, nested structure
DBSCAN / HDBSCAN Dense regions are clusters; sparse points are noise Arbitrary shapes, outliers, unknown k
Gaussian mixture models Soft assignments; each cluster a Gaussian, fitted by expectation-maximisation Overlapping, elliptical clusters; probabilities
Spectral clustering Cluster eigenvectors of a similarity graph Non-convex shapes

Clustering embeddings (chapter 159) is a common way to explore text corpora, deduplicate data and discover topics.

Dimensionality reduction

PCA (derived in chapter 145) projects onto directions of maximum variance: for compression, visualisation, denoising and decorrelating features. t-SNE and UMAP are nonlinear methods for 2-D visualisation of embeddings; they preserve local neighbourhoods but distort global distances and cluster sizes, so don't read too much into them.

Cross-validation

A single validation split is noisy, especially with little data. k-fold cross-validation splits the training data into k folds, trains k times each holding out one fold, and averages the scores.

  • Stratified k-fold keeps class proportions in each fold.
  • Group k-fold keeps all examples from one group (user, patient) in the same fold.
  • Time-series split: expanding window, always training on the past.
  • Nested CV: an inner loop tunes hyperparameters, an outer loop estimates performance of the whole procedure, avoiding optimistic bias from tuning on the evaluation folds.
score₁ 0.86score₂ 0.84score₃ 0.88score₄ 0.85score₅ 0.87 green = validation fold · mean 0.86 ± 0.014
Five-fold cross-validation. The training data is split into five folds; in each round a different fold is held out for validation and the model is trained on the remaining four. The five validation scores are averaged, and their spread indicates how stable the estimate is.

Feature engineering

For classical models, features matter more than algorithms.

Data Techniques
Numeric Standardise (z-score) or min-max for distance/gradient models; log or Box-Cox for skewed values; binning; clipping outliers; ratios and differences (debt/income)
Categorical One-hot (low cardinality); ordinal codes for trees; target encoding with out-of-fold statistics (else leakage); hashing for huge vocabularies; learned embeddings
Missing values Impute (median, mode, model-based) plus an "is missing" indicator, since missingness is often informative; GBDTs handle NaN natively
Dates/times Day of week, hour, holiday flags, time since event, cyclical sin/cos encoding
Text Bag of words, TF-IDF, n-grams; today, sentence embeddings
Aggregates Per-user counts, rolling windows, recency/frequency/monetary features, computed only from data available at prediction time
Interactions Products, crosses (country × device); trees learn many automatically

Feature stores (chapter 150, 178) keep training and serving features consistent ("training–serving skew" is a classic production bug).

scikit-learn pipelines

scikit-learn's consistent estimator API (fit, predict, transform) and Pipeline make leakage-free workflows natural: every preprocessing step is fitted inside each CV fold.

Python
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
import pandas as pd

# A synthetic tabular dataset with numeric and categorical columns and missing values
n = 3000
df = pd.DataFrame({
    "age": rng.integers(18, 70, n).astype(float),
    "income": rng.lognormal(10.5, 0.6, n),
    "plan": rng.choice(["basic", "plus", "pro"], n),
    "region": rng.choice(["north", "south", "east", "west"], n),
})
df.loc[rng.random(n) < 0.1, "income"] = np.nan
logit = -3 + 0.04 * (df["age"] - 40) + 0.9 * (df["plan"] == "pro") + 0.6 * (df["region"] == "south")
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)

X_train, X_test, y_train, y_test = train_test_split(df, y, test_size=0.2, stratify=y, random_state=0)

num, cat = ["age", "income"], ["plan", "region"]
pre = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median", add_indicator=True)),
                      ("scale", StandardScaler())]), num),
    ("cat", OneHotEncoder(handle_unknown="ignore"), cat),
])
logreg = Pipeline([("pre", pre), ("clf", LogisticRegression(C=1.0, max_iter=1000))])

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
cross_val_score(logreg, X_train, y_train, cv=cv, scoring="roc_auc").mean()

gbdt = HistGradientBoostingClassifier(categorical_features="from_dtype", early_stopping=True, random_state=0)
X_train_c = X_train.astype({"plan": "category", "region": "category"})
search = GridSearchCV(gbdt, {"learning_rate": [0.05, 0.1], "max_depth": [3, None]},
                      cv=cv, scoring="roc_auc").fit(X_train_c, y_train)
search.best_params_, search.best_score_

The data here is generated from a logistic model, so logistic regression should match or beat the boosted trees: a reminder to compare against simple baselines.

Across languages and ecosystems

# Python: scikit-learn (classical), XGBoost / LightGBM / CatBoost (boosting)
import xgboost as xgb
model = xgb.XGBClassifier(n_estimators=2000, learning_rate=0.05, max_depth=6,
                          subsample=0.8, colsample_bytree=0.8, early_stopping_rounds=50)
model.fit(X_tr, y_tr, eval_set=[(X_val, y_val)], verbose=False)

Lab: cross-validated comparisons on real tabular data

scikit-learn 1.9.1 and XGBoost 3.4.1 on the lab machine, using the Wisconsin breast-cancer dataset (569 × 30, binary) and the diabetes dataset (442 × 10, regression), both bundled with scikit-learn so no download is needed. Stratified 5-fold CV with a fixed shuffle seed; preprocessing inside make_pipeline so scaling is fitted on each training fold only.

Experiment 1: nine classifiers

Model CV accuracy Time
majority class 62.7% —
logistic regression (unscaled, max_iter 200) 95.6% ± 1.6 0.14 s
logistic regression + StandardScaler 97.9% ± 1.4 0.03 s
k-NN (k=5) unscaled 93.2% ± 1.9 0.04 s
k-NN + scaling 96.5% ± 2.1 0.02 s
SVM, RBF kernel + scaling 97.7% ± 0.7 0.03 s
decision tree 92.6% ± 2.2 0.04 s
random forest, 300 trees 95.8% ± 1.7 2.36 s
XGBoost, 300 trees, depth 3, lr 0.1 97.7% ± 0.9 0.72 s

Unscaled logistic regression was also slower: the optimiser struggled with features on wildly different scales (the condition-number effect of chapter 146) and may stop before converging. Putting the scaler inside the pipeline matters: scaling the whole dataset before splitting leaks test-fold statistics into training, a mild but real form of leakage (chapter 149 shows a severe one). To compare two models properly on the same folds, use paired differences per fold or a corrected resampled t-test, not overlapping error bars.

Experiment 2: the regularisation path

| C | CV accuracy | Σ|w| | |---|---|---| | 0.001 | 89.1% | 1.6 | | 0.01 | 94.9% | 4.3 | | 0.1 | 97.5% | 9.3 | | 1 | 97.9% | 18.2 | | 10 | 97.0% | 37.3 | | 1000 | 95.3% | 186.9 |

Choosing C by CV and then reporting that same CV score is optimistic (you picked the best of six). The honest version is nested cross-validation: an inner CV picks C, an outer CV scores the whole procedure. With an L1 penalty (penalty="l1", solver="liblinear") many weights become exactly zero, giving built-in feature selection.

Experiment 3: regression with limited signal

Model 5-fold R²
linear regression 0.489 ± 0.090
ridge (α = 1) 0.420 ± 0.051
random forest 0.427 ± 0.100
XGBoost (300 trees, depth 2, lr 0.05) 0.438 ± 0.113

Ridge did worse than plain linear regression here because the bundled features are already scaled to small values, so α = 1 is a strong penalty for them; it needed tuning (try RidgeCV). The trees' high variance across folds reflects how few rows there are to split on. When every model plateaus at the same score, effort belongs in features and data (chapter 150), not algorithms.

Try it yourself

  1. Run nested CV for C (inner 5-fold, outer 5-fold) and compare its estimate with Experiment 2's best.
  2. Tune XGBoost's depth, learning rate and number of trees with RandomizedSearchCV and check whether it beats scaled logistic regression beyond the error bars.
  3. Fit an L1-penalised logistic regression and list the features it keeps at C = 0.1.
  4. Use RidgeCV(alphas=np.logspace(-4, 2, 30)) on diabetes and report the chosen α and R².

Revision sheet: classical machine learning

Key ideas

  • Setup: features X, target y; train/validation/test or cross-validation; always a baseline.
  • Linear regression (least squares, normal equations), logistic regression (log loss), regularisation (L2 ridge, L1 lasso, elastic net).
  • k-NN (distance-based, scale-sensitive), SVM (maximum margin, kernels), naive Bayes.
  • Trees (greedy splits by impurity), random forests (bagging + feature subsampling, lower variance), gradient boosting (XGBoost, LightGBM, CatBoost: sequential error correction).
  • Unsupervised: k-means, hierarchical clustering, DBSCAN, PCA.
  • Pipelines: preprocessing fitted inside CV folds; categorical encoding; missing-value handling.
  • Model selection: CV, nested CV, hyperparameter search; error bars and paired comparisons.
  • On tabular data, tuned gradient-boosted trees are the usual strongest baseline.

Numbers to remember

  • Lab: majority baseline 62.7%; scaled logistic regression 97.9% ± 1.4; XGBoost 97.7% ± 0.9.
  • Lab: scaling lifted k-NN from 93.2% to 96.5%.
  • Lab: diabetes R² ≈ 0.42–0.49 for every model.

Pitfalls

  • No baseline; reporting the best of many tries as the expected performance.
  • Fitting scalers or encoders on the full dataset before splitting.
  • Forgetting to scale for distance/gradient models.
  • Over-tuning on small datasets; ignoring fold-to-fold variance.
  • Assuming deep learning will beat boosted trees on tables.

Glossary

  • Bagging: training models on bootstrap samples and averaging.
  • Boosting: adding models sequentially to correct residual errors.
  • Kernel trick: computing similarities in an implicit high-dimensional space.
  • Impurity (Gini, entropy): measure trees reduce when splitting.
  • Nested CV: CV inside CV, separating tuning from evaluation.