Machine Learning
MDC_51006_EP · Year 1 · Period 1
Contents
- Introduction and overview
- 0. Review: optimization, concentration and information tools
- 1. The statistical framework of learning
- 2. Linear regression and regularization
- 3. Classification: logistic regression and SVM
- 4. Evaluation, big data and pipelines
- 5. Kernels and RKHS
- 6. Trees, forests, boosting
- 7. Unsupervised: k-means, EM, PCA
- 8. Generalization theory
- 9. Research at CMAP and LIX (Le Pennec, Read)
- Exercises
- Projects and assessment
- References
Introduction and overview
| Module | Machine Learning — SynapseS 2026-2027 sheet: “Programme d’approfondissement — Bases de l’Apprentissage Automatique” (occurrence: “Foundations of Machine Learning”) |
| Code | MDC_51006_EP |
| Team and workload | Responsible (sheet): Erwan Le Pennec & Jesse Read; responsible of the 2026-2027 occurrence: Erwan Le Pennec · teaching team: Arunava Gantait, Thierry Klein, Paul Mangold, Poyraz Yilan · 36 h in person (lecture / small-class split not displayed; max enrollment 144) · 4.5 ECTS · assessment: a final exam (official description) · language of instruction: English · the methodological foundation of the program: supervised and unsupervised learning, from least squares to boosting, together with the accompanying generalization theory. |
| Status in the program | Mandatory M1 · S1 / period 1 — X-3A-P1 (fall semester, from 17/09/26 to 18/12/26) |
Audience: engineer who already fitted a sklearn model / MNIST-like MLP and wants to understand why it generalizes (or not) — without opening on VC dimension. Empirical first: visible overfitting on a train/test split, ridge that “calibrates” coefficients, a forest that works when linear fails.
Mandatory module: methodological foundation — learning from data, and under what conditions it works. Supervised (least squares → boosting), unsupervised, generalization theory. This is what separates understanding models from calling a library. Downstream LLGA (DL, NLP, Graph ML, RL) reuses this vocabulary.
What you will be able to do
- Frame a learning problem: risk, empirical risk, hypotheses, bias-variance trade-off.
- Implement and tune linear regression, ridge/Lasso regularization, logistic regression and SVMs, justifying every choice.
- Use kernels to move to the nonlinear setting and understand what a “reproducing kernel Hilbert space” brings in practice.
- Choose between trees, random forests and boosting (gradient boosting) according to the nature of the data and the interpretability constraint, and explain a tree ensemble with Shapley values and permutation importance.
- Conduct a complete unsupervised analysis: k-means, Gaussian mixture and EM, PCA and dimensionality reduction.
- State and exploit generalization bounds to argue for a model’s performance on new data.
- Build a rigorous evaluation pipeline: splits, cross-validation, adapted metrics, per-group metrics and fairness criteria, honest comparison of two models, scaling up.
- Read an academic or industrial ML paper and identify the underlying statistical framework.
Official objectives and syllabus (2026-2027 catalog)
Official objectives (paraphrased from the description published on SynapseS): machine learning is the discipline that designs algorithms allowing computers to learn from data, automatically extract complex patterns from them and derive intelligent decisions from them. The course focuses on the methodology underlying supervised and unsupervised learning, with a particular emphasis on the mathematical formulation of the algorithms and on how they can be implemented and used in practice; to this end it presents the necessary tools from optimization theory.
Proofs are not done in lecture: some are done in labs, others are given in a document; each lab ends with a numerical exercise in Python. Official assessment: a final exam.
No session-by-session programme is displayed (the “Descriptif & programme” tab of the sheet is empty); the following table maps every element of the official description to our chapters.
| Element of the official description | Section of the course covering it |
|---|---|
| Methodology of supervised learning | ch. 1 (statistical framework), ch. 2 (regression, regularization), ch. 3 (logistic, SVM), ch. 6 (trees, forests, boosting) |
| Methodology of unsupervised learning | ch. 7 (k-means, EM, PCA) |
| Mathematical formulation of the algorithms | the guiding thread of all chapters, ch. 1 to 8 |
| Implementation and use in practice | Python labs of the chapters, ch. 4 (evaluation, big data, pipelines) |
| Optimization theory tools for ML | ch. 0 (gradient, convexity; 0.2 gradient descent, SGD, step size and conditioning, proximal step; 0.4 Lagrangian, KKT and LP duality), ch. 2 (normal equations, lasso soft thresholding), ch. 3 (convexity and Newton/IRLS for logistic regression; Lagrangian duality and KKT for the SVM), 6.3 (boosting as gradient descent in function space) |
| Numerical Python labs, proofs in labs or in a document | the Python blocks of ch. 0 to 7, the labs of the session plan, and the proofs written out in the chapters and in the exercises |
Our materials deliberately go beyond this official description, which remains generic: ch. 8 (generalization theory) pushes the theoretical analysis further than the official statement, ch. 5 (kernels and RKHS) and ch. 6 (trees, forests, boosting) detail model families that the sheet does not name, and ch. 4 (evaluation, big data, pipelines) and ch. 9 (research at CMAP and LIX (Le Pennec, Read)) are deepenings specific to the LLGA track. No theme explicitly listed in the catalog is missing.
| Official field | Published value (SynapseS 2026-2027) |
|---|---|
| Fields | Applied Mathematics, Computer Science |
| Contact hours | 36 h in person (no lecture / small-class split displayed) · max enrollment 144 |
| Period / language | X-3A-P1, fall semester, period 1 (17/09/26 – 18/12/26) · English |
| Responsible | Erwan Le Pennec, Jesse Read (occurrence: Erwan Le Pennec) · teaching team: Arunava Gantait, Thierry Klein, Paul Mangold, Poyraz Yilan |
| Prerequisites | Not displayed (the prerequisites tab is empty) |
| Assessment | A final exam (“Validation” in the description) · grade format: numeric out of 20 (and US letter grade) · the section for the LLGA track is empty: no resit rule, pass threshold or ECTS is displayed for LLGA · for the other degrees: resit allowed (resit grade kept, or max of the two grades for X and exchange programs), unit acquired if final grade ≥ 10, grade counted in the GPA; ECTS 5 (X, MPRI, CCSN, MJH, exchange programs), 4.5 (ViCAI, TRAI), 4 (XCin) · these notes keep 4.5 ECTS for LLGA |
Where this course fits in the program
This mandatory module of Year 1 · Period 1 (36 h, 4.5 ECTS) is the hinge of the program: it assumes the two refresher modules are completed, Refresher in Statistics (probability, basic inequalities, estimation, tests, linear regression) and Refresher in Computer Science (Python, NumPy, complexity). The refreshers do not teach optimization: the opening chapter “Review” supplies it (gradient descent, convexity, duality), together with Hoeffding’s inequality and the entropy and KL divergence used throughout.
The official 2026-2027 sheet displays no prerequisites (its tab is empty), but the emphasis on mathematical formulation and Python labs presupposes precisely these two foundations. The course unit is moreover shared with the engineering cycle (X), the MJH, MPRI and CCSN master’s programs and the other MScT tracks ViCAI and TRAI — hence a course tailored to advanced scientific profiles.
Downstream, it feeds everything else in the program. Deep Learning immediately follows by revisiting the perceptron and gradient descent; Emerging Subjects in ML reuses SGD and generalization theory for distributed learning. The Statistical Learning Theory notes deepen chapter 8 up to VC bounds and Rademacher complexity; that course is not in the LLGA 1 – S1 list (it is still offered in other tracks), and its notes are kept on this site for reference. The chapter on evaluation, big data and pipelines directly prepares the projects and applied modules of Period 2, from NLP to Graph ML.
The chapter “Research at CMAP and LIX (Le Pennec, Read)” presents the research of Erwan Le Pennec (CMAP) and Jesse Read (LIX): it is a gateway to internships and possible PhD topics from the end of M1.
Course outline
- Review: optimization, concentration and information: gradient, convexity, concentration inequalities, entropy and KL divergence, Lagrangian duality — L3 tools, immediately mobilized.
- The statistical framework of learning: risk, empirical minimization, bias-variance — the constitution of the problem.
- Linear regression and regularization: the reference model and the first answer to overfitting.
- Classification: logistic, SVM and naive Bayes: margins, losses, decision boundaries, generative versus discriminative modelling.
- Evaluation, big data and pipelines: operational rigor — metrics, validation, scaling up.
- Kernels and RKHS: linearizing the nonlinear via the kernel embedding.
- Trees, forests, boosting: the still-essential family on tabular data, in companies as in competitions.
- Unsupervised: k-means, EM, PCA: segmenting and compressing without labels.
- Generalization theory: why (and when) the empirical error announces the true error.
- Research at CMAP and LIX (Le Pennec, Read): research at CMAP and LIX, from forests to ensembles, and possible internship topics.
Session plan
36 h in class = 12 sessions of 3 h. The volume is the one of the SynapseS 2026–2027 sheet (36 h in person); the sheet publishes no session-by-session programme, so the split below is our proposal for covering these notes in that time. Level 1 = foundations (reviews, definitions, first worked examples), 2 = core methods, 3 = advanced theory; the level never goes down from one session to the next.
| Session | Hours | Level | Content | Practice |
|---|---|---|---|---|
| 1 | 3 h | 1 | ch. 0 Review: gradients, convexity, concentration; 0.2 gradient descent and SGD (step size, conditioning, mini-batches); 0.3 entropy, cross-entropy and KL | lab: Hoeffding by simulation; GD versus SGD on least squares; Ex. 5 |
| 2 | 3 h | 1 | ch. 1 The statistical framework: learning paradigms and the pipeline, risk, bias-variance, cross-validation | lab: train/test split, overfitting curve |
| 3 | 3 h | 1 | ch. 2.1 Ordinary least squares, Gauss-Markov, residual analysis | Ex. 2 |
| 4 | 3 h | 2 | ch. 2.2 Ridge and lasso, Bayesian reading | Ex. 1 |
| 5 | 3 h | 2 | ch. 3.1 Logistic regression | Ex. 3 |
| 6 | 3 h | 2 | ch. 3.2 Margin SVM and margin bounds (read 0.4 before); 3.3 generative versus discriminative classifiers, naive Bayes | Ex. 9 |
| 7 | 3 h | 2 | ch. 4.1–4.7 Evaluation: metrics, nested cross-validation, leakage, imbalance, calibration, the reference pipeline, feature selection and the selection-bias trap | Ex. 18 (start the project) |
| 8 | 3 h | 2 | ch. 4.8 Subgroup evaluation and group fairness; ch. 5 Kernels and RKHS | Ex. 14; Ex. 8 |
| 9 | 3 h | 2 | ch. 6 Trees, random forests, boosting; 6.4 explaining tree ensembles | Ex. 4, 15 |
| 10 | 3 h | 2 | ch. 7.1–7.2 k-means, choosing K, hierarchical and density clustering; Gaussian mixtures with EM | Ex. 10, 12 |
| 11 | 3 h | 2 | ch. 7.3 Principal component analysis; limits of t-SNE and UMAP | Ex. 6; lab: PCA on images |
| 12 | 3 h | 3 | ch. 8 Generalization theory: VC dimension, McDiarmid and contraction, Rademacher complexity | Ex. 11, 16 |
Self-study, outside the 36 h (about 5 h in total): ch. 0.4 Lagrangian, KKT and LP duality (≈ 1 h, read before session 3; Ex. 2 in session 3 and Ex. 9 in session 6 use it) · ch. 4.9 Comparing two models honestly (≈ 1 h, after session 7, with Ex. 7) · ch. 9 Research at CMAP and LIX — multi-label learning and aggregation of estimators (≈ 3 h, with Ex. 13 and 17).
How to study this module
- First secure the review: the opening chapter gathers the L3 optimization and concentration tools, which the Refresher in Statistics does not cover, and the entropy and KL divergence met in its section 9.3. The refresher’s probability and estimation chapters are assumed: if an exercise there resists you, handle it before moving on.
- Follow the chapter order: every model family (linear, kernels, trees) is taken up again by generalization theory, which only makes sense after them.
- Reimplement at least once each familiar model (ridge regression, k-means, a tree) in NumPy before using scikit-learn.
- Do the paper exercises on bounds and bias-variance: these are the most discriminating questions in the assessments.
- Build a complete end-to-end mini-pipeline on a real dataset as soon as chapter 4 is done: this is what recruiters expect, and every later model family plugs into it.
- Keep the chapter “Research at CMAP and LIX (Le Pennec, Read)” as an orientation signal: it announces internship topics. For more theory after chapter 8, the Statistical Learning Theory notes are kept on this site for reference (that course is not in the LLGA list).
independent note Whether you aim at LLM×graph deployment or a PhD, the founding question remains that of this module: under what conditions does a model learned on past data generalize? Transformers, GNNs, systems — answers to that question. We start from numbers (split, train vs test error), not from VC.
Notation
Deviations from the site-wide conventions (notation page). Chapter 2 writes p for the number of features, as regression textbooks do. Chapter 9 writes L for the number of labels, as the multi-label literature does. The Lagrangian of sections 0.4 and 3.2 is written \mathcal{L}; it is minimized over the primal variables.
Everywhere else the page follows the site-wide conventions:
- Data: a sample D_n = \{(x_i, y_i)\}_{i=1}^n drawn iid from \mathbb{P}, with n examples and d features, and X \in \mathbb{R}^{n \times d}.
- Losses and risks: a loss \ell(\hat y, y) is written prediction first; \mathcal{R}(f) is the risk, \hat{\mathcal{R}}_n(f) the empirical risk, and F(\theta) an objective minimized over parameters.
- Reserved letters: \eta is a learning rate, or the inverse temperature of exponential weights; L is a smoothness (Lipschitz) constant, or the graph Laplacian L = D - A in graph examples; the bound maximized by EM is written \mathrm{ELBO}.
0. Review: optimization, concentration and information tools
L3 background used throughout the module
- Gradient: \nabla f(x) \in \mathbb{R}^d points in the direction of steepest ascent; for f(x)=\frac12\|Ax - b\|^2, \nabla f(x) = A^\top(Ax - b).
- Convexity: f is convex if f(\lambda x + (1-\lambda)y) \leq \lambda f(x) + (1-\lambda) f(y). A local minimum of a convex function is global — the reason so many ML losses are designed convex.
- Gradient descent: x_{t+1} = x_t - \eta \nabla f(x_t), convergence \mathcal{O}(1/t) for a step \eta < 1/L (L = Lipschitz constant of the gradient).
- Symmetric matrices: diagonalizable (A = Q \Lambda Q^\top, Q orthogonal); A \succeq 0 (positive) iff all its eigenvalues are \geq 0. For a symmetric matrix, \sup_{\|v\| \leq 1} v^\top A v = \lambda_{\max}(A) (Rayleigh quotient) — the hidden tool of PCA (chapter 7).
0.1. Why concentration inequalities in an ML course?
All of generalization theory (chapter 8) rests on one simple question: is the empirical risk \hat{\mathcal{R}}_n(f), computed on n examples, close to the true risk \mathcal{R}(f)? The answer is given by concentration inequalities — results of probability analysis that we use here as a black box, proved once and for all.
Proposition 0.1 — Markov’s inequality Let Z \geq 0 be an integrable random variable. For every t > 0, \mathbb{P}(Z \geq t) \leq \frac{\mathbb{E}[Z]}{t}.
Proof. Writing Z = Z\,\mathbf{1}\{Z \geq t\} + Z\,\mathbf{1}\{Z < t\} and noting that Z\,\mathbf{1}\{Z \geq t\} \geq t\,\mathbf{1}\{Z \geq t\}, monotonicity of the expectation gives \mathbb{E}[Z] \geq t\,\mathbb{P}(Z \geq t).∎
Proposition 0.2 — Chebyshev’s inequality Let X have finite variance. For every t > 0, \mathbb{P}\big(|X - \mathbb{E}[X]| \geq t\big) \leq \frac{\mathrm{Var}(X)}{t^2}.
Proof. Apply Markov to Z = (X - \mathbb{E}[X])^2 \geq 0 with threshold t^2 and note that \{|X - \mathbb{E}[X]| \geq t\} = \{Z \geq t^2\}.∎
Chebyshev gives a 1/(nt^2) decay for a mean of n variables: usable but slow, and with no exponential control. The extra ingredient — independence — provides the exponential magic.
Theorem 0.3 — Hoeffding’s inequality Let X_1, \dots, X_n be independent with X_i \in [a_i, b_i] almost surely and S_n = X_1 + \cdots + X_n. For every t > 0, \mathbb{P}\big(S_n - \mathbb{E}[S_n] \geq t\big) \leq \exp\!\Big(-\,\frac{2t^2}{\sum_{i=1}^n (b_i - a_i)^2}\Big), and the same bound holds for the deviation \mathbb{P}(\mathbb{E}[S_n] - S_n \geq t). In particular, for losses in [0,1]:
Key result — Hoeffding for a loss in [0, 1] \mathbb{P}\big(|\hat{\mathcal{R}}_n(f) - \mathcal{R}(f)| \geq \varepsilon\big) \leq 2e^{-2n\varepsilon^2}.
Proof. Sketch in three moves.
- Hoeffding’s lemma. For centered X \in [a,b], one bounds its generating function. By convexity of u \mapsto e^{su}, the curve lies below the chord joining (a, e^{sa}) and (b, e^{sb}), hence e^{sX} \leq \frac{b - X}{b - a}e^{sa} + \frac{X - a}{b - a}e^{sb}. Taking expectations, \mathbb{E}[e^{sX}] \leq \frac{b}{b-a}e^{sa} - \frac{a}{b-a}e^{sb} = e^{\varphi(s)}, with \varphi(0) = \varphi'(0) = 0 and \varphi''(s) \leq (b-a)^2/4, so \varphi(s) \leq s^2(b-a)^2/8 (second-order Taylor remainder).
- Multiplication. For centered S_n, independence gives \mathbb{E}[e^{sS_n}] = \prod_i \mathbb{E}[e^{sX_i}] \leq \exp\big(s^2 \sum_i (b_i - a_i)^2/8\big).
- Chernoff. For all s > 0, \mathbb{P}(S_n \geq t) \leq e^{-st}\,\mathbb{E}[e^{sS_n}] \leq \exp\big(-st + \tfrac{s^2}{8}\sum_i(b_i - a_i)^2\big). The right-hand side is minimal at s^\star = 4t/\sum_i(b_i-a_i)^2, which gives \exp(-2t^2/\sum_i (b_i-a_i)^2).∎
Why this is central in ML Hoeffding says: for a fixed f, \hat{\mathcal{R}}_n(f) is exponentially close to \mathcal{R}(f). But the learner chooses \hat f_n while looking at the data — one must then control \sup_{f \in \mathcal{F}} over the whole class: this is precisely the subject of chapter 8 (uniform convergence, VC dimension, Rademacher complexity). Without this supplement, nothing can be proved about overfitting.
0.2. Gradient descent and stochastic gradient descent
The official description of the course announces “tools from optimization theory, and how to use them for machine learning”. Almost every estimator of this module is the minimizer of an empirical risk F(\theta) = \frac1n\sum_{i=1}^n \ell_i(\theta), where \ell_i is the loss on example i. When no closed form exists (logistic regression, the lasso, boosting, neural networks), the minimizer is computed iteratively. Two numbers of the problem govern how fast this works: the smoothness constant and the curvature.
Definition 0.4 — Smoothness, strong convexity, condition number A differentiable function f is L-smooth if its gradient is L-Lipschitz: \|\nabla f(x) - \nabla f(y)\| \leq L\|x - y\|. It is \mu-strongly convex (\mu > 0) if f - \frac{\mu}{2}\|\cdot\|^2 is convex. For a twice-differentiable f, these mean \mu I \preceq \nabla^2 f(x) \preceq L I for every x.
The ratio \kappa = L/\mu \geq 1 is the condition number: the larger it is, the more elongated the level sets and the slower gradient descent becomes.
Theorem 0.5 — Convergence of gradient descent Let f be convex and L-smooth with a minimizer x^\star, and run x_{t+1} = x_t - \eta\nabla f(x_t) with \eta = 1/L. Then
- (i) (sublinear rate) f(x_t) - f(x^\star) \leq \dfrac{L\|x_0 - x^\star\|^2}{2t};
- (ii) if moreover f is \mu-strongly convex (linear, also called geometric, rate), \|x_t - x^\star\|^2 \leq (1 - 1/\kappa)^t\,\|x_0 - x^\star\|^2.
Proof. Proof of (ii) for a quadratic f(x) = \frac12 (x - x^\star)^\top A (x - x^\star) with \mu I \preceq A \preceq LI, the case met in least squares. The gradient is A(x - x^\star), so the error e_t = x_t - x^\star satisfies e_{t+1} = (I - \eta A)\,e_t.
The eigenvalues of I - A/L lie in [0, 1 - \mu/L], hence \|e_{t+1}\| \leq (1 - 1/\kappa)\|e_t\| and \|e_t\|^2 \leq (1 - 1/\kappa)^{2t}\|e_0\|^2 \leq (1-1/\kappa)^t\|e_0\|^2.
The general statements (i) and (ii) follow from the descent lemma f(y) \leq f(x) + \langle\nabla f(x), y - x\rangle + \frac L2\|y - x\|^2 combined with convexity (and, for (ii), strong convexity); see Garrigos & Gower (2023), section 3.∎
Example 0.6 — Step size on least squares For F(\theta) = \frac{1}{2n}\|y - X\theta\|^2, the Hessian is H = X^\top X/n, so L-smoothness and strong convexity hold with L = \lambda_{\max}(H) and \mu = \lambda_{\min}(H).
Take two centred, uncorrelated features with variances 4 and 0.04: H = \mathrm{diag}(4, 0.04), so L = 4, \mu = 0.04 and \kappa = 100.
The recursion e_{t+1} = (I - \eta H)e_t diverges as soon as \eta > 2/L = 0.5, because the factor |1 - 4\eta| exceeds 1. With \eta = 1/L = 0.25, the first coordinate is solved in one step (1 - 0.25 \times 4 = 0).
But the second coordinate shrinks by only 1 - 0.01 = 0.99 per step: about \ln(100)/0.01 \approx 460 iterations to divide its error by 100.
Standardizing both features to unit variance gives \kappa = 1 and convergence in one step. This is the optimization reason, beyond interpretability, for the StandardScaler placed in every pipeline of chapter 1.
Stochastic gradient descent (SGD). One full gradient costs \mathcal{O}(nd), which is prohibitive when n reaches millions. SGD replaces it by the gradient of one example drawn uniformly at random, or of a mini-batch B_t of size b: \theta_{t+1} = \theta_t - \eta_t\,\frac1b\sum_{i \in B_t}\nabla \ell_i(\theta_t). Because \mathbb{E}_i[\nabla \ell_i(\theta)] = \nabla F(\theta), the step is right on average; its variance decreases like 1/b when the mini-batch is drawn with replacement.
Two regimes follow. With a constant step, SGD reaches a neighbourhood of the minimizer whose size is proportional to \eta times the gradient noise, and then oscillates there. With decreasing steps such that \sum_t \eta_t = \infty and \sum_t \eta_t^2 < \infty (for example \eta_t \propto 1/t), the iterates converge (Robbins–Monro conditions).
For a convex loss, if \|\theta_0 - \theta^\star\| \leq R and the stochastic gradients satisfy \mathbb{E}\|\nabla \ell_i(\theta_t)\|^2 \leq G^2 along the iterates, the averaged iterate \bar\theta_T obtained with \eta = R/(G\sqrt T) satisfies
\mathbb{E}[F(\bar\theta_T)] - F(\theta^\star) \leq RG/\sqrt T.
This rate is slower per iteration than theorem 0.5, but each iteration is n/b times cheaper — the trade-off behind partial_fit in section 4.6 and behind the training of every neural network in the Deep Learning module.
Non-smooth penalties: the proximal step The lasso objective \frac1n\|y - X\theta\|^2 + \lambda\|\theta\|_1 is not differentiable at zero, so plain gradient descent does not apply. The proximal gradient method (ISTA) takes a gradient step on the smooth part and then applies the soft thresholding of proposition 2.6 coordinate by coordinate: \theta \leftarrow S_{\eta\lambda}\big(\theta - \eta\,\tfrac2n X^\top(X\theta - y)\big), with S_\tau(z) = \mathrm{sign}(z)(|z| - \tau)_+. This is why the lasso solvers of scikit-learn produce exact zeros. With the orthogonal design of proposition 2.6, the smooth part is 2-smooth, and one step of size \eta = 1/2 lands on the exact solution.
import numpy as np
rng = np.random.default_rng(0)
n, d = 10_000, 5
X = rng.normal(size=(n, d)); theta_star = rng.normal(size=d)
y = X @ theta_star + 0.1 * rng.normal(size=n)
L = np.linalg.eigvalsh(X.T @ X / n).max() # smoothness constant
theta = np.zeros(d)
for t in range(100): # full gradient descent, step 1/L
theta -= (1 / L) * X.T @ (X @ theta - y) / n
theta_sgd = np.zeros(d)
for t in range(1, 2001): # mini-batch SGD, b = 32, decreasing step
idx = rng.integers(0, n, size=32)
grad = X[idx].T @ (X[idx] @ theta_sgd - y[idx]) / 32
theta_sgd -= 0.5 / np.sqrt(t) * grad
print(np.linalg.norm(theta - theta_star), np.linalg.norm(theta_sgd - theta_star))0.3. Entropy, cross-entropy and KL divergence
Classification losses, the EM algorithm of chapter 7 and the training objective of every language model compare two probability distributions. Three quantities do this job. We define them on a finite set; for densities, integrals replace the sums.
Definition 0.7 — Entropy, cross-entropy, Kullback–Leibler divergence For distributions p and q on a finite set \mathcal{Z}, with q(z) > 0 wherever p(z) > 0: H(p) = -\sum_z p(z)\log p(z), \qquad H(p, q) = -\sum_z p(z)\log q(z), \qquad \mathrm{KL}(p \,\|\, q) = \sum_z p(z)\log\frac{p(z)}{q(z)}. The entropy H(p) measures the uncertainty of p. The cross-entropy H(p, q) is the average code length when data drawn from p are coded with a code built for q, and the KL divergence is the excess length. With the natural logarithm they are measured in nats; with \log_2, in bits, as in the impurity of section 6.1.
Proposition 0.8 — Gibbs’ inequality and maximum likelihood
- (i) \mathrm{KL}(p \,\|\, q) \geq 0, with equality if and only if p = q.
- (ii) The cross-entropy splits into entropy plus divergence: H(p, q) = H(p) + \mathrm{KL}(p \,\|\, q) \geq H(p).
- (iii) For a sample z_1, \dots, z_n with empirical distribution \hat p_n and a model q_\theta, -\frac1n \sum_{i=1}^n \log q_\theta(z_i) = H(\hat p_n, q_\theta) = H(\hat p_n) + \mathrm{KL}(\hat p_n \,\|\, q_\theta). Since H(\hat p_n) does not depend on \theta, maximizing the likelihood is minimizing the cross-entropy, and also the KL divergence from the data to the model.
Proof.
- (i) The logarithm is strictly concave. Jensen’s inequality under p, applied to the variable q(Z)/p(Z), gives -\mathrm{KL}(p \,\|\, q) = \mathbb{E}_p\Big[\log\frac{q(Z)}{p(Z)}\Big] \leq \log \mathbb{E}_p\Big[\frac{q(Z)}{p(Z)}\Big] = \log \sum_{z :\, p(z) > 0} q(z) \leq \log 1 = 0. Equality in Jensen forces q/p to be a constant c on the support of p; equality in the last step forces c = 1, so p = q.
- (ii) Write \log(p/q) = \log p - \log q in the definition of KL.
- (iii) Grouping equal values, the left-hand side is -\sum_z \hat p_n(z) \log q_\theta(z); then apply (ii).∎
The logistic loss of proposition 3.2 is (iii) for the Bernoulli model of the label given x, and the softmax loss of language models is (iii) for the next token. The Refresher in Statistics, section 9.3 derives (iii) for conditional models.
Mutual information. The dependence between two variables is the divergence between their joint law and the product of their marginals: I(X; Y) = \mathrm{KL}\big(p_{XY} \,\|\, p_X \otimes p_Y\big) = H(Y) - H(Y \mid X) \geq 0, where H(Y \mid X) is the average entropy of Y once X is known. By (i), it is zero if and only if X and Y are independent. It is the information gain of the trees of section 6.1 and one of the filter scores of section 4.7.
Example 0.9 — Forward and reverse KL on a bimodal target The target is the mixture p = \tfrac12\mathcal{N}(-3, 1) + \tfrac12\mathcal{N}(3, 1), and we fit one Gaussian q = \mathcal{N}(m, s^2). KL is not symmetric, and the two directions give different fits.
- Forward KL, minimizing \mathrm{KL}(p \,\|\, q) as maximum likelihood does. The penalty is large wherever p has mass and q has none, so q must cover both modes. The optimum matches the mean and the variance of p: m = 0, \qquad s^2 = 1 + 9 = 10.
- Reverse KL, minimizing \mathrm{KL}(q \,\|\, p) as the E-step of chapter 7 and variational inference do. The penalty is large wherever the fit puts mass and the target has little, so q settles on one mode, near \mathcal{N}(3, 1) or \mathcal{N}(-3, 1), at a cost close to \log 2.
Forward KL is mass-covering; reverse KL is mode-seeking. A numerical minimization over (m, s) confirms both fits.
0.4. Lagrangian duality and KKT conditions (self-study)
Read this section alone before session 3, where Exercise 2 first needs it. Many estimators minimize a function under constraints: the SVM of section 3.2 is solved through its dual, and Exercises 2 and 9 minimize under constraints. Duality turns each constraint into a price, and the KKT conditions characterize the optimum.
Definition 0.10 — Lagrangian and dual problem Consider the problem p^\star = \min_{x \in \mathbb{R}^d} f(x) \quad \text{s.t.} \quad g_i(x) \leq 0 \ (i \leq m), \qquad h_j(x) = 0 \ (j \leq r). Its Lagrangian attaches a multiplier \alpha_i \geq 0 to each inequality and \nu_j \in \mathbb{R} to each equality: \mathcal{L}(x, \alpha, \nu) = f(x) + \sum_i \alpha_i g_i(x) + \sum_j \nu_j h_j(x). The dual function is \psi(\alpha, \nu) = \inf_x \mathcal{L}(x, \alpha, \nu), and the dual problem is \psi^\star = \max_{\alpha \geq 0,\ \nu} \psi(\alpha, \nu).
Theorem 0.11 — Weak duality, strong duality, KKT
- (i) Weak duality: \psi^\star \leq p^\star always.
- (ii) Strong duality (Slater): if f and the g_i are convex, the h_j are affine, and some point satisfies every g_i(x) < 0 and every h_j(x) = 0, then \psi^\star = p^\star.
- (iii) KKT conditions: under the assumptions of (ii), with f and the g_i differentiable, a feasible x^\star is optimal if and only if there exist \alpha^\star \geq 0 and \nu^\star with \nabla f(x^\star) + \sum_i \alpha_i^\star \nabla g_i(x^\star) + \sum_j \nu_j^\star \nabla h_j(x^\star) = 0 \quad \text{(stationarity)}, and \alpha_i^\star g_i(x^\star) = 0 for every i (complementary slackness).
Proof. Proof of (i). Take a feasible x and \alpha \geq 0. Each \alpha_i g_i(x) \leq 0 and each h_j(x) = 0, so \psi(\alpha, \nu) \leq \mathcal{L}(x, \alpha, \nu) \leq f(x). Take the supremum over (\alpha, \nu) on the left and the infimum over feasible x on the right.
The proof of (ii) separates two convex sets by a hyperplane (Boyd & Vandenberghe, 2004, section 5.3). In (iii), complementary slackness says that a multiplier can be positive only on an active constraint: this is how section 3.2 reads the support vectors.∎
Example 0.12 — The constraint of Exercise 2 Minimize \|a\|^2 over a \in \mathbb{R}^n under \mathbf{1}^\top a = 1. The Lagrangian is \mathcal{L}(a, \nu) = \|a\|^2 + \nu(\mathbf{1}^\top a - 1). Stationarity gives 2a + \nu\mathbf{1} = 0, so every a_i equals -\nu/2. The constraint then gives \nu = -2/n, hence a_i = 1/n \quad \text{for every } i, with optimal value 1/n. The problem is convex with an affine constraint, so these conditions are sufficient.
Linear programs. When the objective and the constraints are affine, the dual is again a linear program: \min_{x \geq 0} \ c^\top x \ \ \text{s.t.} \ \ Ax \geq b \qquad \text{has the dual} \qquad \max_{y \geq 0} \ b^\top y \ \ \text{s.t.} \ \ A^\top y \leq c. For linear programs, strong duality holds as soon as the primal has a finite optimum, with no Slater condition. Linear-programming duality comes back in reinforcement learning (the linear program of a Markov decision process) and in optimal transport.
1. The statistical framework of learning
Concrete scene: you fit a classifier on 60,000 digits (MNIST-like), train accuracy 99.8%, test 91%. The model “works”… and memorizes. Conversely, an under-regularized linear model may stall at 85% everywhere. This chapter names those gaps: risk vs empirical risk, bias-variance, validation. Theory comes after the symptom.
What breaks Tuning hyperparameters on the test set; ignoring class imbalance; believing a falling loss ⇒ generalization. All three sabotage a sklearn pipeline as much as an LLM fine-tune.
Learning paradigms and the pipeline Machine learning is usually divided by the kind of feedback the data provide. Supervised learning observes labelled pairs (x_i, y_i) and learns a predictor f(x) \approx y: regression when y is real, classification when y is a class (chapters 1 to 6).
Unsupervised learning observes only the x_i and looks for structure: groups (clustering), a low-dimensional representation (dimensionality reduction) or a density (chapter 7). Self-supervised learning manufactures labels from the data themselves, for example by hiding a word and predicting it; this is how language models are pretrained (Deep Learning module, section 6.5). Reinforcement learning has no labels at all: an agent chooses actions and receives scalar rewards (Deep Learning module, section 1.5).
Whatever the paradigm, a project follows the same pipeline: collect and split the data, learn the preprocessing on the training part only, fit and select models, evaluate once on held-out data, then inspect the errors. Chapter 4 makes each step precise.
Definition 1.1 — iid framework and risk One observes an iid sample D_n = (X_i, Y_i)_{i \leq n} with law \mathbb{P} on \mathcal{X} \times \mathcal{Y}. For a loss \ell : \mathcal{Y} \times \mathcal{Y} \to \mathbb{R}_+, written \ell(\hat y, y) with the prediction first, the risk of a predictor f : \mathcal{X} \to \mathcal{Y} is \mathcal{R}(f) = \mathbb{E}\big[\ell(f(X), Y)\big], and the (observable) empirical risk: \hat{\mathcal{R}}_n(f) = \frac1n \sum_{i=1}^n \ell(f(X_i), Y_i). The Bayes risk is \mathcal{R}^\star = \inf_f \mathcal{R}(f), the infimum over all measurable functions.
Definition 1.2 — Empirical risk minimization (ERM) Given a model class \mathcal{F}, learning solves \hat f_n \in \arg\min_{f \in \mathcal{F}} \ \hat{\mathcal{R}}_n(f). All of ML consists in choosing \mathcal{F} (linear? tree-based? network?), \ell (quadratic, logistic, hinge…), and in controlling the gap \mathcal{R}(\hat f_n) - \inf_{f \in \mathcal{F}} \mathcal{R}(f).
The excess risk decomposes into two contributions of different natures:
Key result — approximation and estimation errors \underbrace{\mathcal{R}(\hat f_n) - \mathcal{R}^\star}_{\text{excess risk}} = \underbrace{\inf_{f \in \mathcal{F}} \mathcal{R}(f) - \mathcal{R}^\star}_{\text{approximation error}} + \underbrace{\mathcal{R}(\hat f_n) - \inf_{f \in \mathcal{F}} \mathcal{R}(f)}_{\text{estimation error}}.
The first depends only on the choice of \mathcal{F} (modeling bias), the second on the sample and the size of \mathcal{F} (variance, chapter 8). Enlarging \mathcal{F} decreases the first and increases the second: the whole dilemma is there.
1.1. Bias-variance
Proposition 1.3 — Bias-variance decomposition (quadratic loss) Assume Y = f^\star(X) + \varepsilon with f^\star(x) = \mathbb{E}[Y \mid X = x] and noise \mathrm{Var}(\varepsilon \mid X) = \sigma^2. For an estimator \hat f_n built on D_n independent of the test pair (X, Y):
Key result — bias-variance decomposition \mathbb{E}\big[(Y - \hat f_n(X))^2\big] = \underbrace{\sigma^2}_{\text{irreducible noise}} + \mathbb{E}\big[\underbrace{\text{bias}^2(\hat f_n)}_{\text{underfitting}} + \underbrace{\mathrm{Var}(\hat f_n)}_{\text{overfitting}}\big].
Proof. Condition on X = x and on D_n (the total expectation is then taken over both).
On the one hand \hat f_n(x) depends only on D_n, and Y = f^\star(x) + \varepsilon with \mathbb{E}[\varepsilon \mid x, D_n] = 0; the cross term therefore vanishes: \mathbb{E}\big[(Y - \hat f_n(x))^2\big] = \sigma^2 + \mathbb{E}\big[(f^\star(x) - \hat f_n(x))^2\big].
On the other hand, for any variable Z, \mathbb{E}[Z^2] = (\mathbb{E}Z)^2 + \mathrm{Var}(Z) applied to Z = f^\star(x) - \hat f_n(x) (the variance is over the randomness of D_n): \mathbb{E}\big[(f^\star(x) - \hat f_n(x))^2\big] = \big(f^\star(x) - \mathbb{E}[\hat f_n(x)]\big)^2 + \mathrm{Var}\big(\hat f_n(x)\big).
Finally integrate over x \sim \mathbb{P}_X.∎
A class \mathcal{F} that is too small ⇒ high bias; too large ⇒ high variance. This decomposition is diagnostic: high training and test errors ⇒ underfitting (enlarge the model); low training and high test ⇒ overfitting (regularize, more data, chapters 2 and 8). No algorithm is universally better (the “no free lunch” theorem): prior knowledge about the data matters as much as the algorithm.
1.2. Cross-validation
The risk \mathcal{R} is unobservable: it is estimated by setting data aside. k-fold: split into k blocks, train k times while rotating the test block, average.
Leave-one-out (k = n) has low bias but high estimation variance and costs n trainings; k = 5 or 10 is the standard compromise.
Program rules: never fit preprocessing on the test set; a final test set that is looked at only once; validation serves to choose hyperparameters and models (chapter 4 for the nested version).
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_val_score(pipe, X, y, cv=5, scoring="neg_root_mean_squared_error")
print(-scores.mean(), scores.std())2. Linear regression and regularization
2.1. Ordinary least squares
Definition 2.1 — Gaussian linear model One observes y = X\theta + \varepsilon where X \in \mathbb{R}^{n \times p} is fixed (the design), \theta \in \mathbb{R}^p, and one assumes:
- (H1) \mathbb{E}[\varepsilon] = 0;
- (H2) \mathrm{Var}(\varepsilon) = \sigma^2 I_n (homoscedasticity);
- (H3) independent components;
- (H4, optional) \varepsilon \sim \mathcal{N}(0, \sigma^2 I_n).
The least squares estimator minimizes \hat{\mathcal{R}}_n(\theta) = \tfrac1n \|y - X\theta\|^2.
Proposition 2.2 — Normal equations If X^\top X is invertible, the unique minimizer is \hat\theta = (X^\top X)^{-1} X^\top y.
Proof. Expand \|y - X\theta\|^2 = \theta^\top X^\top X\,\theta - 2\,\theta^\top X^\top y + \|y\|^2. The gradient in \theta is 2X^\top X \theta - 2X^\top y (symmetric matrix for the quadratic term); setting it to zero gives the normal equations X^\top X\theta = X^\top y. The Hessian 2X^\top X \succeq 0 is positive definite as soon as \mathrm{rank}(X) = p: the function is strictly convex, the stationary point is the unique global minimum.∎
Geometry: an orthogonal projection \hat y = X\hat\theta = P y with P = X(X^\top X)^{-1}X^\top the orthogonal projection onto \mathrm{Im}(X). One checks P^2 = P = P^\top; the residual e = y - \hat y satisfies X^\top e = 0, i.e. e \perp \mathrm{Im}(X).
The h_{ii} = P_{ii} (the leverages) measure the influence of each observation, with \sum_i h_{ii} = p.
Theorem 2.3 — Gauss-Markov Under (H1)-(H3), for every c \in \mathbb{R}^p, the estimator c^\top\hat\theta is the best linear unbiased estimator (BLUE) of c^\top\theta: among the a^\top y with \mathbb{E}[a^\top y] = c^\top\theta for every \theta, it has minimal variance.
Proof. A linear estimator a^\top y is unbiased for every \theta iff a^\top X = c^\top. Set a_\star = X(X^\top X)^{-1}c \in \mathrm{Im}(X): a_\star^\top X = c^\top, so a_\star is admissible, and \mathrm{Var}(a_\star^\top y) = \sigma^2 \|a_\star\|^2 = \sigma^2 c^\top(X^\top X)^{-1}c, which is indeed the variance of c^\top\hat\theta.
Let a be any admissible vector and h = a - a_\star; then h^\top X = 0, so h \perp \mathrm{Im}(X) \ni a_\star, hence \mathrm{Var}(a^\top y) = \sigma^2\|a\|^2 = \sigma^2\big(\|a_\star\|^2 + \|h\|^2\big) \geq \sigma^2\|a_\star\|^2 = \mathrm{Var}(c^\top\hat\theta), with equality iff a = a_\star.∎
Inference: confidence intervals (under H4) Under Gaussian noise (a linear variable of a Gaussian vector), \hat\theta \sim \mathcal{N}\big(\theta,\ \sigma^2(X^\top X)^{-1}\big), and \hat\sigma^2 = \tfrac{1}{n-p}\|y - X\hat\theta\|^2 is an unbiased estimator independent of \hat\theta.
Writing v_j = [(X^\top X)^{-1}]_{jj}, the statistic (\hat\theta_j - \theta_j)/(\hat\sigma\sqrt{v_j}) follows a Student distribution with n - p degrees of freedom, giving the 95% confidence interval: \hat\theta_j \pm t_{0.975}^{\,n-p}\; \hat\sigma \sqrt{v_j}. (Reminder on usual distributions: cf. Refresher Statistics module.) The (estimator, standard deviation) pair reported by any serious regressor is read here: a coefficient whose interval contains 0 is not “significant”.
Residual analysis — the model’s quality control The assumptions (H1)-(H4) are checked graphically on the residuals e_i = y_i - \hat y_i (standardized r_i = e_i/\big(\hat\sigma\sqrt{1 - h_{ii}}\big)):
- residuals vs fitted values (a curvature betrays a missing nonlinearity; a funnel, heteroscedasticity — think of transforming y or weighting);
- Gaussian quantile-quantile plot (departure of the noise from normality);
- spotting high-leverage points h_{ii} \gg 2p/n that “pull” the line.
2.2. Regularization: ridge and lasso
Definition 2.4 — Ridge and lasso \hat\theta_{\text{ridge}} = \arg\min_\theta \Big\{\tfrac1n\|y - X\theta\|^2 + \lambda \|\theta\|_2^2\Big\} = (X^\top X + n\lambda I)^{-1} X^\top y, \hat\theta_{\text{lasso}} = \arg\min_\theta \Big\{\tfrac1n\|y - X\theta\|^2 + \lambda \|\theta\|_1\Big\}. Ridge shrinks all coefficients (a solution always exists); the lasso produces coefficients that are exactly zero (variable selection).
Proposition 2.5 — Ridge: spectral effect Write the SVD X = U\,\mathrm{diag}(\sigma_j)\,V^\top. Then \hat\theta_{\text{ridge}} = \sum_j \frac{\sigma_j\, u_j^\top y}{\sigma_j^2 + n\lambda}\; v_j, \qquad\text{whereas}\qquad \hat\theta = \sum_j \frac{u_j^\top y}{\sigma_j}\;v_j. Ridge damps each direction v_j by the factor \sigma_j^2/(\sigma_j^2 + n\lambda): the well-explained directions (large \sigma_j) pass through, the ill-conditioned directions (collinearities, \sigma_j \to 0) are crushed — exactly the ones that made the least squares variance explode.
In particular \|\hat\theta_{\text{ridge}}\| decreases from \|\hat\theta\| toward 0 as \lambda grows.
Proposition 2.6 — Lasso with an orthogonal design: soft thresholding Assume the columns of X are orthogonal with squared norm n (uncorrelated standardized features), that is X^\top X = n I_p, and set z = X^\top y/n. Then the lasso of definition 2.4 is \hat\theta_{\text{lasso},j} = \mathrm{sign}(z_j)\,\big(|z_j| - \lambda/2\big)_+. With orthonormal columns (X^\top X = I_p) instead, the same computation thresholds X^\top y at n\lambda/2.
Proof. Expanding the square with X^\top X = nI_p gives \tfrac1n\|y - X\theta\|^2 = \|\theta - z\|^2 + \text{const.}, so the lasso objective is twice a functional that separates over the coordinates: \sum_j \big\{\tfrac12(z_j - \theta_j)^2 + \tfrac{\lambda}{2}|\theta_j|\big\}. For z_j > 0, the optimum is either \theta_j = 0 (cost z_j^2/2), or a stationary point in the region \theta_j > 0 where the norm-1 term is differentiable: z_j - \theta_j = \lambda/2, of cost \lambda z_j/2 - \lambda^2/8 < z_j^2/2 as soon as z_j > \lambda/2. Hence the thresholding; the case z_j < 0 is symmetric.∎
It is this “dead zone” around zero that sets coefficients exactly to zero: in arbitrary dimension, the path \lambda \mapsto \hat\theta_{\text{lasso}}(\lambda) is piecewise linear (the LARS algorithm of Efron et al., 2004), which lasso_path visualizes.
Geometry of regularization Constraint \|\theta\|_1 \leq t = diamond: the corners on the axes explain the sparsity; \|\theta\|_2 \leq t = ball: isotropic shrinkage. Regularization is the first weapon against variance — and the ancestor of the weight decay of neural networks (\lambda\|\theta\|_2^2 added to the loss in the Deep Learning module).
Proposition 2.7 — Bayesian reading: ridge = Gaussian prior, lasso = Laplacian prior Assume y = X\theta + \varepsilon with \varepsilon \sim \mathcal{N}(0, \sigma^2 I).
- (i) If \theta \sim \mathcal{N}(0, \tau^2 I), the MAP (maximum a posteriori) is exactly \hat\theta_{\text{ridge}} with \lambda = \sigma^2/(n\tau^2).
- (ii) If the coordinates of \theta are iid with Laplacian density p(\theta_j) = \tfrac{1}{2b}e^{-|\theta_j|/b}, the MAP is \hat\theta_{\text{lasso}} with \lambda = 2\sigma^2/(nb).
Proof. By Bayes’ formula, -\log p(\theta \mid y) = \tfrac{1}{2\sigma^2}\|y - X\theta\|^2 - \sum_j \log p(\theta_j) + \text{const.}
- (i) -\log p(\theta_j) = \theta_j^2/(2\tau^2) + \text{const.}: minimizing amounts to minimizing \|y - X\theta\|^2 + \tfrac{\sigma^2}{\tau^2}\|\theta\|_2^2.
- (ii) -\log p(\theta_j) = |\theta_j|/b + \text{const.}: minimize \|y - X\theta\|^2 + \tfrac{2\sigma^2}{b}\|\theta\|_1.
In both cases the negative log-posterior was multiplied by 2\sigma^2. Dividing by n gives the objectives of definition 2.4, with \lambda = \sigma^2/(n\tau^2) for ridge and \lambda = 2\sigma^2/(nb) for the lasso.∎
Moral: regularizing = encoding a prior (small / sparse coefficients); the Laplacian prior, peaked at zero, “pushes” coefficients toward zero more strongly than the Gaussian.
from sklearn.linear_model import Ridge, Lasso, lasso_path
for lam in [1e-4, 1e-2, 1.0, 10.0]:
l = Lasso(alpha=lam).fit(X, y)
print(f"lambda={lam:8.3f} nonzero coeffs = {(l.coef_ != 0).sum()}")
# lasso regularization path (piecewise linear, cf. LARS)
alphas, coefs, _ = lasso_path(X, y, alphas=np.logspace(-3, 1, 100))3. Classification: logistic regression and SVM
3.1. Logistic regression
Definition 3.1 For Y \in \{0, 1\}, one directly models \mathbb{P}(Y = 1 \mid X = x) = \sigma(\langle \theta, x\rangle) = \frac{1}{1 + e^{-\langle \theta, x\rangle}}, where \sigma is the sigmoid. The log-odds is linear: \log \tfrac{p}{1-p} = \langle\theta, x\rangle — hence an interpretable reading of the coefficients (odds ratio \approx e^{\theta_j} for x_j increased by one unit).
Proposition 3.2 — Likelihood and cross-entropy Maximizing the likelihood \prod_i \sigma(\theta^\top x_i)^{y_i}(1 - \sigma(\theta^\top x_i))^{1 - y_i} is equivalent to minimizing the cross-entropy \hat\theta = \arg\min_\theta \ \frac1n \sum_{i=1}^n \log\!\big(1 + e^{-y'_i \langle\theta, x_i\rangle}\big), \qquad y'_i \in \{-1, +1\}.
Proof. -\log-likelihood = \sum_i -y_i\log p_i - (1 - y_i)\log(1 - p_i) with p_i = \sigma(\theta^\top x_i). Writing y'_i = 2y_i - 1, one checks -y_i \log p_i - (1-y_i)\log(1-p_i) = \log(1 + e^{-y'_i \theta^\top x_i}): for y_i = 1, 1 - p_i = \sigma(-\theta^\top x_i) and 1/(1-p_i) = 1 + e^{\theta^\top x_i}.∎
Theorem 3.3 — Convexity, gradient, Hessian Set p_i(\theta) = \sigma(\theta^\top x_i) and F(\theta) = \tfrac1n\sum_i \log(1 + e^{-y'_i\theta^\top x_i}). Then:
- (i) F is convex, and strictly convex if \ker X = \{0\};
- (ii) \nabla F(\theta) = \tfrac1n X^\top(p(\theta) - y);
- (iii) with w_i = p_i(1 - p_i) \in \,]0, 1/4], \nabla^2 F(\theta) = \tfrac1n X^\top \mathrm{diag}\big(w_i(\theta)\big) X.
Proof.
- (i) Let g(z) = \log(1 + e^{-z}). Then g'(z) = \tfrac{-e^{-z}}{1 + e^{-z}} = -\sigma(-z) and g''(z) = \sigma(-z)\big(1 - \sigma(-z)\big) = \frac{e^{-z}}{(1 + e^{-z})^2} > 0, (the rate of change of \sigma' — or direct differentiation of \sigma' = \sigma(1-\sigma)). Hence g is convex; each g(\pm\theta^\top x_i) is convex in \theta (composition with an affine map), and F, a sum, is convex.
- (ii) The loss of example i is g(y'_i\theta^\top x_i). By the chain rule with g' above, \nabla_\theta\, g(y'_i\theta^\top x_i) = g'(y'_i\theta^\top x_i)\, y'_i x_i = -y'_i x_i\, \sigma(-y'_i \theta^\top x_i). If y_i = 1, then y'_i\sigma(-y'_i\theta^\top x_i) = 1 - p_i; if y_i = 0, it equals -\sigma(\theta^\top x_i) = -p_i. In both cases it is y_i - p_i, so each example contributes x_i(p_i - y_i), and averaging gives (ii).
- (iii) The Jacobian of p(\theta) is \mathrm{diag}(w_i)X (since \sigma' = \sigma(1 - \sigma)), giving the announced Hessian. It is a weighted Gram matrix, not a multiple of X^\top X: for every v, v^\top X^\top \mathrm{diag}(w_i) X v = \sum_i w_i\,(x_i^\top v)^2 \geq 0, because every w_i > 0, with equality only if Xv = 0. The Hessian is therefore positive semidefinite, and positive definite when the columns of X are independent.∎
Practical consequences Convex + smooth ⇒ a unique global optimum, reached by gradient descent or Newton. The Newton method here reads \theta \leftarrow \theta + (X^\top W X)^{-1} X^\top(y - p): this is exactly the iteratively reweighted regression (IRLS) well known from GLMs. This is the classification loss of neural networks (Deep Learning module) and of LLMs (softmax output = multiclass generalization \log\sum_k e^{s_k} - s_{y}).
3.2. Margin SVM
Definition 3.4 — SVM (soft margin, primal) \min_{\theta, b, \xi} \ \tfrac12 \|\theta\|^2 + C \sum_{i=1}^n \xi_i \quad \text{s.t.} \quad y'_i(\langle\theta, x_i\rangle + b) \geq 1 - \xi_i, \quad \xi_i \geq 0. Maximize the margin \gamma = 1/\|\theta\| while tolerating the violations \xi_i (soft constraints, C = unit penalty). The classifier is x \mapsto \mathrm{sign}(\langle\theta, x\rangle + b).
Theorem 3.5 — Dual of the SVM The primal above has the same solution as the dual problem \max_{\alpha} \ \sum_{i=1}^n \alpha_i - \frac12 \sum_{i,j} \alpha_i\alpha_j y'_i y'_j \langle x_i, x_j\rangle \quad \text{s.t.} \quad 0 \leq \alpha_i \leq C, \ \sum_i \alpha_i y'_i = 0, and the primal solution is reconstructed via \theta = \sum_i \alpha_i y'_i x_i.
Proof. Lagrangian. Associate a multiplier \alpha_i \geq 0 with each margin constraint and \mu_i \geq 0 with \xi_i \geq 0: \mathcal{L} = \tfrac12\|\theta\|^2 + C\textstyle\sum_i \xi_i - \sum_i \alpha_i\big[y'_i(\theta^\top x_i + b) - 1 + \xi_i\big] - \sum_i \mu_i \xi_i.
Stationary conditions (KKT). \begin{aligned} \partial_\theta \mathcal{L} = 0 &\Rightarrow \theta = \sum_i \alpha_i y'_i x_i, \\ \partial_b \mathcal{L} = 0 &\Rightarrow \sum_i \alpha_i y'_i = 0, \\ \partial_{\xi_i} \mathcal{L} = 0 &\Rightarrow C = \alpha_i + \mu_i, \text{ i.e. } \alpha_i \leq C. \end{aligned} The first condition says that the predictor is a combination of the data!
Substitute back: the term \theta^\top\theta against -\sum\alpha_i y'_i\theta^\top x_i gives -\tfrac12\|\theta\|^2, then replacing \|\theta\|^2 by the double sum.
The \xi_i disappear exactly ((C - \alpha_i - \mu_i)\xi_i = 0); what remains is the announced dual function with 0 \leq \alpha_i \leq C.
The primal is convex with affine constraints, and the point \theta = 0, b = 0, \xi_i = 2 satisfies all of them strictly: Slater’s condition (theorem 0.11 (ii)) holds whatever C, and guarantees strong duality — dual optimum = primal optimum, and the KKT conditions are necessary and sufficient.∎
Reading the complementarity conditions — who are the support vectors? The KKT complementarity conditions \alpha_i\,[y'_i(\theta^\top x_i + b) - 1 + \xi_i] = 0 and (C - \alpha_i)\,\xi_i = 0 sort the points into three families:
| Case | Position of the point | Role |
|---|---|---|
| \alpha_i = 0 | outside the margin band, well classified | none — any data point |
| 0 < \alpha_i < C | exactly on the margin (\xi_i = 0) | “free” support vector |
| \alpha_i = C | inside the band or misclassified (\xi_i > 0) | “paying” support vector |
The solution depends only on the points with \alpha_i > 0 (dual sparsity): this is the robustness of SVMs to distant data, and the \mathcal{O}(n_{\text{supp}}) prediction cost. The constant b is recovered from any point on the margin: b = y'_i - \theta^\top x_i.
Theorem 3.6 — Margin generalization bounds (sketch) Let \mathcal{F}_R = \{x \mapsto \langle\theta, x\rangle : \|\theta\| \leq R,\ \|x\| \leq 1\}. Its Rademacher complexity (definition in chapter 8) satisfies \mathcal{R}_n(\mathcal{F}_R) \leq R/\sqrt{n}, independently of the dimension of \mathcal{X}. It follows, with high probability, for any score function with margin \gamma (losses dominated by the hinge): \mathcal{R}(f) \ \leq\ \hat{\mathcal{R}}_{n,\gamma}(f) + \frac{2R}{\gamma\sqrt{n}} + \sqrt{\tfrac{\log(2/\delta)}{2n}}. Sketch.
- (i) The hinge (1 - t)_+ is 1-Lipschitz: the contraction lemma brings the loss back to the score.
- (ii) For the class of bounded scores, \mathbb{E}_\sigma \sup_{\|\theta\| \leq R} \tfrac1n\theta^\top\sum_i \sigma_i x_i = \tfrac{R}{n}\,\mathbb{E}_\sigma\big\|\sum_i \sigma_i x_i\big\| \leq \tfrac{R}{n}\sqrt{\mathbb{E}\big\|\sum_i\sigma_ix_i\big\|^2} = \tfrac{R}{n}\sqrt{n} = \tfrac{R}{\sqrt n} (Cauchy-Schwarz, then orthogonality of the \sigma_ix_i and \|x_i\| \leq 1).∎
This “margin, not dimension” viewpoint watches over overfitting; it is developed in chapter 8, and further in the Statistical Learning Theory notes, kept for reference (that course is not in the LLGA list).
3.3. Generative versus discriminative classifiers: naive Bayes
Logistic regression models \mathbb{P}(Y \mid X) directly, and the SVM only a decision boundary: both are discriminative. A generative classifier takes the opposite route: it models how each class produces its inputs, p(x \mid y), together with the class proportions \pi_y = \mathbb{P}(Y = y), and classifies with Bayes’ formula.
Definition 3.7 — Generative classifier and naive Bayes A generative classifier predicts \hat y(x) = \arg\max_k \ \pi_k\, p(x \mid Y = k), which is the Bayes classifier when the model is correct. Naive Bayes assumes that the features are independent given the class: p(x \mid Y = k) = \prod_{j=1}^d p_j(x_j \mid Y = k). Each one-dimensional factor is estimated separately by maximum likelihood: Bernoulli frequencies for binary features (word present or absent), multinomial frequencies for counts, a per-class mean and variance for real features (Gaussian naive Bayes). The number of parameters grows linearly in d, and training is a single counting pass over the data.
Proposition 3.8 — Gaussian naive Bayes has a logistic posterior With two classes, x_j \mid Y = k \sim \mathcal{N}(\mu_{kj}, \sigma_j^2) (variances shared by the classes), \mathbb{P}(Y = 1 \mid x) = \sigma(\theta^\top x + b), \qquad \theta_j = \frac{\mu_{1j} - \mu_{0j}}{\sigma_j^2}, \qquad b = \log\frac{\pi_1}{\pi_0} + \sum_j \frac{\mu_{0j}^2 - \mu_{1j}^2}{2\sigma_j^2}.
Proof. By Bayes’ formula, \log\frac{\mathbb{P}(Y=1\mid x)}{\mathbb{P}(Y=0\mid x)} = \log\frac{\pi_1}{\pi_0} + \sum_j \log\frac{p_j(x_j \mid 1)}{p_j(x_j \mid 0)}. For each j, the Gaussian normalizing constants cancel and \frac{(x_j - \mu_{0j})^2 - (x_j - \mu_{1j})^2}{2\sigma_j^2} = \frac{(\mu_{1j} - \mu_{0j})\,x_j}{\sigma_j^2} + \frac{\mu_{0j}^2 - \mu_{1j}^2}{2\sigma_j^2}. The log-odds is therefore affine in x, and inverting \log\frac{p}{1-p} = z gives p = \sigma(z).∎
The model family is the same as in section 3.1; only the fitting differs. Naive Bayes fits \theta through the joint likelihood of (x, y), which is efficient when its assumptions hold; logistic regression fits \mathbb{P}(Y \mid x) only and remains consistent for that family when they fail.
Ng and Jordan (2002) made the trade-off precise: the generative classifier approaches its asymptotic error with a number of examples of order \log d, the discriminative one with order d, but the discriminative asymptotic error is never worse. Naive Bayes is therefore a strong baseline for small samples and high-dimensional text, and logistic regression usually wins once data are plentiful.
Example 3.9 — A two-word spam filter A training set has 40 spam and 60 legitimate emails. The word “free” appears in 24 spam and 6 legitimate emails; the word “meeting” appears in 4 spam and 30 legitimate emails.
For a new email containing “free” but not “meeting”, the Bernoulli naive Bayes scores are \text{spam: } 0.4 \times \tfrac{24}{40} \times \big(1 - \tfrac{4}{40}\big) = 0.216, \qquad \text{legitimate: } 0.6 \times \tfrac{6}{60} \times \big(1 - \tfrac{30}{60}\big) = 0.03, so \mathbb{P}(\text{spam} \mid x) = 0.216 / (0.216 + 0.03) \approx 0.88.
Had “free” never occurred in a legitimate email, its estimated probability there would be 0 and this single word would veto the class whatever the rest of the email says. Laplace smoothing replaces each frequency m/n_k by (m + 1)/(n_k + 2), which keeps every probability positive.
4. Evaluation, big data and pipelines
4.1. Choosing your metric
| Metric | Definition | When to use it |
|---|---|---|
| accuracy | \frac{TP+TN}{n} | balanced classes |
| balanced accuracy | mean of per-class recall | mild imbalance |
| precision / recall | \frac{TP}{TP+FP} / \frac{TP}{TP+FN} | imbalance (fraud, spam) |
| F1 | harmonic mean of precision/recall | precision/recall trade-off |
| AUC-ROC | area under the ROC curve | ordering examples (ranking) |
| PR-AUC | area in precision-recall | very strong imbalance (more informative than ROC) |
| Brier | \frac1n\sum_i (\hat p_i - y_i)^2 | calibrated quality of probabilities |
| RMSE / MAE | squared / absolute errors | regression |
4.2. Nested cross-validation
Selecting a model and estimating its risk on the same folds is a well-documented optimism bias: the retained score is that of a “champion” chosen among the candidates on those same data — the exact mechanism of selection overfitting (chapter 8!). Nested cross-validation separates the two roles: the inner loop (on k-1 folds) chooses the hyperparameters, the outer loop (the remaining fold) evaluates the model thus chosen. Cost: k_{\text{int}} \times k_{\text{ext}} trainings — the price of statistical honesty.
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
grid = GridSearchCV(pipe, {"logisticregression__C": [0.01, 0.1, 1, 10]}, cv=5)
outer_scores = cross_val_score(grid, X, y, cv=10) # outer loop: honest estimation
print(outer_scores.mean(), outer_scores.std())4.3. Data leakage
The four classic leaks — and the antidote
- (1) Standardizing/imputing before the split: the test statistics contaminate the training.
- (2) Target encoding (target encoding) computed on the whole set: the answer leaks into the features.
- (3) Duplicates of the same entity (patient, sensor) split across both train and test: one evaluates memory, not generalization.
- (4) Variables posterior to the predicted event (reimbursement amount to predict a default).
The antidote fits in one rule: every transformation that “learns” lives inside the pipeline, hence re-estimated on each training fold — this is exactly what scikit-learn’s Pipeline and ColumnTransformer do, including for nested validators.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.ensemble import HistGradientBoostingClassifier
prep = ColumnTransformer([
("num", Pipeline([("imp", SimpleImputer(strategy="median")),
("sc", StandardScaler())]), num_cols),
("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
])
model = Pipeline([("prep", prep), ("clf", HistGradientBoostingClassifier())])
# model.fit on the train only; nothing is learned outside fit().4.4. Imbalanced classes
With 0.5% of fraud, the trivial classifier “everything is normal” reaches 99.5% accuracy. Three levers:
- (i) the loss — weight the classes via
class_weight="balanced": the \propto 1/n_k weighting restores the balance in ERM; - (ii) resampling — oversampling the minority (SMOTE: interpolate between minority neighbors) or undersampling the majority, always inside the training pipeline only (otherwise: leakage);
- (iii) evaluation — precision/recall, PR-AUC; and the decision threshold chosen after calibration (4.5), not at 0.5 by default.
4.5. Probability calibration
Definition 4.1 — Calibration A probability predictor \hat p is calibrated if, among the cases where it announces p, the observed frequency of the event equals p: \mathbb{P}(Y = 1 \mid \hat p(X) = p) = p. The reliability diagram (observed frequency vs predicted probability, per bin) and the Brier score \frac1n\sum_i(\hat p_i - y_i)^2 (a squared loss! cf. chapter 2) measure it.
Two standard post-processings, learned on a separate calibration set: Platt scaling — fit a logistic regression (chapter 3) on the noisy score: \hat p = \sigma(a\,s(x) + b); isotonic regression — the nonparametric monotone function closest to the reliability bins (more flexible, more data needed).
Caution: discrimination and calibration are two distinct properties — a model may excellently order examples (high AUC) while announcing systematically overconfident probabilities. SVM scores are not probabilities: going through calibration is indispensable as soon as one wants probabilities (cost/benefit decisions, stacking).
from sklearn.calibration import CalibratedClassifierCV
cal = CalibratedClassifierCV(estimator=svc, method="isotonic", cv=5).fit(X_train, y_train)
# check: sklearn.calibration.calibration_curve + Brier score4.6. Big data: what does size change?
When n explodes, theory plays for you (bounds in \sqrt{d/n}, chapter 8) but computation costs become the limiting factor. Switch to incremental methods (partial_fit/SGD: the stochastic gradient descent of section 0.2, one pass at a time), to hashing for sparse text features, to histogram implementations (HistGradientBoosting), and to the stream methods of chapter 9 (River) when the data do not fit in memory.
Golden rule of the program: a complete reference pipeline — train/val/test split → preprocessing learned on train only → nested selection → single evaluation on test → error inspection (confusion matrix, residuals of chapter 2, subgroups) — to be replicated in all the labs and the running project. The Year 1 end-of-year projects use this pipeline as their shared evaluation kit, completed by subgroup metrics (4.8), honest model comparison (4.9) and the paired, group-level comparison of the Refresher in Statistics exit checkpoint.
4.7. Feature selection
Removing useless features reduces variance, cost and the effort of interpretation. Three families of methods exist, and all three are learning steps: they must be fitted on training data only.
Definition 4.2 — Filter, wrapper and embedded selection A filter ranks features by a univariate score computed against the label (correlation, ANOVA F statistic, mutual information, \chi^2) and keeps the top k; it is fast but blind to interactions: with y = x_1 \oplus x_2 (exclusive or), each feature alone carries no information although the pair determines y.
A wrapper searches over subsets using the validation error of the model itself; forward stepwise selection adds, at each step, the feature that most reduces that error, at a cost of about kd model fits for k features.
Embedded methods select while fitting: the lasso sets coefficients exactly to zero (section 2.2), and trees and forests rank features by importance (chapter 6); importances should be measured by permutation on held-out data, since impurity-based importances favour features with many distinct values.
Example 4.3 — The selection-bias trap Take n = 50 samples, d = 5000 features of pure noise and random balanced labels: the true error of any classifier is 50%. Yet among 5000 noise features, the largest absolute sample correlation with the labels is of order \sqrt{2\ln(2d)/n} \approx 0.6, so a filter applied to all 50 samples finds features that look strongly predictive.
Cross-validating a classifier on those features after the selection is then badly optimistic: with 100 selected features and a 1-nearest-neighbour classifier, Hastie, Tibshirani and Friedman (Elements of Statistical Learning, section 7.10.2) report an average cross-validated error of 3%. The selection saw the test folds.
The correct procedure puts the selection inside the pipeline, so that it is refitted on the training part of each fold; the cross-validated error then returns to about 50%.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
X = rng.normal(size=(50, 5000)); y = rng.permutation(np.repeat([0, 1], 25)) # pure noise
top = SelectKBest(f_classif, k=20).fit(X, y).get_support() # WRONG: selection on all data
print(cross_val_score(LogisticRegression(), X[:, top], y, cv=5).mean()) # optimistic
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression()) # RIGHT: inside the folds
print(cross_val_score(pipe, X, y, cv=5).mean()) # close to 0.54.8. Subgroup evaluation and group fairness
An average score can hide a group on which the model fails. Before deployment, the error inspection of the reference pipeline (4.6) is repeated per group: by sex, age band, region, device, or any attribute on which errors would be costly or unfair.
The per-group metrics are computed on the held-out predictions of the pipeline, never on the training data. Each comes with its group size: a 20-point gap on a group of 30 people is mostly noise (section 4.9 gives the intervals).
Definition 4.4 — Three group-fairness criteria Let A be a group attribute, Y \in \{0, 1\} the label, S \in [0, 1] a score and \hat Y the decision. For all groups a and b:
- demographic parity asks for the same rate of positive decisions, \mathbb{P}(\hat Y = 1 \mid A = a) = \mathbb{P}(\hat Y = 1 \mid A = b);
- equalized odds (Hardt, Price and Srebro, 2016) asks for the same true-positive and false-positive rates, that is, for y \in \{0, 1\}, \mathbb{P}(\hat Y = 1 \mid Y = y, A = a) = \mathbb{P}(\hat Y = 1 \mid Y = y, A = b); equal opportunity asks this for y = 1 only;
- calibration within groups asks that definition 4.1 hold inside each group, \mathbb{P}(Y = 1 \mid S = s, A = a) = s \quad \text{for every } a \text{ and } s.
These criteria cannot all hold at once. The identity below, a simple count, shows why.
Proposition 4.5 — Precision, error rates and prevalence (Chouldechova, 2017) In a group with prevalence \pi = \mathbb{P}(Y = 1), every decision rule satisfies \mathrm{FPR} = \frac{\pi}{1 - \pi}\cdot\frac{1 - \mathrm{PPV}}{\mathrm{PPV}}\cdot(1 - \mathrm{FNR}), where PPV is the precision, FPR the false-positive rate and FNR the false-negative rate. Hence, if two groups have different prevalences, a rule with the same precision in both (predictive parity) and the same false-negative rate has different false-positive rates, unless it makes no false positive at all.
Kleinberg, Mullainathan and Raghavan (2017) prove the analogue for scores: calibration within groups and balanced error rates are incompatible, except for a perfect predictor or equal prevalences.
Proof. Let N_+ and N_- be the numbers of positives and negatives of the group, so N_-/N_+ = (1 - \pi)/\pi. By the definitions of the false-negative rate and of the precision, \mathrm{TP} = (1 - \mathrm{FNR})\,N_+, \qquad \mathrm{FP} = \mathrm{TP}\,\frac{1 - \mathrm{PPV}}{\mathrm{PPV}}. Dividing \mathrm{FP} by N_- gives the identity.∎
Example 4.6 — Same precision, different false alarms Group a has prevalence 0.5 and group b has prevalence 0.2. A rule has precision 0.8 and false-negative rate 0.2 in both groups. By proposition 4.5, \mathrm{FPR}_a = 1 \times 0.25 \times 0.8 = 0.2, \qquad \mathrm{FPR}_b = 0.25 \times 0.25 \times 0.8 = 0.05. The negatives of group a are wrongly flagged four times as often. Equal false-positive rates would need a different threshold per group, and then the precisions or the false-negative rates would differ. Which criterion matters is a decision about the application, not a property of the model.
There are three places to act on a disparity: before training (reweighting the groups), during training (a constraint in the loss), and after training (one threshold per group, the post-processing of Hardt and coauthors). Deleting the attribute A from the features is not enough when other features are correlated with it.
import pandas as pd
res = pd.DataFrame({"y": y_test, "yhat": model.predict(X_test), "group": X_test["sex"]})
for g, d in res.groupby("group"): # held-out predictions only
pos, neg = d.y == 1, d.y == 0
print(g, len(d), "positive rate", d.yhat.mean(),
"TPR", d.yhat[pos].mean(), "FPR", d.yhat[neg].mean(), "PPV", d.y[d.yhat == 1].mean())4.9. Comparing two models honestly (self-study)
“Model B beats model A by 0.8 points” is a claim about risks, made from noisy estimates. This section, read after session 7, gives the tools to check such a claim before writing it.
Paired comparisons over folds or seeds. Evaluate both models on the same folds, or with the same seeds, and work with the differences \delta_j = s_j(B) - s_j(A) for j = 1, \dots, k. With \bar\delta their mean and s_\delta their standard deviation, the paired statistic t = \frac{\bar\delta}{s_\delta/\sqrt{k}} is compared with a Student distribution with k - 1 degrees of freedom. Pairing removes the variation that both models share: an easy fold is easy for both. Two caveats:
- cross-validation folds share training data, so the differences are correlated and the plain test is too optimistic. Nadeau and Bengio (2003) correct it by replacing 1/k with 1/k + n_{\text{test}}/n_{\text{train}} in the variance;
- with few folds or skewed differences, the Wilcoxon signed-rank test, which uses only the signed ranks of the differences, makes no normality assumption.
One test set: McNemar’s test. When both models are evaluated once on the same test examples, only their disagreements matter. Let n_{01} count the examples that A gets right and B gets wrong, and n_{10} the reverse. If both models have the same accuracy, each disagreement goes either way with probability 1/2, and \chi^2 = \frac{(|n_{01} - n_{10}| - 1)^2}{n_{01} + n_{10}} approximately follows a \chi^2 law with one degree of freedom: reject equality at 5 % above 3.84. With few disagreements, use the exact binomial test instead (Dietterich, 1998).
An interval for one accuracy: Clopper–Pearson. If k of n test examples are classified correctly, the exact 95 % interval for the accuracy is \big[\,B_{0.025}(k,\ n - k + 1),\ \ B_{0.975}(k + 1,\ n - k)\,\big], where B_q(a, b) is the q-quantile of the Beta distribution with parameters a and b. For 870 correct answers out of 1000, it gives [0.848, 0.890]. The interval is 4 points wide, so a 1-point difference between two models needs the paired tests above, not two overlapping intervals.
Many comparisons: Bonferroni. Testing m hypotheses (ten datasets, five baselines) at level \alpha each produces false discoveries. Testing each at level \alpha/m keeps the probability of any false discovery below \alpha, by the union bound.
A protocol for a claim of improvement
- Retrain the baseline with the same pipeline, split and tuning budget as the new model, instead of copying a number from a paper.
- Use at least 3 seeds, or the folds of 4.2, for each model; report the mean, the standard deviation and the paired test.
- Ablate: remove each new component in turn and measure the loss, so that the gain is attributed.
- Touch the test set once, after every choice is made (4.2).
5. Kernels and RKHS
Definition 5.1 — Positive definite kernel k : \mathcal{X} \times \mathcal{X} \to \mathbb{R} is a positive definite kernel if there exists a map \phi : \mathcal{X} \to \mathcal{H} (a Hilbert space) such that k(x, x') = \langle \phi(x), \phi(x')\rangle. Equivalent: for every n, every (x_i) and every (c_i) \in \mathbb{R}^n, \sum_{ij} c_i c_j k(x_i, x_j) \geq 0 — the Gram matrix K = (k(x_i, x_j)) is symmetric positive.
Examples
- Polynomial k(x,x') = (\langle x,x'\rangle + c)^p (explicit feature map: all monomials of degree \leq p, dimension \binom{d+p}{p}).
- Gaussian (RBF) k(x,x') = \exp(-\gamma\|x - x'\|^2) — feature map of infinite dimension: expanding e^{2\gamma\langle x,x'\rangle}e^{-\gamma\|x\|^2}e^{-\gamma\|x'\|^2} as a power series in \langle x, x'\rangle exhibits \phi(x) = a renormalized Gaussian vector.
- On graphs: the diffusion kernel between nodes, k(u, v) = [e^{-\beta L}]_{uv}, with the graph Laplacian L = D - A (degree matrix minus adjacency matrix, cf. Graph ML module), or the shortest-path kernel — kernels are the ancestor of GNNs!
5.1. The Moore-Aronszajn theorem
Theorem 5.2 — Moore-Aronszajn (sketch) If k is a positive definite kernel, there exists a unique Hilbert space \mathcal{H} of functions \mathcal{X} \to \mathbb{R} such that
- (i) k_x := k(\cdot, x) \in \mathcal{H} for every x, and
- (ii) the reproducing property: f(x) = \langle f, k_x\rangle for every f \in \mathcal{H}, every x.
It is called the RKHS of k.
Proof. Construction. Set \mathcal{H}_0 = \mathrm{Span}\{k_x : x \in \mathcal{X}\} (finite combinations) and, for f = \sum_i \alpha_i k_{x_i}, g = \sum_j \beta_j k_{y_j}, \langle f, g\rangle_0 := \sum_{i,j}\alpha_i\beta_j\, k(x_i, y_j). This form is well defined (independent of the decompositions: reduce to the case \langle k_x, k_y\rangle_0 = k(x,y) and expand), bilinear, and positive by the very definition of a positive definite kernel. Definiteness follows from Cauchy-Schwarz: |f(x)|^2 = |\langle f, k_x\rangle_0|^2 \leq \|f\|_0^2\, k(x,x).
Completion. This inequality above all shows that the evaluation f \mapsto f(x) is 1-Lipschitz-continuous on \mathcal{H}_0: it extends to the completion \mathcal{H}, whose elements are therefore genuine functions (local uniform limits of elements of \mathcal{H}_0). The reproducing property, true on \mathcal{H}_0 by construction, passes to the limit; uniqueness follows from the density of the k_x.∎
5.2. The representer theorem and kernel regression
Theorem 5.3 — Representer theorem Let \mathcal{H} be the RKHS of k and \hat f \in \arg\min_{f \in \mathcal{H}} \tfrac1n\sum_i \ell(f(x_i), y_i) + \lambda\|f\|_\mathcal{H}^2 for an arbitrary convex loss. Then \hat f \in \mathrm{Span}\{k_{x_i} : i \leq n\}: \hat f = \sum_{i=1}^n \alpha_i\, k(\cdot, x_i).
Proof. Decompose \mathcal{H} = V \oplus V^\perp with V = \mathrm{Span}\{k_{x_i}\}, and f = f_V + f_\perp. The reproducing property gives f(x_i) = \langle f, k_{x_i}\rangle = \langle f_V, k_{x_i}\rangle = f_V(x_i): the loss term sees only f_V. Since \|f\|^2 = \|f_V\|^2 + \|f_\perp\|^2, any nonzero orthogonal component costs norm without changing anything on the data: the optimum lies in V.∎
Proposition 5.4 — Kernel ridge regression (KRR): closed formula The minimizer in \mathcal{H} of \tfrac1n\sum_i (y_i - f(x_i))^2 + \lambda\|f\|_\mathcal{H}^2 is \hat f(x) = \sum_i \alpha_i k(x_i, x) where \alpha = (K + n\lambda I_n)^{-1} y, \qquad K_{ij} = k(x_i, x_j).
Proof. By the representer theorem, substitute f = \sum_i\alpha_ik(\cdot,x_i). The empirical risk becomes \tfrac1n\|y - K\alpha\|^2 and \|f\|_\mathcal{H}^2 = \sum_{ij}\alpha_i\alpha_j k(x_i,x_j) = \alpha^\top K\alpha. Minimize \tfrac1n\|y - K\alpha\|^2 + \lambda\,\alpha^\top K\alpha in \alpha; the gradient \tfrac2n K(K\alpha - y) + 2\lambda K\alpha = 0 factors through K (symmetric): (K + n\lambda I)\alpha = y, invertible since K \succeq 0.∎
KRR is to kernels what ridge is to the linear case — in infinite dimension but with only n active degrees of freedom. The SVM of chapter 3 is its “hinge” analogue: the representer theorem justifies a posteriori the form \theta = \sum_i\alpha_i y'_i \phi(x_i) obtained by duality.
The kernel trick — and its limit Replacing \langle x_i, x_j\rangle by k(x_i, x_j) in the SVM dual = working in an infinite-dimensional space without ever computing \phi (it suffices that k be directly computable: strings, graphs, sequences…).
Powerful, but costly in \mathcal{O}(n^2) memory and \mathcal{O}(n^3) computation: it is this dimensional limit that motivated deep learning (cf. Deep Learning module), which learns the representation \phi instead of fixing it.
6. Trees, forests, boosting
6.1. Decision trees (CART)
Recursive partition of \mathcal{X} by axis-aligned cuts (binary questions “x_j \leq t?”). At each leaf, one predicts the mean (regression) or the majority class (classification). Growth: at each node, choose (j, t) maximizing the impurity gain; then pruning to avoid overfitting. The exact impurity criteria, for a node D containing the classes in proportions p_1, \dots, p_K:
Definition 6.1 — Usual impurities \text{entropy: } H(D) = -\sum_{k=1}^K p_k \log_2 p_k, \qquad \text{Gini: } G(D) = 1 - \sum_{k=1}^K p_k^2 = \sum_k p_k(1 - p_k). In regression, one uses the squared error Q(D) = \frac{1}{|D|}\sum_{i \in D}(y_i - \bar y_D)^2. For a split D = D_L \cup D_R, the gain is \Delta(j, t) = I(D) - \frac{|D_L|}{|D|} I(D_L) - \frac{|D_R|}{|D|} I(D_R).
Gini and entropy are nearly interchangeable With two classes (p = p_1 = 1 - p_2): G(p) = 2p(1-p) and H(p) = -p\log_2 p - (1-p)\log_2(1-p).
Both are maximal at p = 1/2, zero at 0 and 1, and their expansion around 1/2 coincides to first order: H(p) = 1 - \frac{2}{\ln 2}(p - \tfrac12)^2 + o\big((p-\tfrac12)^2\big) \qquad\text{and}\qquad G(p) = \frac12 - 2(p - \tfrac12)^2.
CART uses Gini (no logarithm, direct computation); ID3/C4.5 use entropy (information gain). The choice is rarely decisive — pruning is. CART’s cost-complexity pruning minimizes R_\alpha(T) = R(T) + \alpha\,|\text{leaves}(T)| over the family of subtrees: yet another fit/complexity trade-off (chapter 8).
6.2. Random forests (bagging)
Theorem 6.2 — Bagging reduces variance Let T_1, \dots, T_B be predictors with the same variance \sigma^2, pairwise correlation \rho. The average A_B = \frac1B\sum_b T_b satisfies \mathrm{Var}(A_B) = \rho\,\sigma^2 + \frac{1 - \rho}{B}\,\sigma^2.
Proof. \mathrm{Var}(A_B) = \frac{1}{B^2}\big[\sum_b \mathrm{Var}(T_b) + \sum_{b \neq b'} \mathrm{Cov}(T_b, T_{b'})\big] = \frac{1}{B^2}\big[B\sigma^2 + B(B-1)\rho\sigma^2\big] = \frac{\sigma^2}{B} + \frac{B-1}{B}\rho\sigma^2, which rewrites as announced. iid case (\rho = 0, for example Gaussian variables with the same law): \mathrm{Var} = \sigma^2/B — divide the variance by B by averaging independent replicates.∎
Why it works so well for trees As B \to \infty, the residual variance tends toward the floor \rho\sigma^2: the whole art consists in lowering \rho. Random forests combine two mechanisms: (i) the bootstrap (resampling the rows); (ii) the random selection of m_{\text{try}} < d candidate variables at each split (decorrelation), which forces the trees to differ structurally. Unpruned trees have low bias and high variance — exactly the profile that bagging can correct.
Bonus: each tree leaves out on average e^{-1} \approx 37\% of the data (out-of-bag), so every example can be predicted by the trees that never saw it. This gives a free risk estimate, a cheap complement to the cross-validation of chapter 4 (oob_score=True in the code below). Forests remain a hard-to-beat tabular baseline.
6.3. Boosting: gradient descent in function space
Definition 6.3 — The functional problem One seeks f : \mathcal{X} \to \mathbb{R} minimizing \Phi(f) = \frac1n \sum_{i=1}^n \ell\big(f(x_i), y_i\big), where \ell(\hat y, y) is convex and differentiable in the prediction \hat y (quadratic, logistic…). One builds f as a sum f_M = \sum_{m=0}^M \eta\, h_m of simple functions (typically small trees), chosen one at a time — a stagewise additive model.
Theorem 6.4 — Boosting is functional gradient descent Assume f_{m-1} built and set g_i = \frac{\partial\, \ell}{\partial \hat y}(f_{m-1}(x_i), y_i) (pseudo-residuals, up to opposite sign). Then, to first order in \eta: \Phi(f_{m-1} + \eta h) = \Phi(f_{m-1}) - \frac{\eta}{n}\sum_{i=1}^n h(x_i)\,\underbrace{(-g_i)}_{\text{pseudo-residuals}} + o(\eta), so the direction h that lowers \Phi the most is the one aligned with the pseudo-residuals -g_i. Gradient boosting fits h_m by regression (trees) on the pairs (x_i, -g_i).
Proof. This is a Taylor expansion of the one-variable function s \mapsto \ell(f_{m-1}(x_i) + s\,h(x_i), y_i) around s = 0, summed over i and divided by n (with s = \eta): \ell(f_{m-1}(x_i) + \eta h(x_i), y_i) = \ell(f_{m-1}(x_i), y_i) + \eta\, h(x_i)\, \frac{\partial \ell}{\partial \hat y}(f_{m-1}(x_i), y_i) + o(\eta).
- Quadratic case \ell(\hat y, y) = \frac12(\hat y - y)^2: g_i = f_{m-1}(x_i) - y_i, hence -g_i = r_i := y_i - f_{m-1}(x_i) — the true residuals: each tree predicts the residuals of the previous ones. Here the second-order expansion is exact, with no further remainder: \Phi(f_{m-1} + \eta h) = \Phi(f_{m-1}) - \frac{\eta}{n}\sum_{i=1}^n h(x_i)\, r_i + \frac{\eta^2}{2n}\sum_{i=1}^n h(x_i)^2.
- Logistic case: the cross-entropy -y\log p - (1-y)\log(1-p) of the probability p = \sigma(\hat y), seen as a function of the score \hat y, has derivative \sigma(\hat y) - y (computation of chapter 3); pseudo-residuals y_i - p_i.∎
Learning rate and early stopping The step \eta (typically 0.01–0.1) is not the optimal descent constant: one gives up exact line search for a small step that (i) limits the variance of each tree, (ii) lets the following trees correct the previous ones — hence more iterations needed.
The number M of iterations plays the role of effective capacity: \Phi(f_M) decreases mechanically with M, but the generalization risk decreases then rises again. Early stopping (choosing M on validation) is the true regularization of boosting — same logic as the norm \|\theta\| in ridge (chapter 8): an increasing M corresponds to a growing dictionary of directions.
Friedman (2001) formalized this paradigm; XGBoost/LightGBM made it industrial (second order, leaf regularization, histograms); the M2 module “From Boosting to Foundation Models” starts from there.
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score
rf = RandomForestClassifier(n_estimators=300, min_samples_leaf=2, oob_score=True)
gbt = HistGradientBoostingClassifier(max_iter=300, learning_rate=0.06)
print(cross_val_score(rf, X, y, cv=5).mean(), cross_val_score(gbt, X, y, cv=5).mean())
print("forest OOB error:", 1 - rf.fit(X, y).oob_score_) # free validation6.4. Explaining tree ensembles
A forest of 300 trees cannot be read like one tree. When a decision must be justified (credit, health, the interpretability constraint of the course objectives), two questions come up: which features matter overall, and why this prediction for this example?
Global importance: impurity versus permutation. Forests report by default the mean decrease in impurity: the gains of definition 6.1, summed over the splits that use each feature. It is computed on the training data and favours features with many possible split points, such as continuous variables or identifiers, even when they are pure noise (Strobl and coauthors, 2007).
The permutation importance (Breiman, 2001) avoids this bias. On held-out data, shuffle one column, which breaks its link with the label, and measure the drop of the score. Two caveats remain: correlated features share their importance, since the model can use one in place of the other, and an importance describes the model, not a causal effect in the world.
Definition 6.5 — Shapley values Let f be a model with features \{1, \dots, d\} and x an example. For a set S of features, let v(S) be the expected prediction when the features in S are fixed to their values in the example and the others are drawn from the data. Thus v(\varnothing) = \mathbb{E}[f(X)], \qquad v(\{1, \dots, d\}) = f(x). The Shapley value of feature j averages its marginal contribution over all orders in which the features can arrive: \phi_j = \sum_{S \subseteq \{1,\dots,d\} \setminus \{j\}} \frac{|S|!\,(d - |S| - 1)!}{d!}\,\big[v(S \cup \{j\}) - v(S)\big].
Theorem 6.6 — The Shapley axioms (Shapley, 1953; statement) The Shapley values are the only attribution that satisfies the following four properties:
- efficiency: the attributions add up to the prediction minus the average prediction, \sum_{j=1}^d \phi_j = f(x) - \mathbb{E}[f(X)];
- symmetry: two features that bring the same contribution to every set S get the same value;
- dummy: a feature that never changes v gets the value 0;
- additivity: the values for a sum of models, such as the trees of a forest or of boosting, are the sums of the values.
For a linear model with independent features, the Shapley value is the familiar “coefficient times deviation”, \phi_j = \theta_j\,(x_j - \mathbb{E}[X_j]) (Exercise 15).
TreeSHAP. The sum of definition 6.5 has 2^{d-1} terms. For trees, however, the values v(S) can be estimated by walking down the tree with the training counts stored in its nodes. TreeSHAP (Lundberg and coauthors, 2020) computes the resulting Shapley values exactly, in time \mathcal{O}(T\,N_{\text{leaf}}\,D^2) for T trees with at most N_{\text{leaf}} leaves and depth D; additivity then sums them over the ensemble.
import shap # pip install shap
explainer = shap.TreeExplainer(gbt.fit(X_train, y_train))
phi = explainer.shap_values(X_test) # one row of attributions per test example
shap.summary_plot(phi, X_test) # global view: the spread of each feature's valuesAttribution methods for neural networks and LLMs (LIME, KernelSHAP, integrated gradients) are taught in Explainability, Security and Privacy of LLMs, ch. 4.
7. Unsupervised: k-means, EM, PCA
7.1. k-means
Definition 7.1 — Criterion and Lloyd’s algorithm For a partition C_1, \dots, C_K and centers \mu_1, \dots, \mu_K, one minimizes W(C, \mu) = \sum_{k=1}^K \sum_{i \in C_k} \|x_i - \mu_k\|^2 by alternating: (i) reassigning each point to the nearest centroid, (ii) recentering the centroids. Complexity \mathcal{O}(n\,k\,d\,T) for T iterations.
Theorem 7.2 — Convergence of Lloyd Lloyd’s algorithm terminates in a finite number of iterations, at a stationary point of W (a local minimum, not necessarily global).
Proof. Step (ii). With the partition fixed, the best center of a cluster S is its barycenter: by Huygens’ identity (expand the square, the cross term cancels), \sum_{i \in S}\|x_i - \mu\|^2 = \sum_{i \in S}\|x_i - \bar x_S\|^2 + |S|\,\|\mu - \bar x_S\|^2 \ \geq\ \sum_{i \in S}\|x_i - \bar x_S\|^2. So (ii) cannot increase W, and strictly decreases it if a center was not at the barycenter.
Step (i). With the centers fixed, each point x_i contributes \min_k \|x_i - \mu_k\|^2: reassignment to the nearest cannot increase W, and strictly decreases it as soon as one point changes cluster for a closer center.
Conclusion. W is decreasing, bounded below by 0; since there are only k^n partitions and as many associated center configurations, W can strictly decrease only finitely many times — the algorithm reaches a configuration where nothing moves: a stationary point.∎
Proposition 7.3 — k-means++ and its guarantee k-means++ initialization: choose \mu_1 uniformly; then choose x as the next center with probability proportional to D(x)^2 (squared distance to the nearest center). Arthur and Vassilvitskii (2007) show \mathbb{E}\big[W_{\text{k-means++}}\big] \leq 8\,(\ln k + 2)\, W^\star, where W^\star is the global optimum — an \mathcal{O}(\log k) guarantee, optimal in general.
Idea of the proof: at each draw, the probability of falling in a “costly” cluster (high mass × high cost) is at least proportional to its cost; as long as a cluster is poorly covered, its cost keeps a fixed chance of being reduced; one “covers” all the clusters after an expected \mathcal{O}(\log k) effective draws, each coverage reduces the cost by a geometric factor via the triangle inequality.
In practice: run k-means++ several times and keep the best W.
Choosing K The criterion W always decreases when K grows, down to W = 0 at K = n, so it cannot choose K alone; the elbow of the curve K \mapsto W is only a visual hint. Two criteria are more principled.
- The silhouette of a point i compares its mean distance a_i to the other points of its cluster with its mean distance b_i to the points of the nearest other cluster: s_i = \frac{b_i - a_i}{\max(a_i, b_i)} \in [-1, 1]. One keeps the K with the largest mean silhouette.
- For a Gaussian mixture (7.2), the Bayesian information criterion penalizes the maximized log-likelihood by the number m_K of free parameters: \mathrm{BIC}(K) = -2\log \hat p_K(x_1, \dots, x_n) + m_K \log n. One keeps the K with the smallest BIC. With full covariances in dimension d, m_K = (K - 1) + Kd + Kd(d+1)/2.
Beyond k-means: hierarchical and density-based clustering. k-means looks for K compact clusters of similar spread. Single-linkage clustering starts from n singletons and repeatedly merges the two clusters whose closest points are closest. The merge heights form a dendrogram, and cutting it at a height gives a partition at that scale.
Its merges are the edges of a minimum spanning tree, which makes it fast but prone to chaining through a few intermediate points. It is also the 0-dimensional persistence of the Topological Data Analysis module.
DBSCAN (Ester, Kriegel, Sander and Xu, 1996) needs a radius \varepsilon and a count m. A point with at least m neighbours within \varepsilon is a core point; clusters are the connected groups of core points with their neighbours, and the remaining points are labelled noise. DBSCAN finds clusters of any shape and chooses their number itself, but a single \varepsilon fits poorly when the densities differ.
7.2. Gaussian mixtures and EM
Model 7.4 — GMM p(x) = \sum_{k=1}^K \pi_k \, \varphi(x ; \mu_k, \Sigma_k), \qquad \pi_k \geq 0, \sum_k \pi_k = 1, with latent variable Z \in \{1, \dots, K\} with law \pi, X \mid Z = k \sim \mathcal{N}(\mu_k, \Sigma_k).
Theorem 7.5 — EM increases the log-likelihood For any law q on Z and any \theta, define the evidence lower bound \mathrm{ELBO}(q, \theta) = \mathbb{E}_q\big[\log p_\theta(x, Z)\big] + H(q), \qquad H(q) = -\mathbb{E}_q[\log q(Z)], where H(q) is the entropy of definition 0.7. Then: \log p_\theta(x) = \mathrm{ELBO}(q, \theta) + \mathrm{KL}\big(q \,\|\, p_\theta(\cdot \mid x)\big) \ \geq\ \mathrm{ELBO}(q, \theta). It follows that the EM algorithm — E-step: q_t = p_{\theta_t}(\cdot\mid x); M-step: \theta_{t+1} \in \arg\max_\theta \mathrm{ELBO}(q_t, \theta) — satisfies \log p_{\theta_{t+1}}(x) \geq \log p_{\theta_t}(x), with equality iff at a stationary point.
Proof. Decomposition. Start from \log p_\theta(x) = \mathbb{E}_q\big[\log p_\theta(x)\big] (a constant for q) and add-subtract \mathbb{E}_q[\log q(Z)]: \log p_\theta(x) - \mathrm{ELBO}(q,\theta) = \mathbb{E}_q\Big[\log \frac{q(Z)}{p_\theta(Z \mid x)}\Big] = \mathrm{KL}\big(q \,\|\, p_\theta(\cdot \mid x)\big) \ \geq\ 0 (Kullback-Leibler divergence, nonnegative by proposition 0.8).
E-step. With \theta = \theta_t fixed, the minimum over q of q \mapsto \mathrm{KL}\big(q \,\|\, p_{\theta_t}(\cdot\mid x)\big) is reached at q = p_{\theta_t}(\cdot\mid x), where the KL is zero: thus \mathrm{ELBO}(q_t, \theta_t) = \log p_{\theta_t}(x), the bound is tight.
M-step. \log p_{\theta_{t+1}}(x) \geq \mathrm{ELBO}(q_t, \theta_{t+1}) \geq \mathrm{ELBO}(q_t, \theta_t) = \log p_{\theta_t}(x) — the log-likelihood can only increase. Strict increase occurs as long as the M-step improves the ELBO.∎
EM for GMMs, explicit formulas
- E-step: compute the responsibilities \gamma_{ik} = \mathbb{P}(z_i = k \mid x_i) \propto \pi_k \varphi(x_i;\mu_k,\Sigma_k) (normalized over k).
- M-step: maximizing \mathrm{ELBO}(q_t, \cdot) (equivalent to a weighted complete likelihood) gives \pi_k = \frac1n\sum_i \gamma_{ik}, \qquad \mu_k = \frac{\sum_i \gamma_{ik} x_i}{\sum_i \gamma_{ik}}, \qquad \Sigma_k = \frac{\sum_i \gamma_{ik}(x_i - \mu_k)(x_i - \mu_k)^\top}{\sum_i \gamma_{ik}}.
In practice: initialize with k-means, constrain \Sigma_k diagonal if d is large, beware of singularities (variance \to 0). EM reappears in hidden Markov models, where the E-step is the forward–backward algorithm and EM is called Baum–Welch (Text Mining & NLP, ch. 6); in VAEs (Deep Learning module), which maximize the same ELBO with a neural q; in probabilistic PCA below; and in graph clustering (stochastic block models, Graph ML module).
7.3. Principal component analysis
Theorem 7.6 — PCA: the two viewpoints are equivalent Let X be the centered matrix (n rows, columns of zero mean) and \hat\Sigma = \tfrac1n X^\top X. The following two problems have the same solutions — the eigenvectors v_1, \dots, v_k of \hat\Sigma associated with the k largest eigenvalues:
- (P1) maximum variance (solved successively under v \perp v_1, \dots): \max \big\{\mathrm{Var}(Xv) : \|v\| = 1\big\} = \max\, v^\top\hat\Sigma v;
- (P2) minimal reconstruction error, with P_V the orthogonal projection: \min \big\{\sum_i \|x_i - P_V x_i\|^2 : \dim V = k\big\}.
Proof. Rayleigh lemma. Diagonalize \hat\Sigma = Q\Lambda Q^\top with \lambda_1 \geq \lambda_2 \geq \dots. For \|v\| = 1, v^\top\hat\Sigma v = \sum_j \lambda_j c_j^2 \leq \lambda_1 \sum_j c_j^2 = \lambda_1, reached at v = v_1; on the orthogonal of v_1, same argument with \lambda_2, etc. This is (P1).
Equivalence. For V with orthonormal basis v_1, \dots, v_k, the projection is a sum of orthogonal projections: P_V x = \sum_j \langle v_j, x\rangle v_j and \|P_V x\|^2 = \sum_j \langle v_j, x\rangle^2 (Pythagoras). Hence \sum_i \|x_i - P_V x_i\|^2 = \sum_i \|x_i\|^2 - \sum_{j=1}^k v_j^\top \hat\Sigma\, v_j\; n = \text{const.} - n\sum_j v_j^\top\hat\Sigma v_j. Minimizing the reconstruction error ⟺ maximizing the sum of the Rayleigh quotients — solved by the same v_1, \dots, v_k (P1).∎
SVD. For X = U\Sigma V^\top (singular value decomposition of the centered matrix), X^\top X = V\Sigma^2V^\top: components = columns of V, scores Z = U\Sigma, variance explained by component j = \sigma_j^2 \big/ \sum_l \sigma_l^2.
The choice of k (elbow, cumulative variance) is yet another capacity choice — cf. chapter 8.
Probabilistic PCA (PPCA, Tipping & Bishop 1999) Latent variable model: Z \sim \mathcal{N}(0, I_k), X = WZ + \mu + \varepsilon, \varepsilon \sim \mathcal{N}(0, \sigma^2 I_d).
The maximum likelihood is reached at \hat\mu = \bar x and \hat W whose spanned space is that of the first k principal components (up to a rotation; the columns are \sqrt{\lambda_j - \hat\sigma^2}\, v_j), with \hat\sigma^2 = mean of the neglected eigenvalues.
Classical PCA is therefore the limit \sigma^2 \to 0 of a generative model; in return, PPCA provides a likelihood (model comparison!), an EM for missing data, and mixtures of subspaces. (The complete proof — integrating the marginal law p(x) = \mathcal{N}(\mu, WW^\top + \sigma^2 I) and maximizing — is an excellent exercise; it can be found in the original paper.)
import numpy as np
Xc = X - X.mean(0)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
Z = Xc @ Vt[:2].T # 2D projection
var_explained = (S**2 / (S**2).sum())[:10] # variance explained per componentSpectral PCA → graphs PCA on the adjacency matrix/Laplacian of a graph (spectral clustering) is the historical link between classical ML and Graph ML: we will do it again on the Laplacian L = D - A (degree matrix minus adjacency matrix) in the Graph ML module.
t-SNE and UMAP: pictures, not measurements PCA is linear: it keeps the large distances and can miss curved structure. Nonlinear embeddings such as t-SNE (van der Maaten and Hinton, 2008) and UMAP (McInnes, Healy and Melville, 2018) preserve neighbourhoods instead and draw clearer clusters in 2D, but their pictures are easy to over-read:
- the sizes of the clusters and the distances between them carry little meaning;
- the picture changes with the perplexity (t-SNE) or the number of neighbours (UMAP), and with the random seed, so compare several settings before concluding;
- at small perplexity, apparent clusters can appear in pure noise;
- use them to look at data, not as features for a model or as evidence for a claim. A PCA to about 50 dimensions first is the usual preprocessing.
8. Generalization theory
This chapter justifies mathematically what precedes: when and why does empirical risk minimization generalize? It is also the starting point of the Statistical Learning Theory notes, kept for reference (that course is not in the LLGA list), and the reading grid for all the hyperparameters of the course (regularization, margin, tree depth, number of boosting iterations).
8.1. Why uniform convergence is necessary
Proposition 8.1 — The estimation gap is controlled by the supremum Let f_\mathcal{F} \in \arg\min_{f \in \mathcal{F}} \mathcal{R}(f). Then \mathcal{R}(\hat f_n) - \mathcal{R}(f_\mathcal{F}) \ \leq\ 2\, \sup_{f \in \mathcal{F}}\ \big|\, \hat{\mathcal{R}}_n(f) - \mathcal{R}(f) \,\big|.
Proof. Interleave the empirical risk: \mathcal{R}(\hat f_n) - \mathcal{R}(f_\mathcal{F}) = \big[\mathcal{R}(\hat f_n) - \hat{\mathcal{R}}_n(\hat f_n)\big] + \big[\hat{\mathcal{R}}_n(\hat f_n) - \hat{\mathcal{R}}_n(f_\mathcal{F})\big] + \big[\hat{\mathcal{R}}_n(f_\mathcal{F}) - \mathcal{R}(f_\mathcal{F})\big]. The middle term is \leq 0 (definition of ERM); the other two are bounded by the supremum.∎
Example 8.2 — When pointwise convergence is not enough: the sinusoids Take \mathcal{X} = [0, 2\pi], with X drawn from a density and a label Y \in \{-1, +1\} drawn uniformly and independently of X (pure noise). Consider the class \mathcal{F} = \{x \mapsto \mathrm{sign}(\sin(\omega x)) : \omega > 0\}. For a fixed f, the label is a fair coin whatever f predicts, so \mathcal{R}(f) = 1/2.
Yet this one-parameter class fits almost every sample perfectly. With probability 1, the sample points x_1, \dots, x_n are linearly independent over the rationals. Kronecker’s theorem then says that the points (\omega x_1, \dots, \omega x_n) taken modulo 2\pi, for \omega > 0, are dense in the torus.
So some \omega puts each \omega x_i modulo 2\pi in the half-period that has the sign y_i, whatever the labels.
Not every sample is shattered: the points 1, 2, 3, 4 cannot carry the labels (+, +, -, +), whatever \omega (Burges, 1998). But the points x_i = 10^{-i} are shattered for every n: the labels y are realized by \omega = \pi\Big(1 + \sum_{i=1}^n \frac{1 - y_i}{2}\,10^i\Big).
ERM therefore reaches \hat{\mathcal{R}}_n = 0 almost surely, whereas every f has risk 1/2. Hoeffding (theorem 0.3) holds for each fixed f, but the supremum of the gap over \mathcal{F} equals 1/2. Without uniform control, learning proves nothing.
8.2. Vapnik-Chervonenkis dimension
Definition 8.3 — Shattering and VC dimension A class \mathcal{F} of classifiers shatters the points x_1, \dots, x_n if every label of \{-1,+1\}^n is realizable by some f \in \mathcal{F}. The growth function is \Pi_\mathcal{F}(n) = \max_{x_1, \dots, x_n} \#\{(\mathrm{sign}\,f(x_1), \dots, \mathrm{sign}\,f(x_n)) : f \in \mathcal{F}\}. The VC dimension is d_{\mathrm{VC}} = \max\{n : \Pi_\mathcal{F}(n) = 2^n\} (possibly +\infty).
Examples 8.4 — Three VC dimensions computed by hand
- (i) Thresholds on \mathbb{R}, f_t = \mathbf{1}\{x \leq t\}: d_{\mathrm{VC}} = 1. One point is shattered (t before/after). Two points x_1 < x_2 are not: the label (0, 1) would require x_1 > t and x_2 \leq t, impossible.
- (ii) Intervals f_{a,b} = \mathbf{1}\{x \in [a, b]\}: d_{\mathrm{VC}} = 2. Two points: all labels (via an empty [a,b], enclosing, or exactly fitted); three points x_1 < x_2 < x_3: the label (1, 0, 1) is unrealizable (an interval containing x_1, x_3 contains x_2).
- (iii) Affine hyperplanes in \mathbb{R}^d: d_{\mathrm{VC}} = d + 1. The d+1 vertices of a simplex are shattered (to each vertex associate the hyperplane through the opposite face); d + 2 points never are — this is Radon’s theorem: any family of d+2 points can be partitioned into two subsets with intersecting convex hulls, and no hyperplane can separate this partition.
- (iv) Example 8.2 shows a class of infinite VC dimension (the points 10^{-i} are shattered for every n) — which learns nothing.
Lemma 8.5 — Sauer-Shelah lemma (statement) If d_{\mathrm{VC}}(\mathcal{F}) = d, then for every n \geq d, \Pi_\mathcal{F}(n) \ \leq\ \sum_{i=0}^{d} \binom{n}{i} \ \leq\ \Big(\frac{e\,n}{d}\Big)^{d}. Intuition: a class of dimension d can realize only labels “determined” by at most d points — the growth is polynomial of degree d in n, not exponential. (Proof by induction on n + d, exercise; cf. Shalev-Shwartz & Ben-David, ch. 7.)
8.3. The VC bound by double sampling (sketch)
Theorem 8.6 — Vapnik-Chervonenkis bound With probability at least 1 - \delta over the sample, simultaneously for every f \in \mathcal{F} (loss in [0,1], VC dimension d, n \geq d): \mathcal{R}(f) \ \leq\ \hat{\mathcal{R}}_n(f) + \sqrt{\frac{8\,\big(d \log \tfrac{2 e n}{d} + \log \tfrac{4}{\delta}\big)}{n}}.
Proof. Sketch in three moves — the Vapnik-Chervonenkis double-sampling argument.
Ghost sample. Draw 2n iid points and split into two halves S, S' with empirical risks \hat R_S, \hat R_{S'}. By Hoeffding (theorem 0.3), each is within \varepsilon/4 of \mathcal{R} with high probability.
Consequently, if some f commits \hat{\mathcal{R}}_S(f) + \varepsilon \leq \mathcal{R}(f), then \hat R_S(f) and \hat R_{S'}(f) differ by at least \varepsilon/2: we have replaced the unobservable risk \mathcal{R} by a second observable sample.
Symmetrization by permutations. Conditionally on the 2n points, the labels f(x_i) of a given f take only \Pi_\mathcal{F}(2n) values.
By randomly swapping the roles S \leftrightarrow S' (random permutation), the probability that a better f of the class separates the two halves by \varepsilon/2 is bounded by 2\,\Pi_\mathcal{F}(2n)\, e^{-n\varepsilon^2/8}: a simple counting over the \Pi_\mathcal{F}(2n) distinct behaviors, each subject to a binomial Hoeffding.
Sauer. Bound \Pi_\mathcal{F}(2n) \leq (2en/d)^d, solve in \varepsilon the inequality (2en/d)^d e^{-n\varepsilon^2/8} \leq \delta: this is the announced square root.∎
Reading the bound The excess risk is \mathcal{O}\big(\sqrt{d/n}\,\big) up to logarithmic constants: to divide the error by two, one needs four times more data — or a class four times smaller. Practical rules: (i) n \gg d is the healthy regime; (ii) capacity control (reduce the effective d by regularization, margin, sparsity) pays as much as more data; (iii) the bound is conservative — it explains, it does not predict exact performance.
8.4. Rademacher complexity
Definition 8.7 — Empirical Rademacher complexity For a sample S = (x_1, \dots, x_n) and iid Rademacher variables \sigma_i uniform on \{-1, +1\}: \hat{\mathcal{R}}_S(\mathcal{F}) = \mathbb{E}_\sigma\Big[\sup_{f \in \mathcal{F}} \frac1n \sum_{i=1}^n \sigma_i f(x_i)\Big]. This is the capacity of \mathcal{F} to “fit the noise”: if a class can align itself with purely random labels, it will also memorize your data.
Lemma 8.8 — McDiarmid’s bounded-differences inequality (statement) Let Z_1, \dots, Z_n be independent, and let \Psi be a function such that changing its i-th argument alone changes its value by at most c_i. Then, for every t > 0, \mathbb{P}\big(\Psi(Z_1, \dots, Z_n) - \mathbb{E}\,\Psi \geq t\big) \leq \exp\Big(-\frac{2t^2}{\sum_i c_i^2}\Big). Hoeffding’s inequality is the case of a sum. For a loss in [0, 1], the worst gap \sup_{f} (\mathcal{R}(f) - \hat{\mathcal{R}}_n(f)) has c_i = 1/n, so with probability at least 1 - \delta it exceeds its mean by at most \sqrt{\log(1/\delta)/(2n)}. (Proof: Boucheron, Lugosi and Massart, 2013, section 6.1.)
Lemma 8.9 — Contraction (Ledoux–Talagrand; statement) If \varphi_1, \dots, \varphi_n : \mathbb{R} \to \mathbb{R} are L-Lipschitz, then for every class \mathcal{F} and sample S, \mathbb{E}_\sigma \sup_{f \in \mathcal{F}} \frac1n\sum_{i=1}^n \sigma_i\, \varphi_i\big(f(x_i)\big) \leq L\, \hat{\mathcal{R}}_S(\mathcal{F}). With \varphi_i(u) = \ell(u, y_i), the loss class is at most L times as complex as \mathcal{F}. (Proof: Mohri, Rostamizadeh and Talwalkar, 2018, lemma 5.7.)
Theorem 8.10 — Oracle bound via Rademacher Let the loss take values in [0, 1] and be L-Lipschitz in the prediction, and let \hat f_n be an empirical risk minimizer. With probability \geq 1 - \delta: \mathcal{R}(\hat f_n) \ \leq\ \inf_{f \in \mathcal{F}} \mathcal{R}(f) + 2\, L\, \mathbb{E}_S\big[\hat{\mathcal{R}}_S(\mathcal{F})\big] + \sqrt{\frac{2\log(2/\delta)}{n}}, and for bounded linear classes \mathcal{F}_R = \{x \mapsto \langle\theta, x\rangle : \|\theta\| \leq R, \|x\| \leq 1\}: \hat{\mathcal{R}}_S(\mathcal{F}_R) \leq R/\sqrt n (computation of theorem 3.6).
Sketch.
- (i) As in proposition 8.1, with f_\mathcal{F} a minimizer of the risk over \mathcal{F} and since the middle term is \leq 0, \mathcal{R}(\hat f_n) - \mathcal{R}(f_\mathcal{F}) \leq \sup_{f \in \mathcal{F}}\big(\mathcal{R}(f) - \hat{\mathcal{R}}_n(f)\big) + \big(\hat{\mathcal{R}}_n(f_\mathcal{F}) - \mathcal{R}(f_\mathcal{F})\big).
- (ii) Symmetrization by a ghost sample (as in 8.3, without counting this time) bounds the mean of the supremum by twice the Rademacher complexity of the loss class, and the contraction lemma 8.9 bounds that by 2L\,\mathbb{E}_S[\hat{\mathcal{R}}_S(\mathcal{F})].
- (iii) Two deviations remain, each at level \delta/2: McDiarmid (lemma 8.8) for the supremum, and Hoeffding for the fixed f_\mathcal{F}. Each adds \sqrt{\log(2/\delta)/(2n)}, and the two add up to the last term.∎
Rademacher versus VC: the Rademacher complexity is data-dependent (it is computed on the sample, by simulating the \sigma_i), without a logarithmic factor, and applies to continuous classes of real-valued functions (scores, margins). It is the standard tool of modern bounds — including the SVM margin bounds (theorem 3.6) and the aggregation bounds of chapter 9.
8.5. Regularizing = controlling capacity
Why this is central in ML Reread the course:
- ridge and lasso constrain \|\theta\| — and the norm-R ball has Rademacher complexity R/\sqrt n (theorem 8.10);
- the SVM maximizes the margin \gamma, which divides the complexity by \gamma (theorem 3.6);
- boosting stops early, limiting the effective size of the tree dictionary;
- tree pruning (6.1) and rank selection in PCA (7.3) do the same.
This is structural risk minimization: a scale of nested classes \mathcal{F}_1 \subset \mathcal{F}_2 \subset \cdots, each with its complexity \mathcal{R}_n(\mathcal{F}_j), and a trade-off tuned on data \hat{\mathcal{R}}_n(f) + \text{complexity}. The “lambda” you tune in the labs is exactly this theory-practice slider.
9. Research at CMAP and LIX (Le Pennec, Read)
At École Polytechnique, two research lines extend this module directly: multi-label classification (Jesse Read, LIX) and estimator aggregation (Erwan Le Pennec, CMAP). Two topics where the previous chapters reappear — and gateways to internships / PhD topics.
9.1. Jesse Read: learning sets of labels (multi-label, streams, extreme)
Definition 9.1 — Multi-label problem Each example x is associated with a set of labels Y \subseteq \{1, \dots, L\}, viewed as a vector of \{0,1\}^L. One learns h : \mathcal{X} \to \{0,1\}^L. Usual losses: Hamming (error rate per label, \frac1L\sum_j \mathbf{1}\{h_j(x) \neq y_j\}) and subset accuracy (subset accuracy: the whole vector must be correct). Applications: text tagging, genomics, recommendation — cf. the running project (exercise 18) and the NLP module.
The taxonomy popularized by Jesse Read’s thesis (Scalable Multi-label Classification, Waikato, 2010) and by the classifier chains paper separates methods into two families: problem transformation (bring multi-label back to standard binary/multiclass problems) and algorithm adaptation (modify kNN, trees, SVMs… to directly ingest label vectors). Three canonical transformations:
| Method | Principle | Strength / weakness |
|---|---|---|
| Binary Relevance (BR) | L independent binary classifiers h_j(x) | simple, parallelizable; ignores dependencies between labels |
| Label Powerset (LP) | each observed combination = one class of a single multiclass problem | captures all dependencies; explosion of rare classes (\leq 2^L) |
| Classifier Chains (CC) | h_j predicts y_j from (x, y_1, \dots, y_{j-1}) | captures conditional dependencies; sensitive to order and to cascading errors |
Example 9.2 — Classifier chains on a mini-corpus Three labels: S (science), P (politics), s (health). Corpus:
| Document | S | P | s |
|---|---|---|---|
| article 1 (climate) | 1 | 0 | 1 |
| article 2 (election) | 0 | 1 | 0 |
| article 3 (research budget) | 1 | 1 | 0 |
| article 4 (sports) | 0 | 0 | 0 |
The pattern “S = 1, P = 0 \Rightarrow s = 1” (non-politicized science articles: health) is invisible to BR, each of whose binary classifiers sees only x. For a chain of order (S, P, s), the last link learns h_s(x, S, P) — the dependency becomes a simple additional feature, and the classifier of chapter 3 applies as is.
At prediction time, one propagates: \hat S = h_S(x), then \hat P = h_P(x, \hat S), then \hat s = h_s(x, \hat S, \hat P).
Two remedies to the arbitrary order and to cascading error: ensembles of chains (random orders, average vote — the bagging of chapter 6, again) and the probabilistic route (predict the expectation over the 2^L paths or sample).
From multi-label to massive data: streaming and extreme Three extensions carried by Jesse Read and his co-authors, which join chapter 4:
- (i) Multi-label streams (Read, Bifet, Pfahringer, Holmes, Scalable and Efficient Multi-label Classification for Evolving Data Streams, Machine Learning, 2012): data arrive continuously, a single pass, bounded memory — one learns incremental multi-output regression trees (iSOUP-Tree) and one predicts score vectors label by label. Concept drift is treated there as a temporal structure: Concept-drifting data streams are time series (arXiv:1810.02266).
- (ii) Extreme classification: L on the order of 10^5 to 10^6 (labels = Wikipedia articles, listings); BR (one-vs-rest) becomes relevant again because label embeddings factorize the sparse matrix — reviewed in Deep Learning for Multi-label Classification (arXiv:1502.05988).
- (iii) Tools: the River library — machine learning for streams in Python (Montiel, Halford, Salles, …, Read et al., JMLR 22(110), 2021) implements these methods; the meta-challenge there is the evaluation protocol (prequential, sliding window), cf. Refresher CS module for the engineering.
9.2. Erwan Le Pennec: aggregating estimators rather than choosing one
Facing a family f_1, \dots, f_M of candidate estimators (different kernels, different wavelet bases, different values of \lambda…), the classical statistician selects one. The alternative carried by Erwan Le Pennec and his co-authors is to aggregate them: predict with a weighted combination f_{\hat\pi} = \sum_m \hat\pi_m f_m, the weights being learned from data — typically exponential weights (Gibbs measure):
Key result — exponential weights \hat\pi_m \ \propto\ \exp\big(-\eta\, n\, \hat{\mathcal{R}}_n(f_m)\big), \qquad \sum_m \hat\pi_m = 1.
Here \eta > 0 is an inverse temperature. The risk of the aggregate is then controlled by an oracle inequality: pay the price of the best candidate up to a \log M term, with no assumption on which one is best.
Example 9.3 — Two estimators, exponential weights M = 2, empirical risks \hat{\mathcal{R}}_n(f_1) = 0.30 and \hat{\mathcal{R}}_n(f_2) = 0.38, n = 100, \eta = 1: \hat\pi_1/\hat\pi_2 = \exp\big(n\eta(0.38 - 0.30)\big) = e^{8} \approx 3000; the aggregate ≈ f_1. With n = 10: ratio e^{0.8} \approx 2.2, an almost uniform mixture.
Moral: \eta tunes the selectivity according to the amount of data — exactly the role of the inverse temperature in Gibbs mechanisms, and we recover the softmax formula of chapter 3. If a third candidate emerges on fresh data, the aggregate will rebalance — a robustness that a hard selection (argmin) does not have.
Typical result (Montuelle & Le Pennec, 2014/2019) In the fixed-design regression model, for a generic collection of linear estimators (projections, ridge, thresholding algorithms, wavelet thresholding estimators…), the PAC-Bayesian aggregation procedure with exponential weights satisfies an oracle inequality in probability: with probability 1 - \delta, the risk of the aggregate is less than the risk of the best estimator of the collection plus an explicit remainder in \sqrt{\log(M/\delta)/n}.
The guarantee holds no longer only in expectation: the in-probability guarantee, a finer one, is the specific contribution of this work (long version: PAC-Bayesian aggregation of linear estimators, Nonparametric Statistics, 2019; preprint arXiv:1410.0661). Aggregation is robust to the worst case: one never bets on a single candidate.
Connection with the rest of the course The guiding thread is the same:
- bagging (theorem 6.2) = aggregation with uniform weights of bootstrap versions of one estimator;
- boosting (6.3) = iterative construction of the dictionary, each tree receiving a weight;
- exponential weights = the update mechanism of AdaBoost and Gibbs algorithms;
- regularization (8.5) = why the aggregate generalizes better than the best empirical candidate.
On this last point, Erwan Le Pennec’s nonparametric statistics provides the guardrails: optimal kernel selection for density estimation, needlet thresholding for models with random coefficients (with É. Gautier), estimation of copula densities by thresholding (with F. Autin and K. Tribouley, 2010) — always the same grammar: a dictionary, a penalty, an oracle inequality. NL-Means image denoising can be reread this way as a local aggregation of kernel estimators (Salmon & Le Pennec, 2009).
Exercises
★ Closed-form ridge. Show that \hat\theta_{\text{ridge}} is indeed given by (X^\top X + n\lambda I)^{-1}X^\top y by setting the gradient to zero, then that the problem is always strictly convex as soon as \lambda > 0.
Proof. Solution Gradient: \nabla_\theta\big(\tfrac1n\|y - X\theta\|^2 + \lambda\|\theta\|_2^2\big) = \tfrac2n X^\top(X\theta - y) + 2\lambda\theta; setting it to zero gives (X^\top X + n\lambda I)\theta = X^\top y.
The Hessian \tfrac2n(X^\top X + n\lambda I) \succeq 2\lambda I \succ 0 is positive definite for \lambda > 0, even if X^\top X is singular: unique global minimum — this is the first practical benefit of regularization (cf. proposition 2.5 for the spectral reading).∎
★ Gauss-Markov in dimension 1. Model y_i = \theta + \varepsilon_i, \varepsilon_i centered, independent, with variance \sigma^2. Show that among the linear unbiased estimators a^\top y of \theta, the empirical mean has minimal variance.
Proof. Solution Unbiasedness: \mathbb{E}[a^\top y] = \theta\,\textstyle\sum_i a_i = \theta for every \theta, hence \sum_i a_i = 1. Variance: \mathrm{Var}(a^\top y) = \sigma^2\|a\|^2.
Minimizing \|a\|^2 under the constraint \mathbf{1}^\top a = 1 (Lagrange multipliers, example 0.12 of section 0.4) gives the uniform a_i = 1/n. This is the case X = \mathbf 1 of theorem 2.3; the estimator \frac1n\sum y_i is its geometric projection.∎
★ Cross-entropy. Verify that minimizing the logistic cross-entropy amounts to maximizing the Bernoulli likelihood \prod_i \sigma(\theta^\top x_i)^{y_i}(1-\sigma)^{1-y_i}, and compute \nabla_\theta \hat{\mathcal{R}}_n = \frac1n X^\top(\sigma(X\theta) - y). (All the steps are in theorem 3.3: redo them without notes.)
★ Bagging and correlation. Derive again the formula \mathrm{Var}(A_B) = \rho\sigma^2 + \tfrac{1-\rho}{B}\sigma^2 of theorem 6.2, then comment: what happens if the B trees are identical (\rho = 1)? Why does a small m_{\text{try}} decrease \rho — and at what price?
Proof. Solution Expand the variance of the sum with equicorrelated covariances \tfrac1{B^2}[B\sigma^2 + B(B-1)\rho\sigma^2]. If \rho = 1, all the trees are identical: the variance remains \sigma^2, bagging is useless. Reducing m_{\text{try}} randomizes the candidate splits and decorrelates the trees; in exchange, each tree, seeing fewer variables, may miss the “right” split — its individual bias increases slightly. The optimal trade-off is found by validation (chapter 4).∎
★ Entropy and the two KL divergences. Write B_p for the Bernoulli distribution of parameter p. Compute in nats the entropy H(B_{0.9}) and the two divergences \mathrm{KL}(B_{0.5} \,\|\, B_{0.9}) and \mathrm{KL}(B_{0.9} \,\|\, B_{0.5}). Then check proposition 0.8(ii) on the pair (B_{0.9}, B_{0.5}).
Proof. Solution The entropy is H(B_{0.9}) = -0.9\ln 0.9 - 0.1\ln 0.1 \approx 0.095 + 0.230 = 0.325. The two divergences differ, since KL is not symmetric: \mathrm{KL}(B_{0.5} \,\|\, B_{0.9}) = 0.5\ln\tfrac{0.5}{0.9} + 0.5\ln\tfrac{0.5}{0.1} \approx 0.511, \qquad \mathrm{KL}(B_{0.9} \,\|\, B_{0.5}) = 0.9\ln 1.8 + 0.1\ln 0.2 \approx 0.368. Check: H(B_{0.9}, B_{0.5}) = -\ln 0.5 = \ln 2 \approx 0.693, and indeed 0.325 + 0.368 = 0.693.∎
★ PCA by hand. Centred data in \mathbb{R}^2 have the empirical covariance \hat\Sigma = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}. Find the principal components, the share of variance explained by the first one, and the mean squared reconstruction error of the projection on it (theorem 7.6).
Proof. Solution The characteristic polynomial (2 - \lambda)^2 - 1 has the roots 3 and 1, with eigenvectors v_1 = (1, 1)/\sqrt2 and v_2 = (1, -1)/\sqrt2.
The first component explains 3/(3 + 1) = 75\% of the variance. By the identity in the proof of theorem 7.6, the mean squared reconstruction error is the total variance \mathrm{tr}\,\hat\Sigma = 4 minus the explained part 3, that is 1 = \lambda_2.∎
★ Is the new model better? Two classifiers are evaluated on the same 1000 test examples. A is right on 870 of them; where they disagree, A alone is right 15 times and B alone 30 times. (i) Give the Clopper–Pearson 95 % interval for the accuracy of A. (ii) Apply McNemar’s test at 5 %. (iii) This comparison was the best of ten datasets that were tried: what changes? (section 4.9)
Proof. Solution (i) The Beta quantiles (
scipy.stats.beta.ppf) give [0.848, 0.890]. B is right on 870 - 15 + 30 = 885 examples.(ii) With n_{01} = 15 and n_{10} = 30, \chi^2 = \frac{(|15 - 30| - 1)^2}{45} = \frac{196}{45} \approx 4.36 > 3.84, so B is significantly better at 5 % (p \approx 0.037; the exact binomial test gives 0.036).
(iii) With ten comparisons, Bonferroni asks for p < 0.005: the gain is no longer significant. Reporting only the best dataset is a selection effect, the trap of Example 4.3.∎
★★ Kernel duel. (i) Show that k(x, x') = (\langle x, x'\rangle + 1)^2 on \mathcal{X} = \mathbb{R}^2 is a kernel by exhibiting an explicit feature map. (ii) Is the function k(x,x') = \cos(x - x') on \mathbb{R} a positive definite kernel?
Proof. Solution (i) Expand: (x_1x'_1 + x_2x'_2 + 1)^2 = x_1^2x_1'^2 + 2x_1x_1'x_2x_2' + x_2^2x_2'^2 + 2x_1x'_1 + 2x_2x'_2 + 1 = \langle \phi(x), \phi(x')\rangle with \phi(x) = (x_1^2,\ \sqrt2\,x_1x_2,\ x_2^2,\ \sqrt2\,x_1,\ \sqrt2\,x_2,\ 1) — dimension 6 versus 2: the kernel trick saves the explicit passage.
(ii) Yes, by the addition formula: \cos(x - x') = \cos x\cos x' + \sin x \sin x' = \langle(\cos x, \sin x),\,(\cos x', \sin x')\rangle. A dimension-2 feature map, unit norm.∎
★★ Dual derivation of the SVM. Take up the primal of theorem 3.5: write the Lagrangian (section 0.4) with multipliers (\alpha_i, \mu_i), set the gradients in (\theta, b, \xi) to zero, and recover (a) the dual function, (b) the three families of points of the table in section 3.2 via the complementarity conditions.
★★ EM for a mixture of two 1D Gaussians. Write the two steps, implement (NumPy), and check on a mixture 0.4\,\mathcal{N}(-2, 1) + 0.6\,\mathcal{N}(3, 1) that the log-likelihood is increasing over 50 iterations (theorem 7.5: plot \log p_{\theta_t} and check the increase, strict away from a stationary point).
★★ VC by hand. (i) Show that the intervals [a,b] of \mathbb{R} do not shatter 3 aligned points (example 8.4(ii)). (ii) Compute the VC bound (theorem 8.6) for d = 10, n = 1000, \delta = 5\% and comment (“how much data per dimension?”).
Proof. Solution (i) For x_1 < x_2 < x_3, the label (1,0,1) is unrealizable: an interval containing x_1 and x_3 contains the whole interval [x_1, x_3], hence x_2.
(ii) The bound is \sqrt{8(10\log(2e \cdot 1000/10) + \log 80)/1000} \approx \sqrt{8 \times (63.0 + 4.4)/1000} \approx 0.73: a theoretical error margin of 73 points! The bound is (very) conservative — it guarantees the consistency of the ERM principle (error \to 0 as n/d \to \infty), not actual performance; this is why one also evaluates by cross-validation (4.2).∎
★★ k-means++. (i) Show that uniform random seeding has no bounded approximation ratio. Take k = 2 and the four corners of a w \times h rectangle with w \gg h. Compute the probability that Lloyd’s algorithm, started from two distinct corners drawn uniformly, stops at the partition into top and bottom pairs, and the ratio W_{\text{final}}/W^\star there. (ii) Compute the same probability for k-means++. (iii) Simulate both initializations on anisotropic blobs and measure W_{\text{final}}/W^\star (proposition 7.3 guarantees 8(\ln k + 2) in expectation for k-means++).
Proof. Solution (i) The optimum pairs the corners of each short side: each pair costs 2(h/2)^2, so W^\star = h^2. If the two seeds lie on the same short side, the two far corners join the seed on their own long side; the centres move to the middles of the long sides, every corner is closest to its own centre, and Lloyd stops with W = 2 \cdot 2(w/2)^2 = w^2.
This happens with probability 2/6 = 1/3, and then W_{\text{final}}/W^\star = (w/h)^2, as large as one wants.
(ii) After a first corner, k-means++ picks the other corner of the same short side with probability h^2/(2w^2 + 2h^2), which tends to 0.∎
★★ Multi-label: Hamming versus subset accuracy. On example 9.2 (labels S, P, s), one tests on 10 documents of which 6 follow the pattern “S=1, P=0 \Rightarrow s=1” and 4 are “all zero”. BR learns h_s \equiv 0 (it sees only x), CC learns h_s(x, S=1, P=0) = 1. Compute the Hamming and subset accuracy losses of the two methods, and explain when BR becomes competitive again.
Proof. Solution CC is perfect on the learned patterns: Hamming 0, accuracy 1.
BR errs on the label s of the 6 “pure science” documents: Hamming = \frac{6}{10 \times 3} = 0.2, accuracy = \frac4{10} = 0.4.
If the S \to s dependency did not exist (labels conditionally independent given x), BR would be optimal for Hamming — the chain would only add noise; it is the targeted loss (Hamming vs fine dependencies) that dictates the method (table in section 9.1).∎
★★ Group fairness on Adult. On the Adult census data (Kohavi, 1996; OpenML dataset 1590), predict whether the income exceeds 50,000 dollars, with the pipeline of 4.3 and a gradient-boosted model.
- (i) Report accuracy, positive rate, true- and false-positive rates and precision for women and for men, each with its group size (4.8).
- (ii) Check the identity of proposition 4.5 on your numbers.
- (iii) Choose one threshold per group so that the true-positive rates are equal, and report what happens to the precision of each group and to the overall accuracy.
- (iv) Remove the attribute
sexfrom the features: does the gap in positive rates disappear?
Proof. Solution Outline. (ii) The identity holds exactly, since it is a count. (iii) The group with the lower true-positive rate gets a lower threshold: its true- and false-positive rates rise, its precision usually falls, and the overall accuracy typically drops a little.
(iv) No. Features correlated with sex, such as
relationship(husband or wife) andmarital-status, still carry it: removing the attribute (“fairness through unawareness”) does not remove the disparity.∎★★ Shapley values by hand. Two independent features have mean zero, and the model is f(x) = x_1 + x_1x_2.
- (i) For the example x = (1, 2), compute v(S) for the four sets S (definition 6.5), then \phi_1 and \phi_2, and check efficiency.
- (ii) How is the interaction term x_1x_2 shared between the two features?
- (iii) Show that for a linear model f(x) = \theta_0 + \theta^\top x with independent features, \phi_j = \theta_j(x_j - \mathbb{E}[X_j]).
Proof. Solution (i) v(\varnothing) = \mathbb{E}[X_1 + X_1X_2] = 0, v(\{1\}) = 1 + \mathbb{E}[X_2] = 1, v(\{2\}) = 3\,\mathbb{E}[X_1] = 0 and v(\{1, 2\}) = f(1, 2) = 3. With two features, each order of arrival has weight 1/2: \phi_1 = \tfrac12(1 - 0) + \tfrac12(3 - 0) = 2, \qquad \phi_2 = \tfrac12(0 - 0) + \tfrac12(3 - 1) = 1, and \phi_1 + \phi_2 = 3 = f(x) - \mathbb{E}[f(X)].
(ii) The main term gives 1 to feature 1; the interaction x_1x_2 = 2 is split equally, 1 to each.
(iii) Here v(S) = \theta_0 + \sum_{k \in S}\theta_k x_k + \sum_{k \notin S}\theta_k\mathbb{E}[X_k]. Adding j to any S adds \theta_j(x_j - \mathbb{E}[X_j]), and the weights of definition 6.5 sum to 1.∎
★★ A margin bound in numbers.
- (i) The ramp loss \varphi_\gamma(u) = \min(1, \max(0, 1 - u/\gamma)), applied to the margin u = y f(x), lies between the 0–1 loss \mathbf{1}\{u \leq 0\} and the margin loss \mathbf{1}\{u < \gamma\}. Show that it is 1/\gamma-Lipschitz, and use lemma 8.9 to explain the term 2R/(\gamma\sqrt n) of theorem 3.6.
- (ii) With R = 1, \gamma = 0.1, n = 10{,}000, \delta = 0.05 and an empirical margin error of 0.05, evaluate the bound of theorem 3.6.
- (iii) How many examples make the complexity term equal to 0.05? Why does the dimension of x not appear, unlike in theorem 8.6?
Proof. Solution (i) \varphi_\gamma is constant outside [0, \gamma] and has slope -1/\gamma on it, so it is 1/\gamma-Lipschitz. Contraction multiplies the complexity R/\sqrt n by 1/\gamma, and symmetrization brings the factor 2.
(ii) The bound is 0.05 + \frac{2}{0.1 \times 100} + \sqrt{\frac{\ln 40}{20{,}000}} \approx 0.05 + 0.2 + 0.014 \approx 0.26.
(iii) 2/(0.1\sqrt n) = 0.05 gives \sqrt n = 400, that is n = 160{,}000. The class is controlled by the norm R and the margin \gamma, not by the number of parameters.∎
★★★ Exponential weights. Three estimators with empirical risks 0.30, 0.32, 0.50, n = 100.
Compute the weights \hat\pi for \eta \in \{0.1\,;\ 1\,;\ 10\} (definition in chapter 9) and plot \max_m \hat\pi_m as a function of \eta. What link with the softmax of chapter 3, and what role does \eta play when one doubts the validity of the empirical risks (small n)?
Proof. Solution Weights \propto \exp(-100\eta \hat R_m):
- for \eta = 0.1, ratios e^{-0.2} \approx 0.82 and e^{-2} \approx 0.14 (soft mixture);
- for \eta = 1, e^{-2} \approx 0.14 and e^{-20} \approx 2\cdot10^{-9};
- for \eta = 10, quasi-hard selection.
This is a softmax on the scores -n\eta\hat R_m — \eta plays the role of the inverse temperature. At small n, the \hat R_m are noisy (chapter 0): taking \eta small keeps a mixture, robust to estimation error — precisely the logic of the oracle inequalities of chapter 9.∎
★★★ Running project. On the 20 Newsgroups dataset (count vectorizer → TF-IDF → logistic/forest), build the complete pipeline with nested cross-validation (4.2), report the confusion matrix and macro F1, and calibrate the probabilities (4.5) before choosing the decision threshold. This text preprocessing will be redone “in a modern neural version” in the NLP module.
Projects and assessment
The official assessment is “a final exam” (SynapseS 2026–2027 sheet, “Validation” in the description); the LLGA section of the sheet displays no weights, no resit rule and no ECTS. Everything below is a proposal: the written exam is a mock of that final exam, and the projects are practice that an instructor may adopt as continuous assessment. They exercise objective O1 (machine-learning foundations) in every subject, O7 (hands-on practice: leak-free pipelines, calibration, reproducible code) and O8 (trustworthy AI: the fairness criteria of 4.8 and the explanations of 6.4).
Solo projects
- [Solo · ≈ 20 h] Honest-evaluation audit. Question: on real data, how optimistic are the evaluation shortcuts that chapter 4 warns against?
- Reproduce the selection-bias trap of Example 4.3. Then inject each of the four leaks of section 4.3 in a controlled way into a pipeline on the Adult census data (Kohavi, 1996; OpenML dataset 1590): scaling before the split, target encoding on the full set, duplicated individuals across folds, a feature computed from the label.
- Compare flat and nested cross-validation (4.2) over a grid of at least 20 configurations, repeated over 10 seeds, with a held-out test set (ch. 1, 4).
- Deliverables: code, a 4–6 page audit report ending with a checklist of fixes, a 10-minute talk. Success: the optimism of each shortcut is measured with an interval over seeds (4.9), and the pipelined estimate agrees with the held-out test set within that interval.
- [Solo · ≈ 20 h] Guided paper study: generative versus discriminative classifiers (Ng and Jordan, 2002). Question: does naive Bayes reach its asymptotic error with fewer examples than logistic regression, and are its probabilities usable?
- Read the paper with a one-page sheet: its statistical framework (definition 1.1), its claims, what is proved and what is only measured, its limits (ch. 1, 3).
- Extend Exercise 18: learning curves of multinomial naive Bayes and logistic regression on 20 Newsgroups (Lang, 1995;
fetch_20newsgroupsin scikit-learn), from 50 examples to the full training set, over 5 seeds. - Calibrate both models with Platt scaling and isotonic regression (4.5); report macro-F1, the Brier score and reliability diagrams, and set the decision thresholds after calibration (ch. 4).
- Deliverables: code, the reading sheet, a 4–6 page report, a 10-minute talk. Success: the crossing of the learning curves is reproduced, or its absence explained; calibration lowers the Brier score of naive Bayes, and the report says whether it changes that of logistic regression.
- [Solo · ≈ 20 h] Generalization bounds against observed gaps. Question: how far are the bounds of chapters 3 and 8 from the gaps that one actually measures?
- For the norm-bounded linear class, the supremum of definition 8.7 has the closed form (R/n)\,\|\sum_i \sigma_i x_i\|; for the ball of radius R of an RKHS, it is (R/n)\sqrt{\sigma^\top K \sigma} (ch. 5). Estimate both complexities by Monte Carlo over the signs.
- Train linear and RBF support vector machines on two classes of Fashion-MNIST (Xiao, Rasul and Vollgraf, 2017), inputs scaled to unit norm, for several n and C. Plot the measured train–test gap against the margin bound (theorem 3.6) and the VC bound (theorem 8.6) (ch. 3, 8).
- Deliverables: code, a 4–6 page report, a 10-minute talk. Success: the estimates stay below R\sqrt{\mathrm{tr}\,K}/n, and the report identifies which terms make each bound loose.
Group projects
- [Group of 3 · ≈ 30 h each] Paper study: why do tree-based models still outperform deep learning on typical tabular data? (Grinsztajn, Oyallon and Varoquaux, 2022). Question: do the paper’s findings also hold against kernel methods, under an honest protocol?
- Member 1: kernel methods — an RBF support vector machine and kernel ridge regression with the Nyström approximation (ch. 5).
- Member 2: random forests and HistGradientBoosting with early stopping; the effect of the number of candidate features per split and of the learning rate (ch. 6).
- Member 3: the shared nested cross-validation pipeline on about ten datasets of the paper’s public benchmark, paired comparisons over 3 seeds (4.9), and the paper’s experiment that adds uninformative features (ch. 4).
- Deliverables: code, a 6–8 page report, a 15-minute talk. Success: a ranking backed by paired tests, and at least one of the paper’s explanations (sensitivity to uninformative features, irregular target functions) confirmed or refuted for kernels.
- [Group of 3 · ≈ 30 h each] A fair and explained income model across US states. Use the ACSIncome task of folktables (Ding, Hardt, Miller and Schmidt, 2021), built from US census microdata to replace the Adult data. The subject prepares Explainability, Security and Privacy of LLMs.
- Member 1: models and calibration — logistic regression and gradient boosting in a leak-free pipeline, with calibration curves per group (ch. 3, 4, 6).
- Member 2: fairness audit (4.8) — positive rates, error rates and precision by sex and by race, with intervals (4.9); one threshold per group for equal opportunity, and its price in accuracy; a numerical check of proposition 4.5.
- Member 3: explanations (6.4) — TreeSHAP against permutation importance, and their stability when the model is trained on one state and tested on another.
- Deliverables: code, a 6–8 page report with a one-page model card, a 15-minute talk. Success: the fairness–accuracy trade-off is plotted with intervals, and the report recommends one criterion and justifies it.
- [Group of 3 · ≈ 30 h each] Classical baselines for text and graphs. Question: how much of a neural model’s gain survives a well-tuned classical baseline run under the same protocol? Best done in Period 2, alongside Text Mining & NLP and Graph ML.
- Member 1: text — TF-IDF with logistic regression on AG News (Zhang, Zhao and LeCun, 2015), against a small fine-tuned encoder (NLP ch. 7).
- Member 2: graphs — the Weisfeiler–Lehman subtree kernel (Shervashidze and coauthors, 2011) with a support vector machine (ch. 5) on MUTAG and PROTEINS from TUDataset (Morris and coauthors, 2020), against a graph neural network (Graph ML ch. 2, 5).
- Member 3: the shared protocol — same splits and tuning budget, 3 seeds, paired tests and calibration (ch. 4), and the contamination checks of LLM ch. 9 for the pretrained encoder.
- Deliverables: code, a 6–8 page report, a 15-minute talk. Success: each gap between the neural model and its classical baseline is reported with a paired interval, and the baselines become the reference rows of the Year 1 end-of-year projects.
Written exam (proposal)
Format: 2 hours, one handwritten A4 sheet allowed, no electronic device, four questions. The sheet announces a final exam but displays no format.
Question (4 points). Define the risk, the empirical risk and empirical risk minimization. State the decomposition of the excess risk into approximation and estimation errors, and say how enlarging the class moves each term. Why is a cross-validated score optimistic when the same folds also chose the hyperparameters, and how does nested cross-validation fix it?
Expected: definitions 1.1–1.2, with the loss written \ell(\hat y, y), and the key result of chapter 1. A larger class lowers the approximation error and raises the estimation error, which proposition 8.1 bounds by a supremum over the class. The retained score is the maximum of noisy estimates, a selection bias (4.2, Example 4.3); nested cross-validation chooses in the inner loop and evaluates on an outer fold never used for the choice.
Question (5 points). (a) With X^\top X = nI_3, z = X^\top y/n = (0.9, -0.2, 0.4) and \lambda = 0.6, compute the lasso of definition 2.4. (b) Two groups have prevalences 0.5 and 0.2; a classifier has precision 0.8 and false-negative rate 0.2 in both. Compute the two false-positive rates. (c) On 1000 shared test examples, model A alone is right 15 times and model B alone 30 times. Apply McNemar’s test at 5 %.
Expected: (a) soft thresholding at \lambda/2 = 0.3 gives (0.6, 0, 0.1) (proposition 2.6). (b) By proposition 4.5, 0.2 and 0.05. (c) \chi^2 = 14^2/45 \approx 4.36 > 3.84: B is significantly better at 5 % (section 4.9).
Question (5 points). For two distributions on a finite set, prove that \mathrm{KL}(p \,\|\, q) \geq 0, with equality if and only if p = q. Deduce that H(p, q) \geq H(p), and show that maximizing the likelihood of a model q_\theta on a sample minimizes the cross-entropy H(\hat p_n, q_\theta).
Expected: Jensen’s inequality for the concave logarithm under p, with its two equality cases (proposition 0.8(i)); the split H(p, q) = H(p) + \mathrm{KL}(p \,\|\, q); grouping equal values, the average log-likelihood is -H(\hat p_n, q_\theta), and H(\hat p_n) does not depend on \theta.
Question (6 points). For logistic regression with p_i = \sigma(\theta^\top x_i) and labels y'_i \in \{-1, +1\}, F(\theta) = \frac1n\sum_{i=1}^n \log\big(1 + e^{-y'_i\theta^\top x_i}\big). (a) Compute \nabla F and \nabla^2 F. (b) Prove that F is convex, and strictly convex when X has full column rank. (c) Write one Newton step and show that it solves a weighted least-squares problem.
Expected: (a) by theorem 3.3, \nabla F = \frac1n X^\top(p - y) and \nabla^2 F = \frac1n X^\top W X with W = \mathrm{diag}(p_i(1 - p_i)). (b) For every v, v^\top \nabla^2 F\, v = \frac1n\sum_i w_i (x_i^\top v)^2 \geq 0, zero only if Xv = 0. (c) \theta^+ = \theta + (X^\top W X)^{-1}X^\top(y - p): the weighted least-squares fit, with weights w_i, of the working response X\theta + W^{-1}(y - p) (IRLS).
Grading rubric (proposal)
| Criterion | Weight | What earns the marks |
|---|---|---|
| Correctness and rigour | 25 % | methods implemented as defined in the chapters; derivations checked numerically; no leakage between training and evaluation |
| Evaluation protocol | 25 % | nested or held-out selection, retrained baselines, at least 3 seeds, paired tests and intervals (4.9), per-group metrics whenever people are scored (4.8) |
| Results and analysis | 20 % | the success criterion is met or its failure explained; ablations, error analysis, calibration |
| Code and reproducibility | 15 % | one script or notebook reruns every number of the report from public data, with fixed seeds |
| Report and talk | 15 % | a clear question, real references, figures that make the point, precise answers to questions |
References
Textbooks
- T. Hastie, R. Tibshirani, J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009 — free PDF: the reference textbook of the course.
- G. James, D. Witten, T. Hastie, R. Tibshirani, An Introduction to Statistical Learning, 2nd ed., Springer, 2021 — the applied (Python) version of the same foundation.
- C. Bishop, Pattern Recognition and Machine Learning, Springer, 2006 — for the generative viewpoint (EM, kernels) taken up again in Deep Learning.
- S. Shalev-Shwartz, S. Ben-David, Understanding Machine Learning, Cambridge, 2014 — ch. 6 (VC dimension and Sauer’s lemma), ch. 26 (Rademacher complexity), ch. 13 (margin bounds, SVM).
- K. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press, 2022 — a modern panorama, free online.
- S. Boucheron, G. Lugosi, P. Massart, Concentration Inequalities: A Nonasymptotic Theory of Independence, Oxford University Press, 2013 — ch. 1-2: Markov, Hoeffding, Chernoff, and beyond (chapter 0).
- G. Garrigos, R. M. Gower, Handbook of Convergence Theorems for (Stochastic) Gradient Methods, arXiv:2301.11235, 2023 — rates of gradient descent and SGD (section 0.2).
- scikit-learn User Guide — the labs follow its conventions (pipelines, calibration, imblearn for imbalance).
Foundational papers cited in the course
- J. H. Friedman, Greedy Function Approximation: A Gradient Boosting Machine, Annals of Statistics 29(5), 2001 — Project Euclid: boosting as functional gradient descent (chapter 6).
- D. Arthur, S. Vassilvitskii, k-means++: The Advantages of Careful Seeding, SODA 2007 — PDF (Stanford): the 8(\ln k + 2) guarantee (chapter 7).
- M. E. Tipping, C. M. Bishop, Probabilistic Principal Component Analysis, JRSS-B 61(3), 1999 — Oxford Academic: PCA as a generative model (chapter 7).
- A. Y. Ng, M. I. Jordan, On Discriminative vs. Generative Classifiers: A Comparison of Logistic Regression and Naive Bayes, NeurIPS 2001 (published 2002): the sample-size trade-off of section 3.3.
Duality, theory, clustering, evaluation and explanation
- S. Boyd, L. Vandenberghe, Convex Optimization, Cambridge University Press, 2004 — free PDF: Lagrangian duality, Slater and KKT (section 0.4).
- C. J. C. Burges, A Tutorial on Support Vector Machines for Pattern Recognition, Data Mining and Knowledge Discovery 2(2), 1998 — the sinusoid class and its unshatterable four points (Example 8.2).
- M. Ledoux, M. Talagrand, Probability in Banach Spaces, Springer, 1991 — the contraction principle (lemma 8.9).
- M. Mohri, A. Rostamizadeh, A. Talwalkar, Foundations of Machine Learning, 2nd ed., MIT Press, 2018 — Rademacher bounds, Talagrand’s lemma and margin bounds (chapter 8).
- M. Ester, H.-P. Kriegel, J. Sander, X. Xu, A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise, KDD 1996 — DBSCAN (section 7.1).
- L. van der Maaten, G. Hinton, Visualizing Data using t-SNE, JMLR 9, 2008; L. McInnes, J. Healy, J. Melville, UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, arXiv:1802.03426, 2018 — section 7.3.
- M. Hardt, E. Price, N. Srebro, Equality of Opportunity in Supervised Learning, NeurIPS 2016 — equalized odds and per-group thresholds (section 4.8).
- A. Chouldechova, Fair Prediction with Disparate Impact: A Study of Bias in Recidivism Prediction Instruments, Big Data 5(2), 2017 — the identity of proposition 4.5.
- J. Kleinberg, S. Mullainathan, M. Raghavan, Inherent Trade-Offs in the Fair Determination of Risk Scores, ITCS 2017 — calibration against balanced error rates (section 4.8).
- T. G. Dietterich, Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms, Neural Computation 10(7), 1998 — McNemar’s test for classifiers (section 4.9).
- C. Nadeau, Y. Bengio, Inference for the Generalization Error, Machine Learning 52(3), 2003 — the corrected resampled t test (section 4.9).
- L. Breiman, Random Forests, Machine Learning 45(1), 2001 — permutation importance (section 6.4).
- C. Strobl, A.-L. Boulesteix, A. Zeileis, T. Hothorn, Bias in Random Forest Variable Importance Measures: Illustrations, Sources and a Solution, BMC Bioinformatics 8, 2007 — the bias of impurity importance (section 6.4).
- L. S. Shapley, A Value for n-Person Games, in Contributions to the Theory of Games II, Princeton University Press, 1953 — the Shapley axioms (section 6.4).
- S. M. Lundberg, G. Erion, H. Chen, et al., From Local Explanations to Global Understanding with Explainable AI for Trees, Nature Machine Intelligence 2, 2020 — TreeSHAP (section 6.4).
Research at CMAP and LIX (Le Pennec, Read)
- J. Read, B. Pfahringer, G. Holmes, E. Frank, Classifier Chains for Multi-label Classification, ECML PKDD 2009 — PDF: the classifier chains paper (chapter 9).
- J. Read, Scalable Multi-label Classification, PhD thesis, University of Waikato, 2010 — full text: the transformation/adaptation taxonomy of multi-label.
- J. Read, A. Bifet, B. Pfahringer, G. Holmes, Scalable and Efficient Multi-label Classification for Evolving Data Streams, Machine Learning 88, 2012 — multi-label on streams (iSOUP-Tree).
- J. Read, Concept-drifting Data Streams are Time Series, 2018 — arXiv:1810.02266.
- J. Read et al., Deep Learning for Multi-label Classification, 2014 — arXiv:1502.05988: a multi-label and deep learning panorama.
- J. Montiel, M. Halford, D. Salles, S. Vrysis, et al. (incl. J. Read), River: machine learning for streaming data in Python, JMLR 22(110), 2021 — JMLR: the tooling of the “streaming” labs.
- L. Montuelle, E. Le Pennec, PAC-Bayesian Aggregation of Affine Estimators, 2014 — arXiv:1410.0661; long version: PAC-Bayesian aggregation of linear estimators, Nonparametric Statistics 33, 2019.
- J. Salmon, E. Le Pennec, An Aggregator Point of View on NL-Means, SPIE Wavelets and Sparsity XIV, 2009 — patch-based denoising reread as aggregation of estimators.
- F. Autin, E. Le Pennec, K. Tribouley, Thresholding Methods to Estimate Copula Density, Journal of Multivariate Analysis 101(1), 2010 — thresholding and automatic selection in nonparametrics.
- É. Gautier, E. Le Pennec, Adaptive Estimation in the Nonparametric Random Coefficients Binary Choice Model by Needlet Thresholding — HAL (inria-00601274): needlets and scale selection, link with logistic regression.