Computing and AI
Machine Learning
English · 288 pp. PDF
Part 0: Introduction & Mathematical Foundations
1 What is Machine Learning?
1.1 Core Definitions and Philosophy
Definition 1.1 (Machine Learning). Machine Learning is a field of study that gives computers the ability to learn from data without being explicitly programmed. More formally, a program is said to learn from experience \(E\) with respect to some task \(T\) and performance measure \(P\), if its performance on \(T\), as measured by \(P\), improves with experience \(E\).
Intuition 2. Think of teaching a child to recognize cats. Instead of writing down explicit rules (“has whiskers, four legs, pointy ears”), you show them many pictures of cats and non-cats. Over time, they learn the pattern themselves. Machine learning works similarly—we provide data (experience), and the algorithm discovers the patterns.
Example 1.3 (Email Spam Filter).
Task \(T\): Classify emails as spam or not spam
Experience \(E\): A dataset of emails labeled as spam/not spam
Performance \(P\): Accuracy of classification on new emails
The algorithm learns from labeled examples. Whether its accuracy improves must be measured on representative unseen emails; additional data alone does not guarantee improvement.
1.2 Types of Machine Learning
Machine learning paradigms are categorized by the type of feedback available during training:
1.2.1 Supervised Learning
In supervised learning, we have a dataset \(\mathcal{D} = \{(\boldsymbol{x}_1, y_1), (\boldsymbol{x}_2, y_2), \ldots, (\boldsymbol{x}_n, y_n)\}\) where \(\boldsymbol{x}_i \in \mathbb{R}^d\) are input features and \(y_i\) are labels.
Classification: \(y_i\) is categorical (e.g., spam/not spam, cat/dog/bird)
Regression: \(y_i\) is continuous (e.g., house prices, temperature)
Goal: Learn a function \(f: \mathbb{R}^d \to \mathcal{Y}\) such that \(f(\boldsymbol{x}) \approx y\) for new, unseen examples.
Example 1.4 (Supervised Learning Applications).
Predicting house prices from size, location, number of rooms (regression)
Diagnosing diseases from medical images (classification)
Speech recognition (classification)
1.2.2 Unsupervised Learning
In unsupervised learning, we only have inputs \(\mathcal{D} = \{\boldsymbol{x}_1, \boldsymbol{x}_2, \ldots, \boldsymbol{x}_n\}\) without labels.
Goal: Discover hidden structure or patterns in the data.
Clustering: Group similar examples together
Dimensionality Reduction: Find lower-dimensional representations
Density Estimation: Model the probability distribution of data
Example 1.5 (Unsupervised Learning Applications).
Customer segmentation in marketing
Anomaly detection in network traffic
Topic modeling in document collections
1.2.3 Semi-Supervised Learning
A middle ground where we have a small amount of labeled data and a large amount of unlabeled data. This is common in practice since labeling is expensive.
1.2.4 Reinforcement Learning
An agent learns to make decisions by interacting with an environment, receiving rewards or penalties for actions.
Agent: The learner/decision maker
Environment: What the agent interacts with
Actions: Choices available to the agent
Rewards: Feedback signal (positive or negative)
Example 1.6 (Reinforcement Learning). Teaching a robot to walk: it tries different leg movements (actions), and receives positive reward when it moves forward and negative reward when it falls.
1.3 From a Learning Problem to an Evaluation Protocol
A supervised example is a pair \((\boldsymbol{x},y)\) drawn from a population distribution \(P\). A training set \(\mathcal D=\{(\boldsymbol{x}_i,y_i)\}_{i=1}^n\) determines a fitted predictor \(f_{\hat\theta(\mathcal D)}\). The central distinction is \[R(\theta)=\mathbb{E}_{(\boldsymbol{x},y)\sim P}\bigl[\ell(f_\theta(\boldsymbol{x}),y)\bigr], \qquad \widehat R_{\mathcal D}(\theta)=\frac1n\sum_{i=1}^n\ell(f_\theta(\boldsymbol{x}_i),y_i).\] The first is population risk; the second is observable training risk. Reducing the second need not reduce the first, because the fitted parameters depend on the same data used to compute training risk. Unless stated otherwise, the elementary analysis assumes independent, identically distributed examples and a test population matching the intended deployment population.
Global matrix, label, and loss conventions are collected in Section 1.4.
A model parameter is fitted within a training run. A hyperparameter controls the model or fitting procedure and is selected outside that run. A classification threshold is also a selected decision rule; optimizing it on the test labels consumes the test set.
Example 1.7 (A complete holdout protocol). Suppose 20 independent examples are assigned in advance to 12 training, 4 validation, and 4 test examples. For each candidate hyperparameter, fit all learned transformations and the model on the 12 training examples. Apply those fitted transformations to the validation examples, then select the candidate using its validation metric. Refit the selected procedure, including its transformations, on the 16 training-plus-validation examples. Evaluate the resulting procedure once on the 4 untouched test examples. The test score measures this final procedure on this small holdout; it is an uncertain estimate, not a population guarantee.
If cross-validation replaces the validation split, each training fold must fit its own transformations. After choosing the hyperparameter, refit the base procedure on its designated non-test fitting block. In this simple example no separate calibrator or threshold is learned afterward. If those stages are required, retain their separate fitting blocks as in Section 23.2; changing the base model after calibration changes the complete predictor. The test set remains outside cross-validation. Section 23 gives the full workflow.
Example 1.8 (An unsupervised transformation can leak information). A scaler fitted to training values \(0,2\) has mean \(1\) and population standard deviation \(1\). It maps a held-out value \(10\) to \((10-1)/1=9\). Fitting the scaler on all three values instead gives \[\bar x=4,\qquad s^2=\frac{16+4+36}{3}=\frac{56}{3},\qquad z_{\rm heldout}=\frac{6}{\sqrt{56/3}}\approx1.389.\] The second representation has already used held-out information, even without labels. This arithmetic demonstrates contamination; it does not assert that every contaminated toy example must improve the reported score. Imputation, PCA, vocabulary learning, feature selection, and target encoding need the same scrutiny. Target encoding additionally needs out-of-fold training encodings to prevent a row’s label from entering its own feature.
Choose the splitting unit before the splitter. Repeated measurements of a patient, user, device, or document source belong in the same group when the goal is prediction for new groups. Stratifying class proportions does not enforce this separation. For forecasting, train on the past and validate on later observations; features must have been available at prediction time. Overlapping feature or label windows may require a gap or purging around the boundary. A random row split answers a different question. See Sections 23.1.1 and 24.
1.4 Notation, Loss Scaling, and the Whole-Book Reading Map
| Symbol | Convention across Parts 0–8 |
|---|---|
| \(n,B,d\) | Dataset size, minibatch size, and original feature count. Local sequence lengths and layer widths are defined separately. |
| \(\boldsymbol{x},\boldsymbol{X}\) | A single input is a column vector; examples are rows of the design matrix. An intercept column is included only where stated. |
| \(\boldsymbol{W}\in\mathbb{R}^{q\times d}\) | A column-affine map has \(q\) outputs and \(d\) inputs. Row-stacked batches use its transpose; attention explicitly defines row-projection matrices. |
| \(y,\hat y,p,q\) | Observed target, predicted output/decision, and declared probability estimates. The context distinguishes a regression output from a class probability. |
| \(\ell_i,\mathcal{L}\) | Per-example scalar loss and an aggregate training objective. The default data term is \(n^{-1}\sum_i\ell_i\); exceptions are explicitly marked. |
| \(\lambda,C,\eta_t\) | Penalty coefficient, SVM/library regularization parameter, and learning rate. Equal names across models do not imply equal numerical conventions. |
| \(c_{FP},c_{FN}\) | Decision costs, separate from the regularization parameter \(C\). |
| \(K,k,\alpha,\gamma,\epsilon\) | Locally defined class/cluster counts, neighbor counts, multipliers, decay/discount factors, radii, or stabilizers; these roles are not interchangeable. |
Binary probabilities use labels \(\{0,1\}\). SVM, perceptron, and binary AdaBoost use \(\{-1,+1\}\), related by \(y_{\pm}=2y_{01}-1\). Mathematical hard decisions use \(\operatorname{sign}(0)=+1\) here; a library’s boundary ties and class-column ordering must still be checked. Natural logarithms are used unless a base is shown explicitly; classification-tree entropy uses \(\log_2\) and bits.
Averages and penalties. For scalar regression, MSE is \(n^{-1}\sum_i(\hat y_i-y_i)^2\), without an extra half. For vector outputs, \(\ell_i=\|\hat{\boldsymbol{y}}_i-\boldsymbol{y}_i\|_2^2\) sums output coordinates before averaging examples. Averaging all \(nq\) scalar entries instead divides that loss and its gradients by \(q\). Sequence-mean and token-mean objectives can also differ and are declared where used. The following conversions preserve minimizers for the same data and intercept treatment:
| Objective in these notes | Equivalent alternative convention |
|---|---|
| \(\mathrm{SSE}/n+\lambda\|w\|_2^2\) | Sum loss \(\mathrm{SSE}+\alpha\|w\|_2^2\) with \(\alpha=n\lambda\) (Ridge). |
| \(\mathrm{SSE}/n+\lambda\|w\|_1\) | Half-mean loss \(\mathrm{SSE}/(2n)+\alpha\|w\|_1\) with \(\alpha=\lambda/2\) (Lasso). |
| \(\|w\|^2/2+C\sum_i\ell_{hinge,i}\) | Mean hinge plus \(\lambda\|w\|^2/2\), with \(\lambda=1/(nC)\). |
| \(\sum_i\ell_i+\Omega\) | Mean data loss plus \(\Omega/n\); divide every penalty term by \(n\) too. |
Multiplying the entire objective by a positive constant preserves minimizers but scales gradients. Plain gradient descent needs a compensating learning rate for identical updates; adaptive optimizers, clipping, and decay require their own update conventions. An unpenalized intercept is excluded from the penalty. Gaussian likelihood scales and VAE decoder variances specify their own reconstruction coefficients; they are not silently replaced by MSE.
Where each thread continues. Linear algebra and likelihoods lead to regression and regularization (Sections 3.1.3 and 3.2.4), probabilistic classification (Section 7.5), and margin methods (Section 9). Ensemble loss scaling is developed in Sections 12.3.1 and 12.4.1; neural gradients and batch reductions in Sections 15.7 and 15.8. PCA, autoencoders, and the VAE bound meet in Sections 20.2.2, 20.4.5, and 20.4.7. Evaluation and the executed deployment workflow are in Sections 23 and 27.9; advanced objectives reuse these conventions in Sections 29.7, 32.4, and 32.6.
“Evaluate once” means that final evaluation supplies no feedback for choosing models, calibration, thresholds, or reported populations. Reproducing a frozen result, checking export parity, and computing prespecified fixed-model intervals are compatible with this rule. A new choice influenced by the final test needs a new evaluation boundary. The four-block calibration protocol in Section 23.2 refines the simpler holdout example; it is not permission to refit a base model after freezing its calibrator.
1.5 Machine Learning vs AI vs Statistics
Artificial Intelligence (AI): The broad goal of creating intelligent machines. ML is a subset of AI.
Machine Learning (ML): Algorithms that improve through experience. Focus on prediction and pattern recognition.
Statistics: The science of collecting, analyzing, and interpreting data. ML borrows heavily from statistics but emphasizes prediction over inference.
The line between ML and statistics is blurry. Roughly: statistics asks “What can we infer?” while ML asks “What can we predict?”
1.6 Major Paradigms and Milestones
1950s-60s: Perceptron, early neural networks
1980s: Backpropagation algorithm
1990s: Support Vector Machines, early randomized tree ensembles
2000s: Random Forests (Breiman, 2001), deep learning resurgence, big data
2010s: AlexNet (2012), AlphaGo (2016), Transformers (2017), BERT and GPT-1 (2018)
2020s: Scaling of large language models, foundation models and multimodal learning
2 Mathematical Foundations
2.1 Linear Algebra Refresher
2.1.1 Vectors and Vector Spaces
Definition 2.1 (Vector). A vector \(\boldsymbol{v} \in \mathbb{R}^n\) is an ordered list of \(n\) real numbers: \[\boldsymbol{v} = \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{bmatrix}\] We denote vectors in bold lowercase (e.g., \(\boldsymbol{x}, \boldsymbol{w}\)).
Geometric Interpretation: A vector represents a point in \(n\)-dimensional space or a direction with magnitude.
Definition 2.2 (Vector Operations). For \(\boldsymbol{u}, \boldsymbol{v} \in \mathbb{R}^n\) and scalar \(\alpha \in \mathbb{R}\):
Addition: \(\boldsymbol{u} + \boldsymbol{v} = [u_1+v_1, u_2+v_2, \ldots, u_n+v_n]^\top\)
Scalar multiplication: \(\alpha \boldsymbol{v} = [\alpha v_1, \alpha v_2, \ldots, \alpha v_n]^\top\)
Dot product: \(\boldsymbol{u} \cdot \boldsymbol{v} = \boldsymbol{u}^\top \boldsymbol{v} = \sum_{i=1}^n u_i v_i\)
Intuition 11. The dot product \(\boldsymbol{u} \cdot \boldsymbol{v}\) measures how much two vectors point in the same direction: \[\boldsymbol{u} \cdot \boldsymbol{v} = \left\lVert\boldsymbol{u}\right\rVert \left\lVert\boldsymbol{v}\right\rVert \cos\theta\] where \(\theta\) is the angle between them. If \(\theta = 90^{\circ}\), then \(\boldsymbol{u} \cdot \boldsymbol{v} = 0\) (orthogonal).
Definition 2.4 (Norm). The Euclidean norm (or \(\ell_2\)-norm) of a vector \(\boldsymbol{v}\) is: \[\left\lVert\boldsymbol{v}\right\rVert_2 = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{\boldsymbol{v}^\top \boldsymbol{v}}\] Other common norms include \(\ell_1\)-norm: \(\left\lVert\boldsymbol{v}\right\rVert_1 = \sum_{i=1}^n |v_i|\) and \(\ell_\infty\)-norm: \(\left\lVert\boldsymbol{v}\right\rVert_\infty = \max_i |v_i|\).
2.1.2 Matrices
Definition 2.5 (Matrix). A matrix \(\boldsymbol{A} \in \mathbb{R}^{m \times n}\) is a rectangular array with \(m\) rows and \(n\) columns: \[\boldsymbol{A} = \begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \end{bmatrix}\] We denote matrices in bold uppercase (e.g., \(\boldsymbol{X}, \boldsymbol{W}\)).
Definition 2.6 (Matrix-Vector Multiplication). For \(\boldsymbol{A} \in \mathbb{R}^{m \times n}\) and \(\boldsymbol{x} \in \mathbb{R}^n\): \[\boldsymbol{A}\boldsymbol{x} = \begin{bmatrix} \boldsymbol{a}_1^\top \boldsymbol{x} \\ \boldsymbol{a}_2^\top \boldsymbol{x} \\ \vdots \\ \boldsymbol{a}_m^\top \boldsymbol{x} \end{bmatrix} \in \mathbb{R}^m\] where \(\boldsymbol{a}_i^\top\) is the \(i\)-th row of \(\boldsymbol{A}\).
Key Point: Matrix multiplication \(\boldsymbol{A}\boldsymbol{x}\) is a linear transformation that maps \(\boldsymbol{x}\) to a new vector.
Definition 2.7 (Matrix-Matrix Multiplication). For \(\boldsymbol{A} \in \mathbb{R}^{m \times n}\) and \(\boldsymbol{B} \in \mathbb{R}^{n \times p}\): \[(\boldsymbol{A}\boldsymbol{B})_{ij} = \sum_{k=1}^n a_{ik} b_{kj}\] Result is \(\boldsymbol{C} \in \mathbb{R}^{m \times p}\).
Definition 2.8 (Transpose). The transpose of \(\boldsymbol{A} \in \mathbb{R}^{m \times n}\) is \(\boldsymbol{A}^\top \in \mathbb{R}^{n \times m}\) where \((\boldsymbol{A}^\top)_{ij} = a_{ji}\).
A matrix is symmetric if \(\boldsymbol{A} = \boldsymbol{A}^\top\).
Definition 2.9 (Identity and Inverse). The identity matrix \(\boldsymbol{I}_n \in \mathbb{R}^{n \times n}\) has 1s on the diagonal and 0s elsewhere: \(\boldsymbol{I}_n \boldsymbol{x} = \boldsymbol{x}\) for all \(\boldsymbol{x}\).
The inverse of a square matrix \(\boldsymbol{A}\) (if it exists) is \(\boldsymbol{A}^{-1}\) such that \(\boldsymbol{A}\boldsymbol{A}^{-1} = \boldsymbol{A}^{-1}\boldsymbol{A} = \boldsymbol{I}\).
2.1.3 Eigenvalues and Eigenvectors
Definition 2.10 (Eigenvalue and Eigenvector). For a square matrix \(\boldsymbol{A} \in \mathbb{R}^{n \times n}\), a non-zero vector \(\boldsymbol{v}\) is an eigenvector with eigenvalue \(\lambda\) if: \[\boldsymbol{A}\boldsymbol{v} = \lambda \boldsymbol{v}\] For a real eigenpair, \(\boldsymbol{A}\) maps \(\boldsymbol{v}\) onto the same line: positive \(\lambda\) preserves its orientation, negative \(\lambda\) reverses it, and \(\lambda=0\) maps it to zero.
Intuition 19. Real eigenvectors identify invariant lines of the transformation; a negative eigenvalue reverses orientation along its line. They reveal the “natural axes” of the transformation.
Definition 2.12 (Eigendecomposition). A symmetric matrix \(\boldsymbol{A} \in \mathbb{R}^{n \times n}\) can be decomposed as: \[\boldsymbol{A} = \boldsymbol{Q}\boldsymbol{\Lambda}\boldsymbol{Q}^\top\] where \(\boldsymbol{Q}\) contains orthonormal eigenvectors as columns, and \(\boldsymbol{\Lambda}\) is diagonal with eigenvalues.
Importance in ML: Eigendecomposition is crucial for PCA, understanding optimization landscapes, and analyzing neural network behavior.
2.1.4 Rank, Projection, and the Singular Value Decomposition
The column space \(\operatorname{col}(\boldsymbol{A})\) is the span of the columns; its dimension is \(\operatorname{rank}(\boldsymbol{A})\). The null space is \(\{\boldsymbol{w}:\boldsymbol{A}\boldsymbol{w}=0\}\). If two parameter vectors differ by a null vector, they make the same fitted predictions. Thus full column rank is the condition for unique unconstrained least-squares coefficients.
Example 2.13 (Projection and non-unique coefficients). Let \(\boldsymbol{v}=(1,2)^\top\) and \(\boldsymbol{q}=(2,1)^\top\). Minimizing \(\|a\boldsymbol{v}-\boldsymbol{q}\|^2\) gives \[0=2\boldsymbol{v}^\top(a\boldsymbol{v}-\boldsymbol{q}),\quad a=\frac{\boldsymbol{v}^\top\boldsymbol{q}}{\boldsymbol{v}^\top\boldsymbol{v}}=\frac45.\] The projection is \(\boldsymbol{p}=(4/5,8/5)^\top\), and the residual \(\boldsymbol{q}-\boldsymbol{p}=(6/5,-3/5)^\top\) is orthogonal to \(\boldsymbol{v}\). The minimum squared error is \(9/5\).
Now let \(\boldsymbol{A}=\left[\begin{smallmatrix}1&1\\2&2\end{smallmatrix}\right]\). Its rank is one and its null space is spanned by \((1,-1)^\top\). All solutions with \(w_1+w_2=4/5\) produce \(\boldsymbol{p}\); the minimum-norm solution is \((2/5,2/5)^\top\).
For any real matrix, the singular value decomposition (SVD) writes \(\boldsymbol{A}=\boldsymbol{U}\boldsymbol{S}\boldsymbol{V}^\top\), with orthogonal singular vectors and nonnegative singular values \(s_j\). The pseudoinverse replaces each nonzero \(s_j\) by \(1/s_j\) and leaves zeros at zero: \[\boldsymbol{A}^+=\boldsymbol{V}\boldsymbol{S}^+\boldsymbol{U}^\top,\qquad \hat{\boldsymbol{w}}=\boldsymbol{A}^+\boldsymbol{q}.\] This gives the minimum-norm least-squares solution even when the normal matrix is singular. In the example, the only nonzero singular value is \(\sqrt{10}\), with left vector \((1,2)^\top/\sqrt5\) and right vector \((1,1)^\top/\sqrt2\). Very small singular values amplify noise through \(1/s_j\); numerical solvers use a tolerance, and regularization limits amplification.
For symmetric \(\boldsymbol{H}=\boldsymbol{Q}\operatorname{diag}(\lambda_j)\boldsymbol{Q}^\top\), the quadratic form is \(\boldsymbol{u}^\top\boldsymbol{H}\boldsymbol{u}=\sum_j\lambda_j(\boldsymbol{Q}^\top\boldsymbol{u})_j^2\). Hence positive semidefinite means all \(\lambda_j\ge0\), and positive definite means all \(\lambda_j>0\). For \(\boldsymbol{H}=\left[\begin{smallmatrix}2&1\\1&2\end{smallmatrix}\right]\), eigenvalues \(3,1\) occur along \((1,1)\) and \((1,-1)\). These directions are the principal axes of a quadratic loss; their ratio controls how differently gradient descent behaves across directions.
2.2 Probability Theory
2.2.1 Random Variables and Distributions
Definition 2.14 (Random Variable). A random variable \(X\) is a function that maps outcomes of a random experiment to real numbers. It can be:
Discrete: Takes countable values (e.g., dice roll, coin flip)
Continuous: Takes values in an interval (e.g., height, temperature)
Definition 2.15 (Probability Mass Function (PMF)). For discrete \(X\), the PMF is \(P(X = x)\), satisfying: \[P(X = x) \geq 0, \quad \sum_x P(X = x) = 1\]
Definition 2.16 (Probability Density Function (PDF)). For continuous \(X\), the PDF \(p(x)\) satisfies: \[p(x) \geq 0, \quad \int_{-\infty}^\infty p(x)\,dx = 1, \quad P(a \leq X \leq b) = \int_a^b p(x)\,dx\]
Example 2.17 (Important Distributions).
Bernoulli: \(X \in \{0,1\}\), \(P(X=1) = p\). Models binary outcomes (coin flip).
Gaussian (Normal): \(X \sim \mathcal{N}(\mu, \sigma^2)\) with PDF: \[p(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)\] Central to ML due to Central Limit Theorem.
Multivariate Gaussian: \(\boldsymbol{X} \sim \mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\Sigma})\) with positive-definite covariance \(\boldsymbol{\Sigma}\) has PDF: \[p(\boldsymbol{x}) = \frac{1}{(2\pi)^{d/2}|\boldsymbol{\Sigma}|^{1/2}} \exp\left(-\frac{1}{2}(\boldsymbol{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\boldsymbol{x}-\boldsymbol{\mu})\right)\]
2.2.2 Expectation and Variance
Definition 2.18 (Expectation). The expected value (or mean) of \(X\) is: \[\mathbb{E}[X] = \begin{cases} \sum_x x \cdot P(X=x) & \text{discrete} \\ \int_{-\infty}^\infty x \cdot p(x)\,dx & \text{continuous} \end{cases}\] For a function \(g(X)\): \(\mathbb{E}[g(X)] = \sum_x g(x) P(X=x)\) or \(\int g(x) p(x)\,dx\).
Properties:
Linearity: \(\mathbb{E}[aX + bY] = a\mathbb{E}[X] + b\mathbb{E}[Y]\)
For independent \(X, Y\): \(\mathbb{E}[XY] = \mathbb{E}[X]\mathbb{E}[Y]\)
Definition 2.19 (Variance). The variance measures spread around the mean: \[\mathrm{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2\] Standard deviation: \(\sigma = \sqrt{\mathrm{Var}(X)}\).
Definition 2.20 (Covariance). For two random variables: \[\mathrm{Cov}(X, Y) = \mathbb{E}[(X-\mathbb{E}[X])(Y-\mathbb{E}[Y])] = \mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y]\] If \(\mathrm{Cov}(X,Y) = 0\), then \(X\) and \(Y\) are uncorrelated (not necessarily independent).
2.2.3 Bayes’ Rule
Theorem 2.21 (Bayes’ Rule). For events \(A\) and \(B\) with \(P(B) > 0\): \[P(A|B) = \frac{P(B|A)P(A)}{P(B)}\] In ML notation with data \(\mathcal{D}\) and parameters \(\theta\): \[P(\theta|\mathcal{D}) = \frac{P(\mathcal{D}|\theta)P(\theta)}{P(\mathcal{D})}\] where:
\(P(\theta|\mathcal{D})\) is the posterior (what we want)
\(P(\mathcal{D}|\theta)\) is the likelihood (how well \(\theta\) explains data)
\(P(\theta)\) is the prior (our initial belief)
\(P(\mathcal{D})\) is the evidence (normalization constant)
Bayes’ rule is fundamental to probabilistic machine learning. It tells us how to update our beliefs about model parameters after seeing data: \[\text{Posterior} \propto \text{Likelihood} \times \text{Prior}\]
2.2.4 Joint Distributions and Conditional Independence
For discrete variables, \(p(x,y)=p(x\mid y)p(y)\) and \(p(x)=\sum_y p(x,y)\). Replace the sum with an integral for a continuous variable. A continuous density is not a point probability: \(P(X=x)=0\), whereas \(p_X(x)\) may be positive and may exceed one. Independence means \(p(x_1,x_2)=p(x_1)p(x_2)\); conditional independence given \(Y\) means \(p(x_1,x_2\mid y)=p(x_1\mid y)p(x_2\mid y)\) for relevant \(y\). Neither statement can be substituted for the other.
Example 2.22 (A shared cause creates marginal dependence). Let \(Y\sim\operatorname{Bernoulli}(1/2)\). Given \(Y\), draw \(X_1,X_2\) independently with success probability \(0.9\) when \(Y=1\) and \(0.1\) when \(Y=0\). Then \[P(X_j=1)=\tfrac12,\qquad P(X_1=X_2=1)=\tfrac12(0.9^2+0.1^2)=0.41\ne0.25.\] Thus \(X_1\perp X_2\mid Y\) but \(X_1\not\perp X_2\), with covariance \(0.41-0.25=0.16\). The laws of total expectation and variance are \[\begin{align*} \mathbb{E}[X]&=\mathbb{E}_Y[\mathbb{E}[X\mid Y]],\\ \mathrm{Var}(X)&=\mathbb{E}_Y[\mathrm{Var}(X\mid Y)]+\mathrm{Var}_Y(\mathbb{E}[X\mid Y]). \end{align*}\] Here \(\mathrm{Var}(X_j)=0.25=0.09+0.16\). This is exactly the type of conditional-independence assumption used by Naive Bayes in Part 2.
2.2.5 Likelihood, Priors, and Posterior Prediction
For observed data \(\mathcal D\), the likelihood \(L(\theta)=p(\mathcal D\mid\theta)\) is a function of \(\theta\); it is not generally a probability distribution over \(\theta\). Maximum likelihood (MLE) maximizes \(\log L\). A prior \(p(\theta)\) gives the posterior \[p(\theta\mid\mathcal D)=\frac{p(\mathcal D\mid\theta)p(\theta)}{\int p(\mathcal D\mid u)p(u)\,du}.\] Maximum a posteriori (MAP) selects its mode. Posterior prediction instead averages: \(p(y_{\rm new}\mid\mathcal D)=\int p(y_{\rm new}\mid\theta)p(\theta\mid\mathcal D)\,d\theta\). A point estimate and this integral need not give the same prediction.
Example 2.23 (Coin learning from beginning to end). For \(h\) heads and \(t\) tails in independent flips, \(L(\theta)\propto\theta^h(1-\theta)^t\). Differentiating \(h\log\theta+t\log(1-\theta)\) yields \(\hat\theta_{\rm MLE}=h/(h+t)\) when \(h+t>0\), with boundary solutions when one count is zero. A \(\operatorname{Beta}(\alpha,\beta)\) prior has density proportional to \(\theta^{\alpha-1}(1-\theta)^{\beta-1}\), so multiplication gives \[\theta\mid\mathcal D\sim\operatorname{Beta}(\alpha+h,\beta+t).\] If both posterior parameters exceed one, its interior mode is \((\alpha+h-1)/(\alpha+\beta+h+t-2)\); otherwise boundary behavior must be checked. Its mean, and hence the next-head predictive probability, is \((\alpha+h)/(\alpha+\beta+h+t)\).
With prior \(\operatorname{Beta}(2,2)\) and observations \(h=3,t=1\), the posterior is \(\operatorname{Beta}(5,3)\): \[\hat\theta_{\rm MLE}=\tfrac34,\quad \hat\theta_{\rm MAP}=\tfrac23,\quad P(\text{next head}\mid\mathcal D)=\tfrac58.\] The normalized prior and posterior densities are \(6\theta(1-\theta)\) and \(105\theta^4(1-\theta)^2\). The posterior mode and mean differ because the posterior is asymmetric.
2.2.6 Why Cross-Entropy Appears in Classification
For discrete distributions \(p,q\) on the same support, \[\begin{align*} H(p)&=-\sum_jp_j\log p_j,\qquad H(p,q)=-\sum_jp_j\log q_j,\\ D_{\rm KL}(p\|q)&=\sum_jp_j\log\frac{p_j}{q_j}=H(p,q)-H(p). \end{align*}\] Terms with \(p_j=0\) contribute zero; if \(p_j>0,q_j=0\), the divergence is infinite. Jensen’s inequality gives \(-\sum_{p_j>0}p_j\log(q_j/p_j)\ge-\log\sum_{p_j>0}q_j\ge0\). Thus, with \(p\) fixed, minimizing cross-entropy minimizes KL divergence. For one observed class, \(p\) is a one-hot vector and the loss is just \(-\log q_y\), the negative log-likelihood. Logarithms are natural throughout these likelihoods; tree entropy explicitly uses base two and is measured in bits.
2.3 Calculus for Machine Learning
2.3.1 Derivatives and Gradients
Definition 2.24 (Derivative). For a function \(f: \mathbb{R}\to \mathbb{R}\), the derivative at \(x\) is: \[f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}\] Geometric interpretation: slope of the tangent line at \(x\).
Definition 2.25 (Partial Derivative). For \(f: \mathbb{R}^n \to \mathbb{R}\), the partial derivative with respect to \(x_i\) is: \[\frac{\partial f}{\partial x_i} = \lim_{h \to 0} \frac{f(x_1, \ldots, x_i+h, \ldots, x_n) - f(x_1, \ldots, x_n)}{h}\] It measures how \(f\) changes when only \(x_i\) varies.
Definition 2.26 (Gradient). The gradient of \(f: \mathbb{R}^n \to \mathbb{R}\) is the vector of partial derivatives: \[\nabla f(\boldsymbol{x}) = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{bmatrix} \in \mathbb{R}^n\]
The gradient \(\nabla f(\boldsymbol{x})\) points in the direction of steepest ascent of \(f\) at \(\boldsymbol{x}\). To minimize \(f\), we move in the direction \(-\nabla f(\boldsymbol{x})\) (gradient descent).
Definition 2.27 (Jacobian Matrix). For \(\boldsymbol{f}: \mathbb{R}^n \to \mathbb{R}^m\), the Jacobian is: \[\boldsymbol{J} = \begin{bmatrix} \frac{\partial f_1}{\partial x_1} & \cdots & \frac{\partial f_1}{\partial x_n} \\ \vdots & \ddots & \vdots \\ \frac{\partial f_m}{\partial x_1} & \cdots & \frac{\partial f_m}{\partial x_n} \end{bmatrix} \in \mathbb{R}^{m \times n}\]
2.3.2 Chain Rule
Theorem 2.28 (Chain Rule - Scalar Case). If \(y = g(u)\) and \(u = f(x)\), then: \[\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{\mathrm{d}y}{\mathrm{d}u} \cdot \frac{\mathrm{d}u}{\mathrm{d}x}\]
Theorem 2.29 (Chain Rule - Multivariable). If \(z = f(\boldsymbol{y})\) and \(\boldsymbol{y} = g(\boldsymbol{x})\), then: \[\frac{\partial z}{\partial x_i} = \sum_j \frac{\partial z}{\partial y_j} \cdot \frac{\partial y_j}{\partial x_i}\] In matrix form: \(\nabla_{\boldsymbol{x}} z = \boldsymbol{J}_g^\top \nabla_{\boldsymbol{y}} z\).
The chain rule is the foundation of backpropagation in neural networks, allowing us to compute gradients efficiently through layers of composition.
2.3.3 Common Derivatives in ML
| Function \(f(x)\) | Derivative \(f'(x)\) |
|---|---|
| \(x^n\) | \(nx^{n-1}\) |
| \(e^x\) | \(e^x\) |
| \(\ln(x)\) | \(1/x\) |
| \(\frac{1}{1+e^{-x}}\) (sigmoid) | \(\sigma(x)(1-\sigma(x))\) |
| \(\max(0, x)\) (ReLU) | \(\begin{cases} 1 & x > 0 \\ 0 & x < 0 \end{cases}\) |
ReLU is not differentiable at zero. Its convex subdifferential there is \([0,1]\); implementations commonly select \(0\) for backpropagation.
Example 2.30 (Gradient of Linear Model). For \(f(\boldsymbol{w}) = \frac{1}{2}\left\lVert\boldsymbol{X}\boldsymbol{w} - \boldsymbol{y}\right\rVert_2^2\): \[\nabla_{\boldsymbol{w}} f = \boldsymbol{X}^\top(\boldsymbol{X}\boldsymbol{w} - \boldsymbol{y})\] This gradient is used in linear regression optimization.
2.3.4 Directional Derivatives, Curvature, and a Computation Graph
For a differentiable scalar function \(f\), the directional derivative along a unit vector \(\boldsymbol{u}\) is \(\nabla f(\boldsymbol{w})^\top\boldsymbol{u}\). Cauchy–Schwarz bounds it below by \(-\|\nabla f\|\), attained at \(\boldsymbol{u}=-\nabla f/\|\nabla f\|\) when the gradient is nonzero. This explains “steepest descent” in Euclidean geometry. The geometry matters: changing the norm changes the steepest direction.
The Hessian is \(\boldsymbol{H}_{ij}=\partial^2 f/(\partial w_i\partial w_j)\). For twice continuously differentiable \(f\), \[f(\boldsymbol{w}+\boldsymbol{h})=f(\boldsymbol{w})+\nabla f(\boldsymbol{w})^\top\boldsymbol{h} +\tfrac12\boldsymbol{h}^\top\boldsymbol{H}(\boldsymbol{w})\boldsymbol{h}+o(\|\boldsymbol{h}\|^2).\] On an open convex domain, a positive-semidefinite Hessian everywhere implies convexity. At a stationary point, a positive-definite Hessian gives a strict local minimum; an indefinite Hessian gives a saddle. A zero gradient alone is insufficient, as \(f(u)=u^3\) at zero illustrates.
Example 2.31 (Backpropagating a scalar binary loss). Take \(x=2,y=1,w=1/2,b=0\). Compute \(z=wx+b=1\), \(p=\sigma(z)=0.731059\), and \(\ell=-\log p=0.313262\). Then \[\frac{\partial\ell}{\partial p}=-\frac1p,\quad \frac{\partial p}{\partial z}=p(1-p),\quad \frac{\partial\ell}{\partial z}=p-1=-0.268941.\] Multiplying by \(\partial z/\partial w=x\) and \(\partial z/\partial b=1\) gives \(\partial\ell/\partial w=-0.537883\) and \(\partial\ell/\partial b=-0.268941\). For general \(y\in\{0,1\}\), differentiating \(-y\log p-(1-y)\log(1-p)\) gives the same cancellation, \(\partial\ell/\partial z=p-y\). Part 1 uses this derivative for logistic regression; Part 4 extends the same computation to neural-network graphs.
2.4 Optimization Basics
2.4.1 The Optimization Problem
In ML, we typically want to minimize a loss function: \[\boldsymbol{w}^* = \mathop{\mathrm{arg\,min}}_{\boldsymbol{w}} \mathcal{L}(\boldsymbol{w})\] where \(\mathcal{L}(\boldsymbol{w})\) measures prediction error on training data.
Definition 2.32 (Convex Function). A function \(f: \mathbb{R}^n \to \mathbb{R}\) is convex if for all \(\boldsymbol{x}, \boldsymbol{y}\) and \(\lambda \in [0,1]\): \[f(\lambda \boldsymbol{x} + (1-\lambda)\boldsymbol{y}) \leq \lambda f(\boldsymbol{x}) + (1-\lambda)f(\boldsymbol{y})\] Geometric interpretation: line segment between any two points on the graph lies above the graph.
Why convexity matters: Every local minimum of a convex function is a global minimum. Existence of a minimizer and convergence of an algorithm still require suitable assumptions, such as smoothness and an appropriate step size.
2.4.2 Gradient Descent
Gradient Descent Algorithm
Input: Initial point \(\boldsymbol{w}_0\), learning rate \(\eta > 0\), tolerance \(\epsilon\), iteration limit \(T_{\max}\)
Output: Approximate minimizer \(\boldsymbol{w}^*\)
Initialize \(t = 0\) and compute \(\boldsymbol{g}_0 = \nabla \mathcal{L}(\boldsymbol{w}_0)\)
while \(\left\lVert\boldsymbol{g}_t\right\rVert\geq\epsilon\) and \(t<T_{\max}\):
Update: \(\boldsymbol{w}_{t+1} = \boldsymbol{w}_t - \eta \boldsymbol{g}_t\)
\(t = t + 1\)
Recompute gradient: \(\boldsymbol{g}_t = \nabla \mathcal{L}(\boldsymbol{w}_t)\)
return \(\boldsymbol{w}_t\)
Intuition 41. Imagine you’re on a mountain and want to reach the valley in fog (can’t see far). At each step, you:
Feel which direction is steepest downhill (compute gradient)
Take a step in that direction (update parameters)
Repeat until you reach (approximately) the bottom
The learning rate \(\eta\) controls step size. Too large: you might overshoot. Too small: slow convergence.
2.4.3 Stochastic Gradient Descent (SGD)
For large datasets with \(n\) examples, computing the full gradient is expensive: \[\nabla \mathcal{L}(\boldsymbol{w}) = \frac{1}{n}\sum_{i=1}^n \nabla \mathcal{L}_i(\boldsymbol{w})\]
Stochastic Gradient Descent (SGD)
At each iteration, randomly sample one example \(i\) and update: \[\boldsymbol{w}_{t+1} = \boldsymbol{w}_t - \eta \nabla \mathcal{L}_i(\boldsymbol{w}_t)\]
Mini-batch SGD: Sample a small batch of \(b\) examples: \[\boldsymbol{w}_{t+1} = \boldsymbol{w}_t - \eta \frac{1}{b}\sum_{i \in \text{batch}} \nabla \mathcal{L}_i(\boldsymbol{w}_t)\]
Advantages of SGD:
Much faster per iteration (especially for large \(n\))
Can escape shallow local minima due to noise
Enables online learning (update as data arrives)
Trade-off: Noisier updates, may need more iterations to converge.
2.4.4 Learning Rate and Convergence
The learning rate \(\eta\) is crucial:
Too large: Divergence or oscillation
Too small: Very slow convergence
Adaptive: Start large, decay over time
Common schedules:
Step decay: \(\eta_t = \eta_0 \cdot \gamma^{\lfloor t/k \rfloor}\)
Exponential: \(\eta_t = \eta_0 e^{-\lambda t}\)
\(1/t\) decay: \(\eta_t = \eta_0 / (1 + \lambda t)\)
Theorem 2.34 (Convergence of Gradient Descent). For a convex function \(f\) with \(L\)-Lipschitz continuous gradient, an attained minimizer \(\boldsymbol{w}^*\), and fixed learning rate \(0<\eta\leq 1/L\), for \(t\geq1\): \[f(\boldsymbol{w}_t) - f(\boldsymbol{w}^*) \leq \frac{\left\lVert\boldsymbol{w}_0 - \boldsymbol{w}^*\right\rVert_2^2}{2\eta t}\] This shows convergence rate \(O(1/t)\).
Remark 43. Many ML problems are non-convex (e.g., neural networks). Gradient-based methods may approach stationary points, but neither reaching a local minimum nor finding a global minimum is guaranteed in general.
2.4.5 Beyond Basic Gradient Descent
Modern optimizers improve on vanilla gradient descent:
Momentum: Accumulates past gradients to accelerate in consistent directions \[\boldsymbol{v}_{t+1} = \beta \boldsymbol{v}_t + \eta_t \nabla \mathcal{L}(\boldsymbol{w}_t), \quad \boldsymbol{w}_{t+1} = \boldsymbol{w}_t - \boldsymbol{v}_{t+1}\]
Adam: Adapts learning rate per parameter using first and second moment estimates. It is widely used in deep learning; the update convention is specified in Section 16.
RMSProp: Uses moving average of squared gradients to normalize updates
We’ll explore these in detail in Part 4.
2.4.6 Deriving the Step-Size Restriction
If \(\nabla f\) is \(L\)-Lipschitz, the descent lemma gives \[f(\boldsymbol{w}+\boldsymbol{h})\le f(\boldsymbol{w})+\nabla f(\boldsymbol{w})^\top\boldsymbol{h}+\frac L2\|\boldsymbol{h}\|^2.\] It follows by integrating the gradient along the segment and bounding its change by \(Lt\|\boldsymbol{h}\|\). Substitution of \(\boldsymbol{h}=-\eta\nabla f(\boldsymbol{w})\) yields \[f(\boldsymbol{w}-\eta\nabla f(\boldsymbol{w}))\le f(\boldsymbol{w}) -\eta(1-L\eta/2)\|\nabla f(\boldsymbol{w})\|^2.\] Thus \(0<\eta<2/L\) ensures descent at nonstationary points; the earlier convex convergence bound uses the simpler sufficient restriction \(\eta\le1/L\). Descent alone does not establish a global minimum for a nonconvex loss.
Example 2.36 (Five gradient steps and an exact convergence law). For \(f(u)=(u-3)^2+5\), \(f'(u)=2(u-3)\) and \(L=2\). The update is \(u_{t+1}-3=(1-2\eta)(u_t-3)\). Starting from zero with \(\eta=0.1\) gives \[\begin{array}{c|rrrrrr} t&0&1&2&3&4&5\\\hline u_t&0&0.6&1.08&1.464&1.7712&2.01696 \end{array}\] and \(f(u_t)-5=9(0.8)^{2t}\). Any \(0<\eta<1\) converges in this quadratic; \(\eta=1\) cycles between \(0\) and \(6\), while \(\eta>1\) diverges unless initialized at the optimum. A rate larger than \(1/L\) can therefore work for this particular quadratic, while falling outside the earlier sufficient theorem.
Example 2.37 (Curvature in two dimensions). Let \(f(\boldsymbol{w})=\tfrac12\boldsymbol{w}^\top\boldsymbol{H}\boldsymbol{w}-\boldsymbol{c}^\top\boldsymbol{w}\), where \(\boldsymbol{H}=\left[\begin{smallmatrix}2&1\\1&2\end{smallmatrix}\right]\) and \(\boldsymbol{c}=(3,0)^\top\). Solving \(\boldsymbol{H}\boldsymbol{w}^*=\boldsymbol{c}\) gives \((2,-1)^\top\). The error obeys \[\boldsymbol{e}_{t+1}=(\boldsymbol{I}-\eta\boldsymbol{H})\boldsymbol{e}_t.\] In the two eigen-directions, errors shrink by \(1-\eta\) and \(1-3\eta\). Hence \(0<\eta<2/3\) is the exact stability interval. At \(\eta=0.6\), the steep direction alternates sign with factor \(-0.8\), producing the oscillation in Figure 6.
What makes an SGD gradient stochastic? If indices \(I_1,\ldots,I_b\) are sampled independently and uniformly with replacement, then at fixed parameters \[\boldsymbol{g}_B=\frac1b\sum_{r=1}^b\nabla\ell_{I_r},\quad \mathbb{E}[\boldsymbol{g}_B]=\nabla\widehat R,\quad \operatorname{Cov}(\boldsymbol{g}_B)=\frac1b\operatorname{Cov}(\nabla\ell_I).\] The covariance identity uses independent draws. Sampling without replacement has a finite-population correction; random reshuffling during an epoch is not conditionally independent sampling from the full dataset after earlier updates. Constant step sizes can leave persistent noise near an optimum, which motivates learning-rate schedules and averaging.
For additional derivations and exercises, see the Stanford CS229 course materials. The examples here fix their own data, loss scaling, and matrix conventions.
2.5 Summary of Part 0
ML Core Idea: Learn patterns from data rather than explicit programming
Learning Types: Supervised (labeled), unsupervised (unlabeled), reinforcement (rewards)
Linear Algebra: Vectors, matrices, eigenvalues—the language of ML
Probability: Random variables, expectations, Bayes’ rule—modeling uncertainty
Calculus: Gradients and chain rule—the engine of learning
Optimization: Gradient descent—how we actually learn from data
Next Steps: With these foundations, we’re ready to dive into specific ML algorithms. Part 1 covers supervised learning methods: regression, classification, and distance-based models.
Exercise 2.38.
Using the Jacobian convention above, show that for \(\boldsymbol{A}\in\mathbb{R}^{m\times n}\) and \(\boldsymbol{x}\in\mathbb{R}^n\), the Jacobian of \(\boldsymbol{f}(\boldsymbol{x})=\boldsymbol{A}\boldsymbol{x}\) is \(\boldsymbol{J}_f=\boldsymbol{A}\), of shape \(m\times n\). Explain why propagating a scalar-loss gradient through this map instead uses \(\boldsymbol{A}^\top\).
Prove that the sigmoid function \(\sigma(x) = 1/(1+e^{-x})\) satisfies \(\sigma'(x) = \sigma(x)(1-\sigma(x))\).
Implement gradient descent to minimize \(f(x) = (x-3)^2 + 5\) starting from \(x_0 = 0\) with learning rate \(\eta = 0.1\). Track the first 5 iterations.
Part 1: Supervised Learning (Classical Models)
3 Regression Models
In regression, we aim to predict a continuous output \(y \in \mathbb{R}\) from input features \(\boldsymbol{x} \in \mathbb{R}^d\).
3.1 Linear Regression
3.1.1 Problem Formulation
Definition 3.1 (Linear Regression Model). We model the relationship between inputs and outputs as: \[y = \boldsymbol{w}^\top \boldsymbol{x} + b + \epsilon\] where \(\boldsymbol{w} \in \mathbb{R}^d\) are weights, \(b \in \mathbb{R}\) is the bias (intercept), and \(\epsilon\) is noise.
For convenience, we absorb the bias into \(\boldsymbol{w}\) by adding a feature \(x_0 = 1\). With \(d\) original features, the augmented input and parameter vectors both lie in \(\mathbb{R}^{d+1}\): \[y \approx \hat{y} = \boldsymbol{w}^\top \boldsymbol{x} = \sum_{j=0}^d w_j x_j\]
Intuition 48. Linear regression assumes the output is a weighted sum of inputs. Think of predicting house price: \(\text{price} = w_1 \cdot \text{size} + w_2 \cdot \text{bedrooms} + w_3 \cdot \text{age} + b\). Each feature contributes linearly to the prediction.
3.1.2 Ordinary Least Squares (OLS)
Given training data \(\mathcal{D} = \{(\boldsymbol{x}_i, y_i)\}_{i=1}^n\), we want to find \(\boldsymbol{w}\) that minimizes prediction error.
Definition 3.3 (Mean Squared Error (MSE) Loss). \[\mathcal{L}(\boldsymbol{w}) = \frac{1}{n}\sum_{i=1}^n (y_i - \boldsymbol{w}^\top\boldsymbol{x}_i)^2 = \frac{1}{n}\left\lVert\boldsymbol{X}\boldsymbol{w} - \boldsymbol{y}\right\rVert_2^2\] where \(\boldsymbol{X}\in\mathbb{R}^{n\times(d+1)}\) is the augmented design matrix with rows \(\boldsymbol{x}_i^\top\), and \(\boldsymbol{y}\in\mathbb{R}^n\) is the target vector. If the intercept is handled separately, the unaugmented design matrix has shape \(n\times d\).
Why squared error?
Mathematically convenient (differentiable, convex)
Penalizes large errors more heavily
Corresponds to maximum likelihood under Gaussian noise assumption
Theorem 3.4 (Normal Equation). The optimal weights that minimize MSE are: \[\boldsymbol{w}^* = (\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top\boldsymbol{y}\] provided that \(\boldsymbol{X}^\top\boldsymbol{X}\) is invertible.
Sketch. Take the gradient of \(\mathcal{L}(\boldsymbol{w})\) and set to zero: \[\begin{align} \nabla_{\boldsymbol{w}} \mathcal{L}&= \nabla_{\boldsymbol{w}} \frac{1}{n}(\boldsymbol{X}\boldsymbol{w} - \boldsymbol{y})^\top(\boldsymbol{X}\boldsymbol{w} - \boldsymbol{y}) \\ &= \frac{2}{n}\boldsymbol{X}^\top(\boldsymbol{X}\boldsymbol{w} - \boldsymbol{y}) = 0 \end{align}\] Solving: \(\boldsymbol{X}^\top\boldsymbol{X}\boldsymbol{w} = \boldsymbol{X}^\top\boldsymbol{y} \implies \boldsymbol{w}^* = (\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top\boldsymbol{y}\). ◻
Computing the Normal Equation
Numerically preferable least-squares solve:
import numpy as np
# X includes the intercept column; y has shape (n,)
w, residuals, rank, singular_values = np.linalg.lstsq(X, y, rcond=None)
# Avoid forming X.T @ X, which squares the condition number.Complexity: \(O(nd^2 + d^3)\) - expensive for large \(d\)!
Alternative: Use gradient descent (iterative, scales better)
3.1.3 OLS as Geometry and Gaussian Maximum Likelihood
Differentiating the gradient once more gives \(\nabla^2\mathcal{L}=2\boldsymbol{X}^\top\boldsymbol{X}/n\), which is positive semidefinite, and positive definite exactly when \(\boldsymbol{X}\) has full column rank. The normal equation states that the residual \(\boldsymbol{r}=\boldsymbol{y}-\boldsymbol{X}\hat{\boldsymbol{w}}\) is orthogonal to every design column. With full column rank, \[\hat{\boldsymbol{y}}=\boldsymbol{P}\boldsymbol{y},\qquad \boldsymbol{P}=\boldsymbol{X}(\boldsymbol{X}^\top\boldsymbol{X})^{-1}\boldsymbol{X}^\top, \quad \boldsymbol{P}^\top=\boldsymbol{P},\quad \boldsymbol{P}^2=\boldsymbol{P}.\] So OLS is an orthogonal projection. With deficient rank the fitted projection is still unique, while coefficients may not be; \(\boldsymbol{X}^+\boldsymbol{y}\) selects the minimum-norm coefficients.
For a probabilistic interpretation, assume independent errors \(\epsilon_i\sim\mathcal N(0,\sigma^2)\) conditional on the fixed design. Then \[\log p(\boldsymbol{y}\mid\boldsymbol{X},\boldsymbol{w},\sigma^2) =-\frac n2\log(2\pi\sigma^2)-\frac{\|\boldsymbol{y}-\boldsymbol{X}\boldsymbol{w}\|^2}{2\sigma^2}.\] For fixed positive \(\sigma^2\), maximizing this likelihood over \(\boldsymbol{w}\) is exactly OLS. Gaussian noise is an assumption for this likelihood interpretation, not a prerequisite for defining or computing least squares. Under the correct linear mean and zero-mean finite-variance noise, OLS can still estimate the mean without Gaussian errors.
Example 3.5 (One dataset, three views of the same solution). Use \((x,y)=(0,1),(1,2),(2,2)\) and include an intercept, so \[\boldsymbol{X}=\begin{bmatrix}1&0\\1&1\\1&2\end{bmatrix},\quad \boldsymbol{X}^\top\boldsymbol{X}=\begin{bmatrix}3&3\\3&5\end{bmatrix},\quad \boldsymbol{X}^\top\boldsymbol{y}=\begin{bmatrix}5\\6\end{bmatrix}.\] Solving gives \((b,\beta)=(7/6,1/2)\) and predictions \((7/6,5/3,13/6)^\top\). The residuals are \((-1/6,1/3,-1/6)^\top\): both their sum and their dot product with \((0,1,2)\) vanish. Thus \[\mathrm{SSE}=\tfrac16,\qquad \mathrm{MSE}=\tfrac1{18}.\] This verifies the algebraic solution, the projection condition, and the Gaussian MLE simultaneously. Starting gradient descent at \((0,0)\) instead gives gradient \((-10/3,-4)\); one step with \(\eta=0.1\) yields \((1/3,2/5)\) and MSE \(14/15\), still above the optimum.
3.1.4 Gradient Descent for Linear Regression
Gradient Descent for Linear Regression
Input: Data \(\boldsymbol{X}, \boldsymbol{y}\), learning rate \(\eta\), max iterations \(T\)
Initialize: \(\boldsymbol{w}_0\) randomly
For \(t = 0, 1, \ldots, T-1\):
Compute predictions: \(\hat{\boldsymbol{y}} = \boldsymbol{X}\boldsymbol{w}_t\)
Compute gradient: \(\boldsymbol{g}_t = \frac{2}{n}\boldsymbol{X}^\top(\hat{\boldsymbol{y}} - \boldsymbol{y})\)
Update weights: \(\boldsymbol{w}_{t+1} = \boldsymbol{w}_t - \eta \boldsymbol{g}_t\)
Return: \(\boldsymbol{w}_T\)
Example 3.6 (Linear Regression in 1D). Dataset: \(\{(1, 3), (2, 5), (3, 7), (4, 9)\}\)
True relationship: \(y = 2x + 1\)
Using normal equation with \(\boldsymbol{X} = \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \\ 1 & 4 \end{bmatrix}\) and \(\boldsymbol{y} = \begin{bmatrix} 3 \\ 5 \\ 7 \\ 9 \end{bmatrix}\):
We recover \(\boldsymbol{w} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}\) (intercept and slope).
3.2 Regularization
Problem: With many features, the model can overfit—memorizing noise instead of learning the true pattern.
Solution: Add a penalty term to discourage complex models.
3.2.1 Ridge Regression
Definition 3.7 (Ridge Loss). \[\mathcal{L}_{\text{ridge}}(\boldsymbol{w}) = \frac{1}{n}\sum_{i=1}^n (y_i - \boldsymbol{w}^\top\boldsymbol{x}_i)^2 + \lambda \left\lVert\boldsymbol{w}\right\rVert_2^2\] where \(\lambda \geq 0\) is the regularization strength.
Intuition 54. Ridge penalizes large weights. The \(\ell_2\) penalty \(\left\lVert\boldsymbol{w}\right\rVert_2^2 = \sum_j w_j^2\) generally shrinks coefficients without promoting exact sparsity; individual coefficients can still be zero for particular data.
Theorem 3.9 (Ridge Solution). The optimal Ridge weights are: \[\boldsymbol{w}^*_{\text{ridge}} = (\boldsymbol{X}^\top\boldsymbol{X} + n\lambda \boldsymbol{I})^{-1}\boldsymbol{X}^\top\boldsymbol{y}\] The factor \(n\) follows from the \(1/n\) scaling of the squared loss above. This formula penalizes every component of \(\boldsymbol{w}\), including an absorbed intercept; \(\boldsymbol{X}^\top\boldsymbol{X}+n\lambda\boldsymbol{I}\) is invertible for \(\lambda>0\).
For the usual unpenalized intercept, center the features and target, apply the formula to the slope coefficients, and recover \(b=\bar y-\boldsymbol{w}^\top\bar{\boldsymbol{x}}\). The Lasso and ElasticNet formulas below likewise penalize every displayed component unless the intercept is separated.
Effect of \(\lambda\):
\(\lambda = 0\): Standard OLS (no regularization)
\(\lambda \to \infty\): \(\boldsymbol{w} \to \boldsymbol{0}\) (maximum regularization)
Intermediate \(\lambda\): Balance fit and simplicity
3.2.2 Lasso Regression (L1 Regularization)
Definition 3.10 (Lasso Loss). \[\mathcal{L}_{\text{lasso}}(\boldsymbol{w}) = \frac{1}{n}\sum_{i=1}^n (y_i - \boldsymbol{w}^\top\boldsymbol{x}_i)^2 + \lambda \left\lVert\boldsymbol{w}\right\rVert_1\] where \(\left\lVert\boldsymbol{w}\right\rVert_1 = \sum_j |w_j|\).
Lasso vs Ridge:
Ridge (\(\ell_2\)): Shrinks weights smoothly without explicitly promoting sparsity
Lasso (\(\ell_1\)): Produces sparse solutions—many weights become exactly zero
Why sparsity? The \(\ell_1\) penalty’s sharp corner at zero encourages weights to hit exactly zero, performing automatic feature selection.
When to use:
Lasso: When you believe only a few features are relevant
Ridge: When all features contribute (small weights acceptable)
3.2.3 ElasticNet
Definition 3.11 (ElasticNet Loss). Combines both penalties: \[\mathcal{L}_{\text{elastic}}(\boldsymbol{w}) = \frac{1}{n}\sum_{i=1}^n (y_i - \boldsymbol{w}^\top\boldsymbol{x}_i)^2 + \lambda_1 \left\lVert\boldsymbol{w}\right\rVert_1 + \lambda_2 \left\lVert\boldsymbol{w}\right\rVert_2^2\]
Benefit: The \(\ell_1\) term can produce sparsity; the \(\ell_2\) term stabilizes correlated coefficients and can encourage a grouping effect. Selection of every correlated feature is not guaranteed.
3.2.4 Deriving Shrinkage and Its Probabilistic Interpretation
Keep the convention \(\mathcal{L}=\mathrm{SSE}/n+\lambda\|\boldsymbol{w}\|_2^2\). Its gradient is \(2\boldsymbol{X}^\top(\boldsymbol{X}\boldsymbol{w}-\boldsymbol{y})/n+2\lambda\boldsymbol{w}\). Setting it to zero explains the factor \(n\lambda\) in the ridge normal equation. With \(\lambda>0\), penalizing all coordinates makes the Hessian positive definite even if the design is rank deficient.
If the intercept should be unpenalized, center each original feature and the target using training means, fit slopes on the centered design \(\boldsymbol{X}_c\), and recover \(b=\bar y-\hat{\boldsymbol{\beta}}^{\top}\bar{\boldsymbol{x}}\). For \(\boldsymbol{X}_c=\boldsymbol{U}\boldsymbol{S}\boldsymbol{V}^\top\), the fitted target component in left singular direction \(j\) is multiplied by \[\frac{s_j^2}{s_j^2+n\lambda}.\] Small singular directions shrink most, which stabilizes the noise amplification seen in the pseudoinverse.
Under the Gaussian observation model, independent priors \(w_j\sim\mathcal N(0,\tau^2)\) give negative log-posterior \(\mathrm{SSE}/(2\sigma^2)+\|\boldsymbol{w}\|^2/(2\tau^2)+\text{constant}\). Multiplying by \(2\sigma^2/n\) gives ridge with \(\lambda=\sigma^2/(n\tau^2)\). Independent Laplace priors with density proportional to \(\exp(-|w_j|/a)\) instead give lasso with \(\lambda=2\sigma^2/(na)\). An unpenalized intercept is excluded from these slope priors. These equalities depend on the loss scaling; a library using \(\mathrm{SSE}/(2n)\) has different numerical penalty parameters.
Example 3.12 (Ridge on the OLS dataset). For the three observations in Section 3.1.3, \(\bar x=1\), \(\bar y=5/3\), \(\sum(x_i-\bar x)^2=2\), and \(\sum(x_i-\bar x)(y_i-\bar y)=1\). With an unpenalized intercept, \[\hat\beta_\lambda=\frac1{2+3\lambda},\qquad b_\lambda=\frac53-\hat\beta_\lambda.\] At \(\lambda=1/3\), the slope is \(1/3\), the intercept is \(4/3\), and predictions are \((4/3,5/3,2)\). SSE is \(2/9\), MSE is \(2/27\), and the penalty is \(1/27\), giving objective \(1/9\). The OLS slope \(1/2\) gives the smaller MSE \(1/18\) but the larger penalized objective \(1/18+1/12=5/36\). Regularization sacrifices training fit to constrain the estimator; its test benefit still needs validation.
Why lasso gives exact zeros. The subgradient of \(|w|\) is \(\operatorname{sign}(w)\) for \(w\ne0\) and the interval \([-1,1]\) at zero. For the scalar problem \((w-a)^2+\lambda|w|\), the optimality condition \(0\in2(w-a)+\lambda\partial|w|\) gives \[\hat w=S(a,\lambda/2),\qquad S(a,t)=\operatorname{sign}(a)\max(|a|-t,0).\] For \(a=(1.2,0.2,-0.8)\) and \(\lambda=0.6\), coordinatewise lasso gives \((0.9,0,-0.5)\); ridge for the analogous separable objective gives \(a/(1+\lambda)=(0.75,0.125,-0.5)\). The lasso’s interval of subgradients at zero allows a coefficient to stay exactly zero.
For a centered design, fix other coordinates and define \(\boldsymbol{r}_j=\boldsymbol{y}-\sum_{k\ne j}\boldsymbol{x}_k w_k\). Coordinate descent for \(\mathrm{SSE}/n+\lambda_1\|\boldsymbol{w}\|_1+\lambda_2\|\boldsymbol{w}\|_2^2\) gives \[w_j\leftarrow \frac{S(\boldsymbol{x}_j^\top\boldsymbol{r}_j/n,\lambda_1/2)}{\boldsymbol{x}_j^\top\boldsymbol{x}_j/n+\lambda_2}.\] The denominator must be positive; a zero-variance feature with no quadratic penalty should be removed or treated separately. Setting \(\lambda_2=0\) recovers lasso. Scaling features inside the training fold makes coefficient penalties comparable in units.
3.3 Polynomial Regression and Basis Expansion
Definition 3.13 (Polynomial Features). To capture non-linear relationships, transform features. For input \(x\), create: \[\boldsymbol{\phi}(x) = [1, x, x^2, x^3, \ldots, x^p]^\top\] Then fit: \(y = \boldsymbol{w}^\top \boldsymbol{\phi}(x)\)
Intuition 60. Polynomial regression is still linear in parameters \(\boldsymbol{w}\), so we can use the same OLS/Ridge/Lasso methods! We just work in a transformed feature space.
Example 3.15 (Quadratic Fit). Original: \(x\). Transform: \(\boldsymbol{\phi}(x) = [1, x, x^2]^\top\).
Model: \(y = w_0 + w_1 x + w_2 x^2\) (parabola).
This captures non-linear patterns while remaining a linear model in \(\boldsymbol{w}\).
Remark 62. Danger: High-degree polynomials can severely overfit! Use regularization (Ridge/Lasso) to control complexity.
Definition 3.17 (General Basis Functions). More generally, choose \(m\) basis functions: \[y = \sum_{j=1}^m w_j \phi_j(x)\] Examples:
Polynomial: \(\phi_j(x) = x^j\)
Fourier: \(\phi_j(x) = \sin(jx), \cos(jx)\)
Gaussian (RBF): \(\phi_j(x) = \exp(-\gamma\left\lVert x - \mu_j\right\rVert^2)\)
3.3.1 Basis Design and an Exactly Solved Polynomial
A basis model is \(f(\boldsymbol{x})=\sum_{j=0}^{p}w_j\phi_j(\boldsymbol{x})\): nonlinear in the inputs can still mean linear in the parameters. Its design row is \((\phi_0(\boldsymbol{x}_i),\ldots,\phi_p(\boldsymbol{x}_i))\). A degree-\(p\) univariate polynomial has \(p+1\) coefficients; all monomials of total degree at most \(p\) in \(d\) variables have \(\binom{d+p}{p}\) coefficients, including the constant. For example, degree two in two variables includes \(1,x_1,x_2,x_1^2,x_1x_2,x_2^2\).
Example 3.18 (Interpolation is not a test of generalization). Fit \(w_0+w_1x+w_2x^2\) to \((-1,2),(0,1),(1,2)\). The middle observation gives \(w_0=1\); subtracting the two endpoint equations gives \(w_1=0\); either endpoint then gives \(w_2=1\). Training SSE is zero. The extrapolated prediction at \(x=2\) is \(5\), but no observation here establishes its accuracy. Higher-degree raw polynomial columns can be poorly conditioned; centering/scaling or orthogonal bases improve numerical behavior but do not by themselves prevent overfitting.
3.4 Logistic Regression
Task shift: From regression (continuous \(y\)) to binary classification (\(y \in \{0, 1\}\)).
3.4.1 The Sigmoid Function
Definition 3.19 (Sigmoid (Logistic) Function). \[\sigma(z) = \frac{1}{1 + e^{-z}}\] Properties:
Range: \((0, 1)\) (perfect for probabilities!)
\(\sigma(0) = 0.5\), \(\sigma(z) \to 1\) as \(z \to \infty\), \(\sigma(z) \to 0\) as \(z \to -\infty\)
Derivative: \(\sigma'(z) = \sigma(z)(1 - \sigma(z))\)
Intuition 66. We need to convert a linear combination \(\boldsymbol{w}^\top\boldsymbol{x}\) (range: \(-\infty\) to \(+\infty\)) to a probability (range: 0 to 1). The sigmoid function does exactly this smoothly!
3.4.2 Logistic Regression Model
Definition 3.21 (Logistic Regression). Model the probability of class 1: \[P(y = 1 | \boldsymbol{x}) = \sigma(\boldsymbol{w}^\top\boldsymbol{x}) = \frac{1}{1 + e^{-\boldsymbol{w}^\top\boldsymbol{x}}}\] Predict class 1 if \(P(y=1|\boldsymbol{x}) \geq 0.5\), i.e., if \(\boldsymbol{w}^\top\boldsymbol{x} \geq 0\).
Definition 3.22 (Decision Boundary). The decision boundary is where \(\boldsymbol{w}^\top\boldsymbol{x} = 0\):
\(\boldsymbol{w}^\top\boldsymbol{x} > 0 \implies\) predict class 1
\(\boldsymbol{w}^\top\boldsymbol{x} < 0 \implies\) predict class 0
This is a linear boundary in the original space (a hyperplane).
3.4.3 Cross-Entropy Loss
Definition 3.23 (Binary Cross-Entropy Loss). For binary labels \(y_i \in \{0, 1\}\): \[\mathcal{L}(\boldsymbol{w}) = -\frac{1}{n}\sum_{i=1}^n \left[y_i \log(\hat{p}_i) + (1-y_i)\log(1-\hat{p}_i)\right]\] where \(\hat{p}_i = \sigma(\boldsymbol{w}^\top\boldsymbol{x}_i)\) is the predicted probability.
Intuition 70. Cross-entropy measures how different our predicted probabilities are from the true labels:
If \(y_i = 1\) and \(\hat{p}_i \approx 1\): loss \(\approx 0\) (good)
If \(y_i = 1\) and \(\hat{p}_i \approx 0\): loss \(\to \infty\) (bad)
Theorem 3.25 (Gradient of Cross-Entropy). The gradient for logistic regression is: \[\nabla_{\boldsymbol{w}} \mathcal{L}= \frac{1}{n}\sum_{i=1}^n (\hat{p}_i - y_i)\boldsymbol{x}_i = \frac{1}{n}\boldsymbol{X}^\top(\hat{\boldsymbol{p}} - \boldsymbol{y})\] Remarkably similar to linear regression! But \(\hat{p}_i = \sigma(\boldsymbol{w}^\top\boldsymbol{x}_i)\) is non-linear.
3.4.4 Multi-Class Classification
Approach 1: One-vs-Rest (OvR)
For \(K\) classes, train \(K\) binary classifiers:
Classifier 1: class 1 vs (class 2, 3, ..., K)
Classifier 2: class 2 vs (class 1, 3, ..., K)
... and so on
At test time, predict the class with highest probability.
Definition 3.26 (Softmax Regression (Multinomial Logistic)). For \(K\) classes, model: \[P(y = k | \boldsymbol{x}) = \frac{e^{\boldsymbol{w}_k^\top\boldsymbol{x}}}{\sum_{j=1}^K e^{\boldsymbol{w}_j^\top\boldsymbol{x}}}\] The softmax function generalizes sigmoid to multiple classes.
Softmax Properties:
Outputs sum to 1: \(\sum_{k=1}^K P(y=k|\boldsymbol{x}) = 1\) (valid probability distribution)
Higher \(\boldsymbol{w}_k^\top\boldsymbol{x}\) gives higher probability for class \(k\)
For \(K=2\), \(P(y=1\mid\boldsymbol{x})=\sigma((\boldsymbol{w}_1-\boldsymbol{w}_2)^\top\boldsymbol{x})\)
Definition 3.27 (Categorical Cross-Entropy). Loss for multi-class (with one-hot encoded labels \(\boldsymbol{y}_i \in \{0,1\}^K\)): \[\mathcal{L}(\boldsymbol{W}) = -\frac{1}{n}\sum_{i=1}^n \sum_{k=1}^K y_{ik} \log(P(y=k|\boldsymbol{x}_i))\]
3.4.5 From Log-Odds to the Likelihood and Hessian
Assuming linear log-odds, \(\log\{p/(1-p)\}=\boldsymbol{w}^\top\boldsymbol{x}\), and solving for \(p\) gives the sigmoid. Independent Bernoulli observations have likelihood \(\prod_i p_i^{y_i}(1-p_i)^{1-y_i}\), so the mean negative log-likelihood is binary cross-entropy. With logits \(z_i=\boldsymbol{w}^\top\boldsymbol{x}_i\), write it stably as \[\mathcal{L}(\boldsymbol{w})=\frac1n\sum_i\bigl[\log(1+e^{z_i})-y_i z_i\bigr],\qquad \nabla\mathcal{L}=\frac1n\boldsymbol{X}^\top(\boldsymbol{p}-\boldsymbol{y}).\] Implement \(\log(1+e^z)\) as \(\max(z,0)+\log(1+e^{-|z|})\) or a stable library primitive to avoid overflow. The Hessian is \[\nabla^2\mathcal{L}=\frac1n\boldsymbol{X}^\top\boldsymbol{R}\boldsymbol{X},\qquad \boldsymbol{R}=\operatorname{diag}\{p_i(1-p_i)\}.\] For any vector \(\boldsymbol{v}\), its quadratic form is \(\sum_i p_i(1-p_i)(\boldsymbol{x}_i^\top\boldsymbol{v})^2/n\ge0\), proving convexity. Convexity does not guarantee an attained finite MLE: on strictly separable data the loss approaches zero as a separating coefficient vector grows without bound. A quadratic penalty on all parameters makes the objective coercive and strictly convex; if an intercept is exempt, additional conditions are needed for a finite optimum.
Example 3.28 (A complete gradient update). Take \(x=(-1,0,1)\), \(y=(0,0,1)\) with augmented parameter \((b,w)\). At \((0,0)\), all probabilities are \(1/2\), the loss is \(\log2=0.693147\), and \[\nabla\mathcal{L}=\frac13\begin{bmatrix}1&1&1\\-1&0&1\end{bmatrix} \begin{bmatrix}1/2\\1/2\\-1/2\end{bmatrix} =\begin{bmatrix}1/6\\-1/3\end{bmatrix}.\] A step of size one gives \((b,w)=(-1/6,1/3)\), with \[\boldsymbol{z}=(-1/2,-1/6,1/6),\qquad \boldsymbol{p}=(0.377541,0.458430,0.541570).\] The updated loss is \(0.566880\). All three labels are now correct at threshold \(1/2\), yet probabilities and loss continue changing. Classification accuracy and likelihood optimize different aspects of a prediction.
3.4.6 Probability Estimation and Decision Costs
If \(p=P(Y=1\mid\boldsymbol{x})\), false-positive cost is \(c_{FP}>0\), false-negative cost is \(c_{FN}>0\), and correct decisions cost zero, predicting one has conditional expected cost \(c_{FP}(1-p)\); predicting zero costs \(c_{FN}p\). Therefore the Bayes decision predicts one when \[p\ge t=\frac{c_{FP}}{c_{FP}+c_{FN}}.\] For costs \(4\) and \(1\), \(t=0.8\) rather than \(0.5\). In a logistic model, the boundary becomes \(\boldsymbol{w}^\top\boldsymbol{x}=\log\{t/(1-t)\}\). For the updated model above, \(t=1/2\) gives \(x=1/2\), whereas \(t=0.8\) gives \(x=1/2+3\log4\approx4.659\). This decision argument assumes probabilities appropriate for the deployment population and the stated costs. Any fitted calibration or empirically optimized threshold uses validation or out-of-fold predictions, with the final test labels kept untouched.
3.4.7 Softmax Identifiability and a Three-Class Calculation
For logits \(z_c=\boldsymbol{w}_c^\top\boldsymbol{x}\), adding the same scalar to every logit leaves softmax unchanged. Subtracting \(\max_c z_c\) before exponentiation is numerically stable; fixing a reference-class coefficient vector removes the shared-shift ambiguity in an unpenalized parameterization. With \(\boldsymbol{X}\in\mathbb{R}^{n\times(d+1)}\) and one-hot target matrix \(\boldsymbol{Y}\in\mathbb{R}^{n\times K}\), \[\nabla_{\boldsymbol{W}}\mathcal{L}=(\boldsymbol{P}-\boldsymbol{Y})^\top\boldsymbol{X}/n\in\mathbb{R}^{K\times(d+1)}.\] For one example with logits \((0,\log2,\log3)\), probabilities are \((1/6,1/3,1/2)\). If the true class is the third, the loss is \(\log2\) and the gradient with respect to logits is \((1/6,1/3,-1/2)\), whose entries sum to zero as shift invariance requires.
4 Distance-Based Models
4.1 K-Nearest Neighbors (KNN)
Definition 4.1 (KNN Algorithm). To predict the label of a new point \(\boldsymbol{x}\):
Find the \(k\) nearest training examples to \(\boldsymbol{x}\) (by distance)
For classification: Vote—assign the majority class
For regression: Average—assign the mean of their values
Intuition 76. “You are the average of your \(k\) closest friends.” KNN assumes nearby points have similar labels. It is a non-parametric method: prediction stores or indexes training examples rather than fitting a fixed-dimensional coefficient vector. Preprocessing, distance parameters, and any search index still have a training/fitting stage.
KNN Classification
Input: Training data \(\mathcal{D} = \{(\boldsymbol{x}_i, y_i)\}_{i=1}^n\), test point \(\boldsymbol{x}_{\text{test}}\), \(k\)
Compute distances: \(d_i = \left\lVert\boldsymbol{x}_{\text{test}} - \boldsymbol{x}_i\right\rVert\) for all \(i\)
Sort: Find indices of \(k\) smallest distances
Vote: \(\hat{y} = \text{mode}\{y_i : i \in \text{k-nearest}\}\)
Output: Predicted label \(\hat{y}\)
4.2 Distance Metrics
Definition 4.3 (Common Distance Metrics). For \(\boldsymbol{x}, \boldsymbol{z} \in \mathbb{R}^d\):
Euclidean (\(\ell_2\)): \(d(\boldsymbol{x}, \boldsymbol{z}) = \sqrt{\sum_{j=1}^d (x_j - z_j)^2}\)
Manhattan (\(\ell_1\)): \(d(\boldsymbol{x}, \boldsymbol{z}) = \sum_{j=1}^d |x_j - z_j|\)
Minkowski (\(\ell_p\), \(p\geq1\)): \(d(\boldsymbol{x}, \boldsymbol{z}) = \left(\sum_{j=1}^d |x_j - z_j|^p\right)^{1/p}\)
Mahalanobis: \(d(\boldsymbol{x}, \boldsymbol{z}) = \sqrt{(\boldsymbol{x}-\boldsymbol{z})^\top\boldsymbol{\Sigma}^{-1}(\boldsymbol{x}-\boldsymbol{z})}\)
where \(\boldsymbol{\Sigma}\) is a positive-definite covariance matrix fitted on training data. It accounts for correlations and feature scales; a singular covariance requires regularization or a suitably defined pseudometric.
Example 4.4 (When to Use Different Metrics).
Euclidean: Default choice, works well when features have similar scales
Manhattan: Uses absolute coordinate differences; still requires appropriate feature scaling when units differ
Mahalanobis: When features are correlated or have vastly different variances
4.3 Weighted KNN
Definition 4.5 (Distance-Weighted KNN). Instead of equal votes, one smoothed inverse-distance rule, with fixed \(\epsilon>0\), is: \[w_i = \frac{1}{d(\boldsymbol{x}_{\text{test}}, \boldsymbol{x}_i) + \epsilon}\] Then predict: \(\hat{y} = \mathop{\mathrm{arg\,max}}_c \sum_{i \in \text{k-nearest, class } c} w_i\)
Benefit: Closer neighbors have more influence, which often improves accuracy.
4.4 The Curse of Dimensionality
Distances can concentrate in high dimensions under suitable distributional assumptions; this is not a statement about every dataset.
Example: Let \(\boldsymbol{x},\boldsymbol{z}\) be independent and uniform on \([0,1]^d\) with independent coordinates. Then \[\mathbb{E}[\left\lVert\boldsymbol{x}-\boldsymbol{z}\right\rVert_2^2]=d/6,\qquad \mathrm{Var}(\left\lVert\boldsymbol{x}-\boldsymbol{z}\right\rVert_2^2)=7d/180.\] Thus the relative fluctuations of squared distance shrink as \(O(d^{-1/2})\), and typical distance is about \(\sqrt{d/6}\). Maintaining a fixed resolution in every coordinate can require exponentially many samples. Low intrinsic dimension or informative structure can substantially change this behavior.
Impact on KNN:
Nearest neighbors aren’t actually “near”
Maintaining fixed coordinate-wise resolution can require exponentially more data as \(d\) grows
Performance degrades in high dimensions
Solutions:
Feature selection/dimensionality reduction (PCA, feature engineering)
Choose a distance suited to the data; cosine similarity can help for directional data but does not universally remove high-dimensional difficulties
Regularized methods that work better in high \(d\)
4.5 Choosing k
\(k=1\): Very flexible, but sensitive to noise (high variance)
Large \(k\): Smoother, but may miss local patterns (high bias)
Optimal \(k\): Use cross-validation to select
Remark 80. KNN is a lazy learner. Brute-force prediction compares the query with all stored examples; KD-tree or ball-tree indexes can speed some searches, depending on dimension, metric, and data geometry. Build the index and fit any scaling on training data only.
4.6 A Complete Neighbor Calculation and the Effect of Units
Example 4.7 (Voting, weighting, and regression). Let the query be \(\boldsymbol{q}=(4,3)\). Use the following six training observations:
| Index | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| \(\boldsymbol{x}_i\) | \((1,1)\) | \((2,2)\) | \((3,1)\) | \((6,5)\) | \((7,7)\) | \((8,6)\) |
| \(y_i\) | \(+\) | \(+\) | \(+\) | \(-\) | \(-\) | \(-\) |
| \(\|\boldsymbol{x}_i-\boldsymbol{q}\|^2\) | 13 | 5 | 5 | 8 | 25 | 25 |
For \(k=3\), indices \(2,3,4\) are selected, giving positive-class vote fraction \(2/3\). With exact inverse-distance weights \(1/d_i\) (all selected distances here are positive), that fraction becomes \[\frac{2/\sqrt5}{2/\sqrt5+1/\sqrt8}\approx0.717.\] The two equal distances do not change this neighbor set. A reproducible implementation must specify how to break ties at the \(k\)th neighbor or in class votes. If a query exactly matches training points, inverse-distance weighting needs an explicit zero-distance rule, such as voting only among those matches. For regression targets \(10,20,50\) on these three neighbors, unweighted KNN predicts \((10+20+50)/3=80/3\). Local vote fractions estimate local conditional frequencies; they are not automatically well calibrated probabilities.
Example 4.8 (Scaling changes the model). Use \(A=(0,0),B=(1,10),C=(2,0),D=(3,10)\), with labels \(0,0,1,1\). For query \((1.1,4.8)\), raw squared distances to \(B,C\) are \(27.05,23.85\); checking \(A,D\) gives \(24.25,30.65\). Raw 1-NN therefore predicts class 1 from \(C\). Training feature means are \((1.5,5)\) and population standard deviations are \((\sqrt{1.25},5)\). After dividing coordinate differences by these training scales, the four squared distances are \[1.8896,\quad1.0896,\quad1.5696,\quad3.9696.\] Now \(B\) is nearest and the prediction is class 0. Scaling is a choice of metric and must be fitted on the training fold, as in Section 1.3; the query must not change these scales.
For positive-definite covariance \(\boldsymbol{\Sigma}=\boldsymbol{Q}\boldsymbol{\Lambda}\boldsymbol{Q}^\top\), the whitened coordinates \(\boldsymbol{\Lambda}^{-1/2}\boldsymbol{Q}^\top\boldsymbol{x}\) turn Euclidean distance into Mahalanobis distance: \[\|\boldsymbol{\Lambda}^{-1/2}\boldsymbol{Q}^\top(\boldsymbol{x}-\boldsymbol{z})\|^2 =(\boldsymbol{x}-\boldsymbol{z})^\top\boldsymbol{\Sigma}^{-1}(\boldsymbol{x}-\boldsymbol{z}).\] Estimating this covariance is itself a learned transformation; singular covariance requires regularization or dimension reduction rather than an ordinary inverse.
5 Decision Trees and Rule-Based Methods
5.1 Decision Tree Basics
Definition 5.1 (Decision Tree). A tree structure where:
Internal nodes: Tests on features (e.g., \(x_2 < 5\)?)
Branches: Outcomes of tests
Leaf nodes: Predictions (class label or value)
Prediction: Start at root, follow branches based on feature values until reaching a leaf.
Intuition 84. Decision trees mimic human decision-making: “If age < 30 AND income > 50K, then approve loan.” They’re highly interpretable!
5.2 Splitting Criteria
Key question: At each node, which feature and threshold should we split on?
Goal: Create pure subsets (all same class or similar values).
5.2.1 Entropy and Information Gain
Definition 5.3 (Entropy (Classification)). For a set \(S\) with class distribution \(p_1, p_2, \ldots, p_K\): \[H(S) = -\sum_{k=1}^K p_k \log_2(p_k)\] Entropy measures impurity/uncertainty.
\(H = 0\): Perfectly pure (all one class)
\(H = \log_2(K)\): Maximum impurity (uniform distribution)
Definition 5.4 (Information Gain). The reduction in entropy from splitting on feature \(A\): \[\text{IG}(S, A) = H(S) - \sum_{v \in \text{values}(A)} \frac{|S_v|}{|S|} H(S_v)\] where \(S_v\) is the subset of \(S\) where feature \(A\) has value \(v\).
Choose split: \(A^* = \mathop{\mathrm{arg\,max}}_A \text{IG}(S, A)\)
Example 5.5 (Entropy Calculation). Dataset: 9 positive, 5 negative examples. \[H(S) = -\frac{9}{14}\log_2\left(\frac{9}{14}\right) - \frac{5}{14}\log_2\left(\frac{5}{14}\right) \approx 0.940\]
After splitting on feature \(A\):
Branch 1: 6 pos, 1 neg \(\implies H = 0.592\)
Branch 2: 3 pos, 4 neg \(\implies H = 0.985\)
\[\text{IG} \approx 0.940 - \left(\frac{7}{14} \cdot 0.592 + \frac{7}{14} \cdot 0.985\right) \approx 0.152\]
5.2.2 Gini Index
Definition 5.6 (Gini Impurity). \[\text{Gini}(S) = 1 - \sum_{k=1}^K p_k^2\] Alternative to entropy, computationally simpler (no logarithms).
Gini = 0: Pure node
Gini = \(1 - 1/K\): Maximum impurity (for \(K\) classes)
Entropy vs Gini: Both work well in practice. Gini is slightly faster; entropy more theoretically motivated.
5.3 Tree Growing Algorithms
ID3 Algorithm (Iterative Dichotomiser 3)
Input: Dataset \(S\), remaining feature set \(A\), and parent-majority default class
Base cases:
If \(S\) is empty: return a leaf with the parent-majority default class
If all examples in \(S\) have same class: return leaf with that class
If no features left: return leaf with majority class
Recursive case:
Find best feature: \(A^* = \mathop{\mathrm{arg\,max}}_A \text{IG}(S, A)\)
Create node for \(A^*\)
For each value \(v\) of \(A^*\):
Add branch for \(A^* = v\)
Recursively build on \(S_v\) with remaining features \(A\setminus\{A^*\}\) and the current node majority as the default
Return: Decision tree
Remark 89 (Tree Algorithms).
ID3: Original, uses information gain, only categorical features
C4.5: Extension of ID3, handles continuous features and missing values
CART (Classification and Regression Trees): Builds binary trees; classification may use Gini impurity, while squared-error regression uses the leaf/variance criterion below
5.4 Regression Trees
For regression, use variance reduction instead of information gain:
Definition 5.8 (Variance Reduction). \[\text{VR}(S, A) = \mathrm{Var}(S) - \sum_{v} \frac{|S_v|}{|S|} \mathrm{Var}(S_v)\] where \(\mathrm{Var}(S) = \frac{1}{|S|}\sum_{i \in S}(y_i - \bar{y})^2\).
At leaves, predict the mean: \(\hat{y} = \frac{1}{|S|}\sum_{i \in S} y_i\).
5.5 Pruning
Problem: Trees can grow very deep and overfit the training data.
Solution: Pruning—simplify the tree by removing branches.
Definition 5.9 (Pre-Pruning (Early Stopping)). Stop growing the tree early if:
Maximum depth reached
Node contains fewer than min_samples_split examples
Information gain below threshold
Definition 5.10 (Post-Pruning). Grow full tree, then prune back:
Grow complete tree
For each internal node, evaluate: “Does removing this subtree improve validation performance?”
If yes, replace subtree with leaf (using majority class or mean)
Cost-Complexity Pruning: Balance tree size and error: \[\text{Cost} = \text{Error}(\text{tree}) + \alpha \cdot |\text{leaves}|\] Increase \(\alpha\) to get simpler trees.
5.6 Interpretability vs Performance
Advantages of Decision Trees:
Interpretable: Easy to visualize and explain (“If-then” rules)
Non-parametric: No fixed finite-dimensional distribution family; the tree still imposes a recursive partitioning structure
Handles mixed data: Both categorical and numerical features
Feature interactions: Automatically captures interactions
Disadvantages:
High variance: Small data changes can drastically alter tree structure
Greedy: Locally optimal splits may not be globally optimal
Bias toward features with more levels: Tend to favor categorical features with many values
Overfitting: Without pruning, can memorize training data
When to use:
When interpretability is crucial (medical diagnosis, loan approval)
As a baseline or for feature engineering
As components in ensemble methods (Random Forests, Boosting)
5.7 Deriving Leaf Predictions and Working Through a Tree
For a classification leaf with empirical class proportions \(\hat p_c\), its mean categorical negative log-likelihood is \(-\sum_c\hat p_c\log q_c\). A Lagrange multiplier for \(\sum_c q_c=1\) gives the optimum \(q_c=\hat p_c\) and minimum entropy \(H(\hat p)\). Therefore a weighted entropy reduction is an improvement in the best leaf likelihood, up to the log-base scale. Gini impurity also has a loss interpretation: for one-hot target \(\boldsymbol{e}_Y\), \[\min_{\boldsymbol{q}}\mathbb{E}\|\boldsymbol{e}_Y-\boldsymbol{q}\|^2 =1-\sum_c\hat p_c^2,\] attained at \(\boldsymbol{q}=\hat{\boldsymbol{p}}\). These are different impurity criteria and need not rank all candidate splits identically.
Example 5.11 (All candidate thresholds, then pruning). Consider eight observations with two features \(x,B\):
| \(x\) | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| \(B\) | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 |
| \(y\) | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
The root contains four of each class, so entropy is one bit. For thresholds halfway between consecutive \(x\) values, the information gains are
| Threshold | 1.5 | 2.5 | 3.5 | 4.5 | 5.5 | 6.5 | 7.5 |
|---|---|---|---|---|---|---|---|
| Gain (bits) | .137925 | .311278 | .548795 | .188722 | .048795 | 0 | .137925 |
For the best split at \(3.5\), the left child is pure and the right has four positives and one negative. Thus the weighted entropy is \((3/8)0+(5/8)H_2(4/5)=0.451205\). Splitting on \(B\) gives two balanced children and zero gain. The best root is therefore \(x\le3.5\). Splitting its right child at \(7.5\) makes both children pure. The resulting rule predicts 1 only for \(3.5<x\le7.5\), so a query \((x,B)=(6,1)\) is classified as 1.
Measure pruning risk by the training misclassification fraction, using any fixed rule for the tied root majority. The full tree has risk 0 and 3 leaves; its root-only split (stump) has risk \(1/8\) and 2 leaves; a single root leaf has risk \(1/2\). Cost-complexity objectives are respectively \[3\alpha,\qquad\tfrac18+2\alpha,\qquad\tfrac12+\alpha.\] The preferred size changes at \(\alpha=1/8\) and \(3/8\) (ties at the boundaries). On a separate validation set \(x=(2,4,6,8)\) with labels \((0,1,1,1)\), the full tree makes one error and the stump makes none. This can favor the pruned tree even though it has worse training error. The validation labels select the subtree; final test labels do not.
Example 5.12 (A regression split with every SSE shown). A leaf predicts a constant \(a\) minimizing \(\sum_i(y_i-a)^2\); differentiating gives \(a=\bar y\). For \(x=(1,2,3,4)\) and \(y=(2,3,8,9)\), the root mean is \(5.5\) and SSE is \(12.25+6.25+6.25+12.25=37\). Splitting at \(x=2.5\) gives means \(2.5\) and \(8.5\), each child SSE \(0.5\), and total SSE \(1\). The reduction is \(36\). Squared-error regression trees choose splits by this reduction, not by classification entropy.
6 Bias–Variance Tradeoff
6.1 Decomposition of Prediction Error
Fix a test input \(\boldsymbol{x}\) and suppose \(y=f(\boldsymbol{x})+\epsilon\), with \(\mathbb{E}[\epsilon\mid\boldsymbol{x}]=0\) and \(\mathrm{Var}(\epsilon\mid\boldsymbol{x})=\sigma^2\). The fitted predictor \(\hat f\) varies with the training set, which is independent of the test noise.
Theorem 6.1 (Bias-Variance Decomposition). The expected test error at a point \(\boldsymbol{x}\) is: \[\mathbb{E}[(\hat{f}(\boldsymbol{x}) - y)^2] = \underbrace{(\mathbb{E}[\hat{f}(\boldsymbol{x})] - f(\boldsymbol{x}))^2}_{\text{Bias}^2} + \underbrace{\mathbb{E}[(\hat{f}(\boldsymbol{x}) - \mathbb{E}[\hat{f}(\boldsymbol{x})])^2]}_{\text{Variance}} + \underbrace{\sigma^2}_{\text{Irreducible Error}}\] On the left, expectation is over training-set randomness and independent test noise; expectations involving only the fitted predictor are over training sets.
Sketch. \[\begin{align} \mathbb{E}[(\hat{f}(\boldsymbol{x}) - y)^2] &= \mathbb{E}[(\hat{f}(\boldsymbol{x}) - f(\boldsymbol{x}) + f(\boldsymbol{x}) - y)^2] \\ &= \mathbb{E}[(\hat{f}(\boldsymbol{x}) - f(\boldsymbol{x}))^2] + \mathbb{E}[(f(\boldsymbol{x}) - y)^2] \\ &\quad + 2\mathbb{E}[(\hat{f}(\boldsymbol{x}) - f(\boldsymbol{x}))(f(\boldsymbol{x}) - y)] \end{align}\] The cross term vanishes since \(f(\boldsymbol{x})\) and \(\hat{f}(\boldsymbol{x})\) are independent of \(\epsilon = y - f(\boldsymbol{x})\).
Expanding the first term: \[\begin{align} \mathbb{E}[(\hat{f}(\boldsymbol{x}) - f(\boldsymbol{x}))^2] &= \mathbb{E}[(\hat{f}(\boldsymbol{x}) - \mathbb{E}[\hat{f}] + \mathbb{E}[\hat{f}] - f)^2] \\ &= \underbrace{\mathrm{Var}(\hat{f}(\boldsymbol{x}))}_{\text{Variance}} + \underbrace{(\mathbb{E}[\hat{f}(\boldsymbol{x})] - f(\boldsymbol{x}))^2}_{\text{Bias}^2} \end{align}\] ◻
6.2 Understanding Bias and Variance
Definition 6.2 (Bias). Bias measures how far the average prediction (over many training sets) is from the true value.
High bias = underfitting:
Model is too simple to capture the true pattern
Example: Linear model for non-linear data
Definition 6.3 (Variance). Variance measures how much predictions vary across different training sets.
High variance = overfitting:
Model is too sensitive to training data fluctuations
Example: Very deep decision tree
Intuition 98. Think of shooting arrows at a target:
Low bias, low variance: Arrows cluster tightly around bullseye (ideal)
High bias, low variance: Arrows cluster tightly, but away from bullseye (systematic error)
Low bias, high variance: Arrows scattered around bullseye (inconsistent)
High bias, high variance: Arrows scattered far from bullseye (worst case)
6.3 Model Complexity and the Tradeoff
In the classical schematic tradeoff, increasing model complexity often has the following tendencies:
Bias decreases: More flexible models can fit data better
Variance increases: More flexibility means more sensitivity to data
Sweet spot: Balance bias and variance to minimize total error.
6.4 Examples by Model Type
| Model | Bias | Variance |
|---|---|---|
| Linear Regression | High (if data non-linear) | Low |
| High-degree Polynomial | Low | High |
| KNN with \(k=1\) | Low | High |
| KNN with large \(k\) | High | Low |
| Shallow Decision Tree | High | Low |
| Deep Decision Tree | Low | High |
6.5 Controlling the Tradeoff
6.5.1 Cross-Validation
Definition 6.5 (\(k\)-Fold Cross-Validation: preview). Partition the current non-test training data into \(k\) approximately equal folds. Fit the complete procedure on the other folds and validate on the held-out fold, repeating once per fold. Use these scores for model selection; full algorithms, unequal-fold aggregation, uncertainty, and group/time alternatives are in Sections 22.3 and 23.1.1. This inner selection score is not a final test estimate of the selected procedure.
Definition 6.6 (Leave-One-Out Cross-Validation (LOOCV)). Special case with \(k = n\) (number of examples). Train on \(n-1\) examples, test on 1. Repeat for each example.
Pros: Each fit uses \(n-1\) observations, so its training size is close to the final fit. The resulting risk estimate need not be exactly unbiased and can have high variance.
Cons: Computationally expensive (\(n\) model fits)
6.5.2 Regularization
As discussed earlier, regularization (Ridge, Lasso, ElasticNet) explicitly controls model complexity:
Can increase bias by restricting the fitted procedure; the effect is model- and distribution-dependent
Can reduce variance; improved total test risk still requires validation
Tune \(\lambda\) via cross-validation to find optimal tradeoff
6.5.3 Ensemble Methods
Preview of Part 3: Averaging predictors with the same expectation preserves their common bias; changing how base models are fitted can also change bias. The precise dependence calculation is in Section 10.1:
Bagging (e.g., Random Forests): Reduces variance by averaging
Boosting (e.g., XGBoost): Sequentially optimizes a declared training loss; bias, variance, and test-risk changes depend on the procedure
6.6 Exact Arithmetic and a Repeated-Training Experiment
Example 6.7 (Computing every term at a fixed input). Let the true mean at a fixed input be \(f(x)=1\), with independent test noise of mean zero and variance \(0.25\). Suppose two equally likely training datasets yield predictions \(0.8,1.2\) for procedure A. Its mean prediction is 1, bias squared is 0, variance is \([(0.8-1)^2+(1.2-1)^2]/2=0.04\), and expected test MSE is \(0.29\). Procedure B yields \(0.6,0.8\), so its mean is \(0.7\), bias squared is \(0.09\), variance is \(0.01\), and test MSE is \(0.35\). Lower variance alone does not imply lower error.
The decomposition can be estimated by training repeatedly on synthetic datasets where the true mean is known. Here each of 400 datasets has 20 independent inputs uniform on \([-1,1]\), targets \(y=x^2+\epsilon\), and \(\epsilon\sim\mathcal N(0,0.3^2)\). Fit degree-1, degree-2, and degree-5 polynomials by least squares. At the fixed input \(x=0\), let \(\bar f\) be the mean of the 400 fitted predictions and use empirical variance with divisor 400: \[\widehat{\mathrm{Bias}^2}=(\bar f-0)^2,\quad \widehat{\mathrm{Var}}=\frac1{400}\sum_{r=1}^{400}(\hat f_r-\bar f)^2.\] The displayed estimates are finite Monte Carlo estimates of the population bias and variance, not exact population values or confidence intervals. The empirical identity \(\frac1{400}\sum_r(\hat f_r-f)^2=(\bar f-f)^2+\frac1{400}\sum_r(\hat f_r-\bar f)^2\) is exact; adding the known noise variance gives the corresponding estimated test risk.
| Degree | Estimated bias\(^2\) | Estimated variance | Noise | Sum |
|---|---|---|---|---|
| 1 | .098978 | .009786 | .090000 | .198764 |
| 2 | .000003 | .009851 | .090000 | .099855 |
| 5 | .000009 | .021381 | .090000 | .111390 |
Real datasets do not provide repeated independent training samples and a known generating mean. Cross-validation estimates predictive performance of a fitting procedure, not separate ground-truth bias and variance terms. Select preprocessing, model complexity, and regularization inside the validation workflow of Section 1.3; do not select them by repeatedly inspecting a final test score.
6.7 Summary of Part 1
Linear Regression: Foundation of supervised learning. Normal equation for closed-form; gradient descent for iterative solution.
Regularization: Ridge (\(\ell_2\)) for shrinkage, Lasso (\(\ell_1\)) for sparsity. Essential for high-dimensional data.
Logistic Regression: Linear model for classification using sigmoid function and cross-entropy loss.
KNN: Non-parametric, instance-based learning. Simple but suffers from curse of dimensionality.
Decision Trees: Interpretable, handles non-linear patterns. Prone to overfitting without pruning.
Bias-Variance Tradeoff: Squared test risk decomposes at a fixed input into squared bias, variance, and noise. Increasing flexibility often reduces approximation bias but can increase variance; the behavior depends on the fitted procedure. Use validation to assess predictive risk.
Next Steps: Part 2 develops probabilistic models such as Naive Bayes and GDA, then maximum-margin methods such as SVMs. Their scores have different interpretations: an uncalibrated SVM score is not a posterior probability.
Exercise 6.8.
Derive the gradient of the Ridge loss with its stated \(1/n\) scaling and show that it leads to \(\boldsymbol{w}^* = (\boldsymbol{X}^\top\boldsymbol{X} + n\lambda\boldsymbol{I})^{-1}\boldsymbol{X}^\top\boldsymbol{y}\). State whether the intercept is penalized.
Show that the mean logistic-loss Hessian is positive semidefinite. Explain why convexity alone does not guarantee a finite MLE on separable data, and state how a penalty changes the problem.
For a dataset with 8 positive and 4 negative examples, compute the entropy. If a feature splits it into (6 pos, 1 neg) and (2 pos, 3 neg), compute the information gain.
Implement KNN (\(k=3\)) with positive points \((1,1)\), \((2,2)\), \((3,1)\) and negative points \((6,5)\), \((7,7)\), \((8,6)\). Classify \((4,3)\).
For univariate polynomial regression of degree \(p\), including an intercept, how many parameters are in the model? How does increasing \(p\) affect flexibility and the risk of overfitting?
Draw a bias-variance diagram and mark where the following would fall: (a) \(k=1\) KNN, (b) Linear regression on non-linear data, (c) Deep decision tree.
Part 2: Probabilistic Models
7 Naive Bayes
7.1 Probabilistic Classification Framework
Generative classifiers model \(P(\boldsymbol{x},y)\) and use Bayes’ rule. Discriminative classifiers instead learn conditional probabilities or a decision function directly, without modeling the input distribution.
Definition 7.1 (Bayes’ Rule for Classification). Given features \(\boldsymbol{x}\) and class \(y \in \{1, 2, \ldots, K\}\): \[P(y = c | \boldsymbol{x}) = \frac{P(\boldsymbol{x} | y = c) \cdot P(y = c)}{P(\boldsymbol{x})} = \frac{P(\boldsymbol{x} | y = c) \cdot P(y = c)}{\sum_{k=1}^K P(\boldsymbol{x} | y = k) \cdot P(y = k)}\] where:
\(P(y=c|\boldsymbol{x})\) is the posterior probability (what we want)
\(P(\boldsymbol{x}|y=c)\) is the likelihood (how likely are these features given class \(c\))
\(P(y=c)\) is the prior (how common is class \(c\) in general)
\(P(\boldsymbol{x})\) is the evidence (normalization constant)
Classification rule: \[\hat{y} = \mathop{\mathrm{arg\,max}}_{c} P(y=c|\boldsymbol{x}) = \mathop{\mathrm{arg\,max}}_{c} P(\boldsymbol{x}|y=c) \cdot P(y=c)\] We can ignore \(P(\boldsymbol{x})\) since it doesn’t depend on \(c\).
7.2 The Naive Bayes Assumption
Challenge: An unrestricted joint probability table for \(d\) categorical features with \(K\) values each has \(K^d-1\) parameters per class. Structured parametric models need not have this exponential parameter count.
Solution: Assume conditional independence.
Definition 7.2 (Naive Bayes Assumption). Features are conditionally independent given the class: \[P(\boldsymbol{x} | y = c) = P(x_1, x_2, \ldots, x_d | y = c) = \prod_{j=1}^d P(x_j | y = c)\]
Intuition 105. “Naive” because we assume features don’t interact given the class. For spam detection: knowing an email contains “free” doesn’t change the probability of “money” appearing, given we know it’s spam. This is often false in reality, but works surprisingly well in practice!
Theorem 7.4 (Naive Bayes Classifier). \[\hat{y} = \mathop{\mathrm{arg\,max}}_{c} P(y=c) \prod_{j=1}^d P(x_j | y=c)\] In log space (for numerical stability): \[\hat{y} = \mathop{\mathrm{arg\,max}}_{c} \left[\log P(y=c) + \sum_{j=1}^d \log P(x_j | y=c)\right]\]
7.3 Estimating Parameters
From training data \(\mathcal{D} = \{(\boldsymbol{x}_i, y_i)\}_{i=1}^n\):
Definition 7.5 (Prior Estimation). \[P(y = c) = \frac{\text{count}(y=c)}{n}\] Simply the fraction of training examples in class \(c\).
Definition 7.6 (Likelihood Estimation). Depends on the type of features:
Categorical: \(P(x_j = v | y=c) = \frac{\text{count}(x_j=v, y=c)}{\text{count}(y=c)}\)
Continuous: Assume a distribution (e.g., Gaussian) and estimate parameters
7.4 Variants of Naive Bayes
7.4.1 Gaussian Naive Bayes
For continuous features, assume each feature follows a Gaussian distribution.
Definition 7.7 (Gaussian Naive Bayes). Assume \(X_j\mid y=c\sim\mathcal{N}(\mu_{jc},\sigma_{jc}^2)\) with \(\sigma_{jc}^2>0\); its conditional density is: \[P(x_j | y=c) = \frac{1}{\sqrt{2\pi\sigma_{jc}^2}} \exp\left(-\frac{(x_j - \mu_{jc})^2}{2\sigma_{jc}^2}\right)\] where \(\mu_{jc}\) and \(\sigma_{jc}^2\) are estimated from training data: \[\mu_{jc} = \frac{1}{n_c}\sum_{i: y_i=c} x_{ij}, \quad \sigma_{jc}^2 = \frac{1}{n_c}\sum_{i: y_i=c} (x_{ij} - \mu_{jc})^2\]
Example 7.8 (Medical Diagnosis). Predict disease (yes/no) from symptoms: temperature and blood pressure.
Training data:
Disease=Yes (3 examples): temps = [38.5, 39.0, 38.7], BP = [140, 145, 142]
Disease=No (2 examples): temps = [36.8, 37.1], BP = [120, 118]
Estimates:
\(P(\text{Disease}=\text{Yes}) = 3/5 = 0.6\)
\(\mu_{\text{temp,yes}} = 38.73\), \(\sigma_{\text{temp,yes}}^2 \approx 0.04222\)
\(\mu_{\text{temp,no}} = 36.95\), \(\sigma_{\text{temp,no}}^2 = 0.0225\)
Similar for blood pressure
Test: Patient with temp=38.0, BP=135. Compute both posteriors and predict the larger.
7.4.2 Multinomial Naive Bayes
For count data (e.g., word frequencies in documents).
Definition 7.9 (Multinomial Naive Bayes). Each \(x_j\) is a token count. Conditional on class and document length \(N=\sum_jx_j\), token positions are modeled as independent categorical draws; the resulting counts are multinomial and are not mutually independent for fixed \(N\). Model: \[P(\boldsymbol{x} | y=c) = \frac{\left(\sum_j x_j\right)!}{\prod_j x_j!} \prod_{j=1}^d \theta_{jc}^{x_j}\] where \(\theta_{jc} = P(\text{feature } j | y=c)\).
Parameter estimation (with Laplace smoothing): \[\theta_{jc} = \frac{\text{count}(x_j, y=c) + \alpha}{\sum_{j'} \text{count}(x_{j'}, y=c) + \alpha d}\] \(\alpha > 0\) is a smoothing parameter (typically \(\alpha=1\)).
Intuition 112. Laplace smoothing prevents zero probabilities. If a word never appears in spam training data, we still assign it a small non-zero probability rather than zero (which would make the entire product zero).
Example 7.11 (Text Classification). Classify documents as “sports” or “politics”.
Vocabulary: {game, team, vote, election, win}
Training:
Sports docs: “game win”, “team game”, “team win win”
Politics docs: “vote election”, “election win”
Word counts by class:
Sports: game=2, team=2, vote=0, election=0, win=3 (7 tokens)
Politics: game=0, team=0, vote=1, election=2, win=1
With \(\alpha=1\): \[\theta_{\text{game,sports}} = \frac{2+1}{7+5} = \frac{3}{12} = 0.25\]
Test: “game election”. The document priors are \(3/5\) and \(2/5\). Omitting the common multinomial coefficient, the two scores are \[s_{\mathrm{sports}}=\frac35\frac3{12}\frac1{12}=\frac1{80},\qquad s_{\mathrm{politics}}=\frac25\frac1{9}\frac3{9}=\frac2{135}.\] Normalizing gives \(P(\mathrm{sports}\mid\mathrm{doc})=27/59\approx0.458\) and \(P(\mathrm{politics}\mid\mathrm{doc})=32/59\approx0.542\), so predict politics.
7.4.3 Bernoulli Naive Bayes
For binary features (presence/absence).
Definition 7.12 (Bernoulli Naive Bayes). Each \(x_j \in \{0, 1\}\) indicates feature presence: \[P(x_j | y=c) = \theta_{jc}^{x_j}(1-\theta_{jc})^{1-x_j}\] where \(\theta_{jc} = P(x_j=1 | y=c)\).
Estimation: \[\theta_{jc} = \frac{\text{count}(x_j=1, y=c) + \alpha}{\text{count}(y=c) + 2\alpha}\]
Counts vs presence: Multinomial NB uses word counts. Bernoulli NB uses presence and absence: “Does word \(j\) appear?”
7.5 Likelihood Derivations and Completed Probability Calculations
For class \(c\), the labeled-data log-likelihood separates into \(n_c\log\pi_c\) and one feature likelihood per class. Maximizing the prior terms subject to \(\sum_c\pi_c=1\) gives \(\hat\pi_c=n_c/n\). For a Gaussian feature, differentiation gives \[\hat\mu_{cj}=\frac1{n_c}\sum_{i:y_i=c}x_{ij},\qquad \hat\sigma_{cj}^2=\frac1{n_c}\sum_{i:y_i=c}(x_{ij}-\hat\mu_{cj})^2.\] The divisor is \(n_c\) for MLE, not \(n_c-1\). With one example or a constant feature in a class, the estimate is zero and the density formula is degenerate; a variance floor or smoothing rule is needed, fitted using training data only.
Why add-one smoothing is a predictive calculation. For multinomial parameters \(\boldsymbol{\theta}\) with Dirichlet prior \(\operatorname{Dirichlet}(\alpha_1,\ldots,\alpha_V)\) and counts \(N_j\), the posterior is \(\operatorname{Dirichlet}(N_j+\alpha_j)\). Integrating the next token gives predictive probability \((N_j+\alpha_j)/(N+\sum_k\alpha_k)\). Symmetric \(\alpha_j=1\) gives add-one smoothing. This is a posterior mean/predictive probability, not the posterior mode: when an interior mode exists, that mode subtracts one from every posterior parameter before normalization.
Example 7.13 (Finishing the medical Gaussian NB example). For the training observations above, the Disease=Yes feature means and MLE variances are \[\boldsymbol{\mu}_{\rm yes}=(38.733333,142.333333),\quad \boldsymbol{\sigma}^2_{\rm yes}=(0.042222,4.222222),\] while Disease=No has \(\boldsymbol{\mu}_{\rm no}=(36.95,119)\) and \(\boldsymbol{\sigma}^2_{\rm no}=(0.0225,1)\). At test input \((38,135)\), compute each score as \[s_c=\log\pi_c-\frac12\sum_{j=1}^2\left[\log(2\pi\sigma_{cj}^2)+\frac{(x_j-\mu_{cj})^2}{\sigma_{cj}^2}\right].\] With priors \(0.6,0.4\), this gives \(s_{\rm yes}=-14.223321\) and \(s_{\rm no}=-153.357048\). Hence the predicted class is yes; log posterior odds are \(139.133727\). Normalize stably by subtracting the largest score before exponentiating. The posterior is numerically extremely close to one under this fitted model, not evidence of real-world certainty: only five training observations and very small fitted variances make this a deliberately fragile illustration, not a medical decision rule.
Example 7.14 (Multinomial and Bernoulli NB give different answers). Reuse the five-document sports/politics corpus and vocabulary order (game, team, vote, election, win). The multinomial calculation above gives posterior sports probability \(27/59\approx0.457627\) for “game election”. It counts tokens and ignores the combinatorial coefficient when comparing classes because it is common to both scores.
For Bernoulli NB, count document presence rather than token frequency and include absent words. Add-one probabilities are \[\boldsymbol{\theta}_S=(3/5,3/5,1/5,1/5,3/5),\qquad \boldsymbol{\theta}_P=(1/4,1/4,1/2,3/4,1/2).\] The query presence vector is \((1,0,0,1,0)\). Its two unnormalized scores, including the absence factors, are \[\begin{align*} s_S&=\tfrac35\cdot\tfrac35\cdot\tfrac25\cdot\tfrac45\cdot\tfrac15\cdot\tfrac25 =\frac{144}{15625},\\ s_P&=\tfrac25\cdot\tfrac14\cdot\tfrac34\cdot\tfrac12\cdot\tfrac34\cdot\tfrac12 =\frac9{640}. \end{align*}\] Thus \(P(S\mid\boldsymbol{x})=s_S/(s_S+s_P)=2048/5173\approx0.395902\). Repeating the word “game” would change a multinomial vector but not this binary vector. The model choice determines which information contributes to the likelihood.
For multinomial NB, the log posterior odds are linear in token counts: \[\log\frac{P(S\mid\boldsymbol{x})}{P(P\mid\boldsymbol{x})} =\log\frac{\pi_S}{\pi_P}+\sum_j x_j\log\frac{\theta_{Sj}}{\theta_{Pj}}.\] A generative model can therefore induce a linear discriminative rule. Conditional independence is useful for tractability but can count correlated evidence repeatedly, so good classification accuracy need not imply well calibrated posterior probabilities.
7.6 Applications
Spam Filtering:
Features: words in email
Classes: spam / not spam
Use Multinomial or Bernoulli NB
Fast training and prediction
Document Classification:
Categorize news articles, scientific papers
Large vocabularies: naive assumption helps reduce parameters
Sentiment Analysis:
Classify reviews as positive/negative
Features: word frequencies or presence
Advantages:
Simple, fast training and prediction
Works well with small training data
Handles high-dimensional data naturally
Probabilistic predictions (useful for uncertainty estimation)
Limitations:
Strong independence assumption rarely holds
Poor at capturing feature interactions
Probability estimates can be extreme (overconfident)
8 Generative vs Discriminative Models
8.1 Key Distinction
Definition 8.1 (Discriminative Models). Learn \(P(y\mid\boldsymbol{x})\) directly or learn a decision function without modeling the input distribution. Standard SVMs learn a margin-based decision function, not posterior probabilities.
Examples: Logistic regression, SVM, decision trees, neural networks
Goal: Find the decision boundary separating classes
Definition 8.2 (Generative Models). Learn the joint probability \(P(\boldsymbol{x}, y) = P(\boldsymbol{x}|y)P(y)\) and use Bayes’ rule.
Examples: Naive Bayes, Gaussian Discriminant Analysis, HMMs
Goal: Model how data is generated for each class
| Aspect | Generative | Discriminative |
|---|---|---|
| Learns | \(P(\boldsymbol{x},y)\) | \(P(y\mid\boldsymbol{x})\) or decision function |
| Input generation | Possible from the fitted joint model | Not supplied by the conditional model alone |
| Input density | Available from the joint model | Not specified by a classifier alone |
| Missing features | Can marginalize when tractable; missingness assumptions still matter | Requires an explicit handling strategy |
| Statistical assumptions | Models features as well as labels | Models conditional labels or a decision rule |
Intuition 119. Generative: “I understand what cats and dogs look like. Let me generate examples of each and see which your image resembles.”
Discriminative: “I just need to distinguish cats from dogs. Let me find the boundary that separates them best.”
Generative classifiers specify the feature distribution as well as labels. A discriminative classifier avoids that part of the modeling task. Which assumption set predicts better must be assessed with an appropriate validation protocol.
8.2 Gaussian Discriminant Analysis (GDA)
GDA is a generative classifier that models each class as a multivariate Gaussian.
Definition 8.4 (GDA Model). For binary classification (\(y \in \{0, 1\}\)): \[\begin{align} y &\sim \text{Bernoulli}(\phi) \\ \boldsymbol{x}|y=0 &\sim \mathcal{N}(\boldsymbol{\mu}_0, \boldsymbol{\Sigma}) \\ \boldsymbol{x}|y=1 &\sim \mathcal{N}(\boldsymbol{\mu}_1, \boldsymbol{\Sigma}) \end{align}\] Note: We assume the same covariance \(\boldsymbol{\Sigma}\) for both classes.
Theorem 8.5 (GDA Parameters). Maximum likelihood estimates from data \(\{(\boldsymbol{x}_i, y_i)\}_{i=1}^n\): \[\begin{align} \phi &= \frac{1}{n} \sum_{i=1}^n \mathbb{1}_{\{y_i=1\}}, \\ \boldsymbol{\mu}_0 &= \frac{\sum_{i=1}^n \mathbb{1}_{\{y_i=0\}}\,\boldsymbol{x}_i}{\sum_{i=1}^n \mathbb{1}_{\{y_i=0\}}}, \\ \boldsymbol{\mu}_1 &= \frac{\sum_{i=1}^n \mathbb{1}_{\{y_i=1\}}\,\boldsymbol{x}_i}{\sum_{i=1}^n \mathbb{1}_{\{y_i=1\}}}, \\ \boldsymbol{\Sigma} &= \frac{1}{n} \sum_{i=1}^n \bigl(\boldsymbol{x}_i - \boldsymbol{\mu}_{y_i}\bigr)\bigl(\boldsymbol{x}_i - \boldsymbol{\mu}_{y_i}\bigr)^\top. \end{align}\]
Theorem 8.6 (GDA Decision Boundary). The decision boundary where \(P(y=1|\boldsymbol{x}) = P(y=0|\boldsymbol{x})\) is linear: \[\boldsymbol{w}^\top\boldsymbol{x} + w_0 = 0\] where \(\boldsymbol{w} = \boldsymbol{\Sigma}^{-1}(\boldsymbol{\mu}_1 - \boldsymbol{\mu}_0)\) and \[w_0=-\tfrac12\boldsymbol{\mu}_1^\top\boldsymbol{\Sigma}^{-1}\boldsymbol{\mu}_1 +\tfrac12\boldsymbol{\mu}_0^\top\boldsymbol{\Sigma}^{-1}\boldsymbol{\mu}_0 +\log\frac{\phi}{1-\phi}.\] Here \(0<\phi<1\) and the shared covariance is positive definite.
This shows GDA produces a linear classifier, similar to logistic regression!
GDA vs Logistic Regression:
Both produce linear decision boundaries
GDA makes stronger assumptions (Gaussian distributions)
Correct Gaussian assumptions can make GDA statistically efficient; the finite-sample comparison depends on the data and estimator
Logistic regression avoids modeling the marginal feature distribution, but is still sensitive to misspecification of the conditional log-odds
Shared-covariance GDA implies a logistic conditional probability; fitting the joint and conditional likelihoods generally gives different estimates
Rule of thumb: Try both. If data looks roughly Gaussian, GDA may work better. Otherwise, prefer logistic regression.
8.2.1 Expanding the Joint Likelihood and the Boundary
Let \(\boldsymbol{r}_i=\boldsymbol{x}_i-\boldsymbol{\mu}_{y_i}\), and \(\boldsymbol{S}=\sum_i\boldsymbol{r}_i\boldsymbol{r}_i^\top\). Up to a constant the joint log-likelihood is \[\ell=\sum_i\{y_i\log\phi+(1-y_i)\log(1-\phi)\} -\frac n2\log|\boldsymbol{\Sigma}|-\frac12\operatorname{tr}(\boldsymbol{\Sigma}^{-1}\boldsymbol{S}).\] The class-prior derivative gives \(\hat\phi=n_1/n\). Each mean derivative is \(\boldsymbol{\Sigma}^{-1}\sum_{i:y_i=c}(\boldsymbol{x}_i-\boldsymbol{\mu}_c)\), which yields its class sample mean. Writing precision \(\boldsymbol{\Omega}=\boldsymbol{\Sigma}^{-1}\), the covariance-dependent part is \((n/2)\log|\boldsymbol{\Omega}|-\operatorname{tr}(\boldsymbol{\Omega}\boldsymbol{S})/2\). Its derivative \(n\boldsymbol{\Omega}^{-1}/2-\boldsymbol{S}/2=0\) gives \(\hat{\boldsymbol{\Sigma}}=\boldsymbol{S}/n\). These density calculations require a positive-definite covariance; a singular empirical estimate requires a regularized model.
Bayes’ rule cancels the marginal \(p(\boldsymbol{x})\) in posterior odds. Equal covariance also cancels the log-determinants and the \(\boldsymbol{x}^\top\boldsymbol{\Sigma}^{-1}\boldsymbol{x}\) terms: \[\begin{align*} \log\frac{P(1\mid\boldsymbol{x})}{P(0\mid\boldsymbol{x})} &=\log\frac\phi{1-\phi}-\tfrac12\bigl[(\boldsymbol{x}-\boldsymbol{\mu}_1)^\top\boldsymbol{\Sigma}^{-1}(\boldsymbol{x}-\boldsymbol{\mu}_1)\\ &\hspace{42mm}-(\boldsymbol{x}-\boldsymbol{\mu}_0)^\top\boldsymbol{\Sigma}^{-1}(\boldsymbol{x}-\boldsymbol{\mu}_0)\bigr]\\ &=\boldsymbol{w}^\top\boldsymbol{x}+w_0. \end{align*}\] Solving these log-odds for the probability gives \(P(1\mid\boldsymbol{x})=\sigma(\boldsymbol{w}^\top\boldsymbol{x}+w_0)\). This is a conditional functional form, not a claim that conditional-likelihood and joint-likelihood estimators coincide.
Example 8.7 (Fitting a two-dimensional GDA model). Use the following class-specific observations: \[\begin{align*} \text{Class 0: }&(-1,0),(1,0),(0,-1),(0,1),\\ \text{Class 1: }&(1,0),(3,0),(2,-1),(2,1). \end{align*}\] Their means are \((0,0),(2,0)\), each within-class scatter is \(2\boldsymbol{I}\), and the pooled MLE is \((2\boldsymbol{I}+2\boldsymbol{I})/8=\tfrac12\boldsymbol{I}\). Priors are equal. The repeated coordinate \((1,0)\) with different labels represents overlapping classes. Consequently \(\boldsymbol{w}=(4,0)\) and \(w_0=-4\): the equal-posterior boundary is \(x_1=1\). At \((0.75,0.2)\), log-odds are \(-1\) and \(P(1\mid\boldsymbol{x})=\sigma(-1)=0.268941\).
If instead the class covariances are separately specified as \(\boldsymbol{\Sigma}_0=\boldsymbol{I}\) and \(\boldsymbol{\Sigma}_1=\tfrac14\boldsymbol{I}\), keeping the same means and priors, the QDA log-odds become \[\log4-\tfrac32(x_1^2+x_2^2)+8x_1-8.\] The determinant term is \(\log4\) in two dimensions. Its zero set is the circle \((x_1-8/3)^2+x_2^2=16/9+(2/3)\log4\). Unequal covariances leave quadratic terms rather than a linear boundary. These are changed assumptions, not new estimates from the preceding eight points.
9 Support Vector Machines
9.1 Intuition: Maximum Margin Classification
Logistic regression minimizes logistic loss (with regularization when specified). SVM instead optimizes a margin-based objective; hard-margin SVM selects the largest-margin separator when the data are linearly separable.
Definition 9.1 (Margin). The margin is the distance from the decision boundary to the nearest data point.
A maximum margin classifier maximizes this distance.
Intuition 129. Imagine two classes of points that are linearly separable. Many hyperplanes separate them, but intuitively, the maximum-margin choice maximizes the smallest training-point distance in the chosen Euclidean geometry. This protects those training decisions against sufficiently small input perturbations; it does not alone guarantee lower test error or robustness to label noise.
9.2 Mathematical Formulation (Hard Margin)
Definition 9.3 (Linear Classifier). Decision function: \(f(\boldsymbol{x}) = \boldsymbol{w}^\top\boldsymbol{x} + b\)
Prediction: \(\hat{y} = \text{sign}(f(\boldsymbol{x})) = \begin{cases} +1 & \text{if } f(\boldsymbol{x}) \geq 0 \\ -1 & \text{if } f(\boldsymbol{x}) < 0 \end{cases}\)
Definition 9.4 (Functional and Geometric Margin). Functional margin of \((\boldsymbol{w}, b)\) with respect to \((\boldsymbol{x}_i, y_i)\): \[\hat{\gamma}_i = y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b)\] Positive for a strictly correct score; a zero score follows the declared tie rule and has zero margin.
Geometric margin (actual distance to hyperplane): \[\gamma_i = \frac{y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b)}{\left\lVert\boldsymbol{w}\right\rVert}\]
Theorem 9.5 (Hard Margin SVM (Primal Form)). To maximize the margin: \[\begin{aligned} \max_{\boldsymbol{w}, b} \quad & \frac{1}{\left\lVert\boldsymbol{w}\right\rVert} \\ \text{subject to} \quad & y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) \geq 1, \quad i = 1, \ldots, n \end{aligned}\] Equivalently (minimization form): \[\begin{aligned} \min_{\boldsymbol{w}, b} \quad & \frac{1}{2}\left\lVert\boldsymbol{w}\right\rVert^2 \\ \text{subject to} \quad & y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) \geq 1, \quad i = 1, \ldots, n \end{aligned}\]
Intuition 133. The constraint \(y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) \geq 1\) ensures all points are correctly classified and at least distance \(1/\left\lVert\boldsymbol{w}\right\rVert\) from the boundary. Minimizing \(\left\lVert\boldsymbol{w}\right\rVert^2\) maximizes the margin \(1/\left\lVert\boldsymbol{w}\right\rVert\).
9.3 Lagrange Duality and the Dual Form
The primal is a constrained optimization problem. We use Lagrange multipliers.
Definition 9.7 (Lagrangian). \[\begin{equation} \tag{9.1} \mathcal{L}(\boldsymbol{w}, b, \boldsymbol{\alpha}) = \frac{1}{2}\left\lVert\boldsymbol{w}\right\rVert^2 - \sum_{i=1}^n \alpha_i[y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) - 1] \end{equation}\] where \(\alpha_i \geq 0\) are Lagrange multipliers.
Theorem 9.8 (KKT Conditions). At the optimum:
\(\nabla_{\boldsymbol{w}} \mathcal{L} = 0 \implies \boldsymbol{w} = \sum_{i=1}^n \alpha_i y_i \boldsymbol{x}_i\)
\(\frac{\partial \mathcal{L}}{\partial b} = 0 \implies \sum_{i=1}^n \alpha_i y_i = 0\)
\(y_i(\boldsymbol{w}^\top\boldsymbol{x}_i+b)\geq1\) (primal feasibility)
\(\alpha_i \geq 0\) (dual feasibility)
\(\alpha_i [y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) - 1] = 0\) (complementary slackness)
The complementary slackness condition is crucial:
If \(\alpha_i > 0\), then \(y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) = 1\) (point is on the margin)
These points are called support vectors
Only support vectors affect the decision boundary!
Most \(\alpha_i = 0\) \(\to\) sparse solution
Theorem 9.9 (Dual Form). Substituting the KKT conditions into the Lagrangian: \[\begin{equation} \tag{9.2} \begin{aligned} \max_{\boldsymbol{\alpha}} \quad & \sum_{i=1}^n \alpha_i - \frac{1}{2}\sum_{i=1}^n\sum_{j=1}^n \alpha_i\alpha_j y_i y_j \boldsymbol{x}_i^\top\boldsymbol{x}_j \\ \text{subject to} \quad & \alpha_i \geq 0, \quad i = 1, \ldots, n \\ & \sum_{i=1}^n \alpha_i y_i = 0 \end{aligned} \end{equation}\] This is a quadratic programming problem in \(\boldsymbol{\alpha}\).
Why dual is useful:
Only depends on dot products \(\boldsymbol{x}_i^\top\boldsymbol{x}_j\) (enables kernel trick!)
Sparse solution (most \(\alpha_i = 0\))
Once solved, prediction: \(f(\boldsymbol{x}) = \sum_{i=1}^n \alpha_i y_i \boldsymbol{x}_i^\top\boldsymbol{x} + b\)
9.3.1 Distance, Duality, and a Solved Hard-Margin Problem
The closest point on \(\boldsymbol{w}^\top\boldsymbol{x}+b=0\) to \(\boldsymbol{x}\) is \(\boldsymbol{x}_{\rm proj}=\boldsymbol{x}-(\boldsymbol{w}^\top\boldsymbol{x}+b)\boldsymbol{w}/\|\boldsymbol{w}\|^2\). Substitution verifies that it lies on the hyperplane; the displacement is normal to it. The distance is therefore \(|\boldsymbol{w}^\top\boldsymbol{x}+b|/\|\boldsymbol{w}\|\). Rescaling a separating \((\boldsymbol{w},b)\) makes the smallest functional margin \(y_i(\boldsymbol{w}^\top\boldsymbol{x}_i+b)\) equal to one. The one-sided geometric margin is then \(1/\|\boldsymbol{w}\|\), while the full band between the \(+1\) and \(-1\) hyperplanes has width \(2/\|\boldsymbol{w}\|\).
Starting from Equation (9.1), stationarity gives \(\boldsymbol{w}=\sum_i\alpha_i y_i\boldsymbol{x}_i\) and \(\sum_i\alpha_i y_i=0\). Substitution cancels the \(b\) term and combines the quadratic terms into Equation (9.2). For separable finite data, scaling a separator makes every constraint strict, giving Slater’s condition. Convexity and this strict feasibility justify strong duality and the sufficiency of KKT conditions. Complementary slackness implies that \(\alpha_i>0\) only when the point lies on a canonical margin; a margin point can still have zero multiplier in a degenerate solution.
Example 9.10 (Solving both the primal and the dual). Use the one-dimensional dataset \[(x_i,y_i)\in\{(1,+1),(2,+1),(4,-1),(5,-1)\}.\] This is a different dataset from the earlier two-dimensional illustration. The closest opposing examples are 2 and 4. Solving \(2w+b=1\) and \(4w+b=-1\) yields \(w=-1,b=3\), geometric margin 1, and band width 2. Multipliers \((0,1/2,1/2,0)\) satisfy \(\sum\alpha_i y_i=0\) and \(w=\sum\alpha_i y_i x_i=-1\). Every primal constraint and complementary-slackness equation holds. The primal objective is \(1/2\); the dual is \(1-(1/2)(-1)^2=1/2\), certifying optimality. A query \(x=3.5\) has score \(-0.5\) and predicted label \(-1\).
9.4 The Kernel Trick
Problem: What if data is not linearly separable?
Approach: Map inputs to a feature space in which a linear separator can represent a nonlinear boundary in the original coordinates. Separability is not guaranteed; conflicting labels at identical inputs, for example, still require a soft margin.
Definition 9.11 (Feature Map). Let \(\boldsymbol{\phi}: \mathbb{R}^d \to \mathbb{R}^D\) (with \(D \gg d\)) be a feature map.
Transform: \(\boldsymbol{x} \to \boldsymbol{\phi}(\boldsymbol{x})\)
Run SVM in the transformed space: \(f(\boldsymbol{x}) = \boldsymbol{w}^\top\boldsymbol{\phi}(\boldsymbol{x}) + b\)
Example 9.12 (Simple Kernel). For \(\boldsymbol{x} = [x_1, x_2]^\top\), define: \[\boldsymbol{\phi}(\boldsymbol{x}) = [1, \sqrt{2}x_1, \sqrt{2}x_2, x_1^2, \sqrt{2}x_1x_2, x_2^2]^\top\] This maps 2D to 6D. Data that’s not linearly separable in 2D might be in 6D!
Issue: Computing \(\boldsymbol{\phi}(\boldsymbol{x})\) explicitly for high \(D\) is expensive.
Theorem 9.13 (Kernel Trick). We only need dot products \(\boldsymbol{\phi}(\boldsymbol{x}_i)^\top\boldsymbol{\phi}(\boldsymbol{x}_j)\) in the dual.
Define kernel function: \(K(\boldsymbol{x}_i, \boldsymbol{x}_j) = \boldsymbol{\phi}(\boldsymbol{x}_i)^\top\boldsymbol{\phi}(\boldsymbol{x}_j)\)
If we can compute \(K\) directly without computing \(\boldsymbol{\phi}\) explicitly, we get efficiency!
Definition 9.14 (Common Kernels).
Linear: \(K(\boldsymbol{x}, \boldsymbol{z}) = \boldsymbol{x}^\top\boldsymbol{z}\)
Polynomial: \(K(\boldsymbol{x},\boldsymbol{z})=(\boldsymbol{x}^\top\boldsymbol{z}+c)^p\) with nonnegative \(c\) and positive integer \(p\)
For \(c>0\) the feature map contains monomials through degree \(p\); for \(c=0\) it contains only homogeneous degree-\(p\) monomials.
RBF (Radial Basis Function / Gaussian): \[K(\boldsymbol{x}, \boldsymbol{z}) = \exp\left(-\gamma\left\lVert\boldsymbol{x} - \boldsymbol{z}\right\rVert^2\right)\] where \(\gamma > 0\) is a bandwidth parameter.
This corresponds to infinite-dimensional feature space!
Sigmoid form: \(K(\boldsymbol{x},\boldsymbol{z})=\tanh(\alpha\boldsymbol{x}^\top\boldsymbol{z}+c)\) is not positive semidefinite for arbitrary parameters and domains. A valid kernel must produce positive-semidefinite Gram matrices; the standard convex kernel-SVM theory requires this condition.
The kernel trick magic:
The polynomial kernel \((x^\top z + 1)^2\) computes the dot product in a space of monomials of total degree at most two: \[(x^\top z + 1)^2 = (x_1z_1 + x_2z_2 + 1)^2 = x_1^2z_1^2 + 2x_1x_2z_1z_2 + x_2^2z_2^2 + 2x_1z_1 + 2x_2z_2 + 1\] This equals \(\boldsymbol{\phi}(\boldsymbol{x})^\top\boldsymbol{\phi}(\boldsymbol{z})\) with \(\boldsymbol{\phi}(\boldsymbol{x}) = [1, \sqrt{2}x_1, \sqrt{2}x_2, x_1^2, \sqrt{2}x_1x_2, x_2^2]^\top\).
We computed this in \(O(d)\) time instead of \(O(D)\) where \(D=\binom{d+2}{2}\)!
For RBF kernel: we operate in infinite dimensions without ever computing infinite-dimensional vectors!
Theorem 9.15 (Kernelized Dual). With kernel \(K\): \[\begin{aligned} \max_{\boldsymbol{\alpha}} \quad & \sum_{i=1}^n \alpha_i - \frac{1}{2}\sum_{i=1}^n\sum_{j=1}^n \alpha_i\alpha_j y_i y_j K(\boldsymbol{x}_i, \boldsymbol{x}_j) \\ \text{subject to} \quad & \alpha_i \geq 0, \sum_{i=1}^n \alpha_i y_i = 0 \end{aligned}\] Prediction: \(f(\boldsymbol{x}) = \sum_{i=1}^n \alpha_i y_i K(\boldsymbol{x}_i, \boldsymbol{x}) + b\)
9.4.1 An Explicit Kernel Calculation on XOR
Example 9.16 (Features, Gram matrix, and multipliers). Use the four input points \[\boldsymbol{x}\in\{(-1,-1),(-1,1),(1,-1),(1,1)\},\] with labels \((-1,+1,+1,-1)\), so \(y=-x_1x_2\). No affine line separates opposite corners from the other pair. The interaction \(u=x_1x_2\) does separate them with score \(-u\).
For \(K(\boldsymbol{x},\boldsymbol{z})=(\boldsymbol{x}^\top\boldsymbol{z}+1)^2\), one explicit feature map is \[\phi(\boldsymbol{x})=(1,\sqrt2x_1,\sqrt2x_2,x_1^2,\sqrt2x_1x_2,x_2^2)^\top.\] Expanding the inner product verifies the kernel identity. In the stated order, the Gram matrix is \[\boldsymbol{K}=\begin{bmatrix}9&1&1&1\\1&9&1&1\\1&1&9&1\\1&1&1&9\end{bmatrix}=8\boldsymbol{I}+\boldsymbol{1}\boldsymbol{1}^\top.\] Its eigenvalues are \(12,8,8,8\), all positive. Multipliers \(\alpha_i=1/8\) and \(b=0\) give training scores \(\sum_i\alpha_i y_i K(\boldsymbol{x}_i,\boldsymbol{x}_j)=y_j\). The corresponding feature-space weight has only the interaction coefficient nonzero, equal to \(-1/\sqrt2\). Its norm squared is \(1/2\); primal and dual objectives both equal \(1/4\), proving a hard-margin optimum.
Pairwise evaluation can avoid constructing a high-dimensional feature vector, but a dense Gram matrix still requires \(O(n^2)\) entries. A kernel trick removes explicit feature expansion, not the dependence on the number of training examples.
9.5 Soft Margin SVM
Problem: Real data is rarely perfectly separable. Hard-margin SVM has no feasible solution if no affine separator satisfies every margin constraint.
Solution: Allow some misclassifications with penalty.
Definition 9.17 (Slack Variables). Introduce \(\xi_i\geq0\) for each point. At an optimum with \(C>0\), \(\xi_i=\max(0,1-y_i(\boldsymbol{w}^\top\boldsymbol{x}_i+b))\), so:
\(\xi_i = 0\): Point correctly classified with margin \(\geq 1\)
\(0 < \xi_i < 1\): Correctly classified but within margin
\(\xi_i=1\): On the decision boundary (classification depends on the tie convention)
\(\xi_i>1\): Strictly misclassified
Relaxed constraint: \(y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) \geq 1 - \xi_i\)
Theorem 9.18 (Soft Margin SVM). \[\begin{aligned} \min_{\boldsymbol{w}, b, \boldsymbol{\xi}} \quad & \frac{1}{2}\left\lVert\boldsymbol{w}\right\rVert^2 + C\sum_{i=1}^n \xi_i \\ \text{subject to} \quad & y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b) \geq 1 - \xi_i \\ & \xi_i \geq 0, \quad i = 1, \ldots, n \end{aligned}\] \(C > 0\) is a hyperparameter controlling the trade-off:
Large \(C\): Fewer violations allowed (closer to hard margin, may overfit)
Small \(C\): More violations allowed (more regularization, may underfit)
Intuition 146. Soft margin balances two goals:
Maximize margin (minimize \(\left\lVert\boldsymbol{w}\right\rVert^2\))
Minimize hinge-margin violations (minimize \(\sum \xi_i\)); these are not the number of classification errors
Parameter \(C\) controls this trade-off. Use cross-validation to choose \(C\).
Definition 9.20 (Hinge Loss Formulation). Soft margin SVM can be written as: \[\min_{\boldsymbol{w}, b} \frac{1}{2}\left\lVert\boldsymbol{w}\right\rVert^2 + C\sum_{i=1}^n \max(0, 1 - y_i(\boldsymbol{w}^\top\boldsymbol{x}_i + b))\] where \(\ell_{\text{hinge}}(z) = \max(0, 1-z)\) is the hinge loss.
This connects SVM to other loss functions (logistic loss, squared loss, etc.).
9.5.1 Slack Variables, Hinge Loss, and the Meaning of \(C\)
At fixed \(\boldsymbol{w},b\), the least feasible slack is \(\xi_i=\max(0,1-y_if_i)\) because \(C>0\) penalizes every extra unit. Eliminating slacks gives \[\tfrac12\|\boldsymbol{w}\|^2+C\sum_i\max(0,1-y_if_i).\] Dividing by \(nC\) gives the equivalent average-hinge objective \(\lambda\|\boldsymbol{w}\|^2/2+\frac1n\sum_i\max(0,1-y_if_i)\) with \(\lambda=1/(nC)\). This conversion assumes the sum-loss convention above.
In the constrained Lagrangian, let \(\mu_i\ge0\) multiply \(-\xi_i\). Stationarity in \(\xi_i\) gives \(C-\alpha_i-\mu_i=0\), hence \(0\le\alpha_i\le C\). Complementary slackness implies: if \(0<\alpha_i<C\), then \(\xi_i=0\) and \(y_if_i=1\); if \(\alpha_i=C\), the point may violate the margin, including being misclassified, but need not do so. A point with \(\alpha_i=0\) has no dual contribution. Recover \(b=y_i-\boldsymbol{w}^\top\boldsymbol{x}_i\) from a free support vector with \(0<\alpha_i<C\); if none exists, use the KKT bounds on \(b\) rather than assuming an arbitrary support vector has zero slack.
Example 9.21 (Small \(C\) permits margin violations without classification errors). On the preceding four-point one-dimensional dataset, take \(C=0.05\). One optimum is \(w=-0.3,b=0.9\), giving scores \((0.6,0.3,-0.3,-0.6)\) and slacks \((0.4,0.7,0.7,0.4)\). All four labels are correct, yet every point is inside the canonical margin. Set all multipliers to \(0.05\). They satisfy the box constraints and label-balance constraint, and imply \(w=\sum_i\alpha_i y_ix_i=-0.3\). The primal value is \(0.045+0.05(2.2)=0.155\) and the dual value is \(0.2-0.045=0.155\). This certifies optimality; the unpenalized intercept is not unique here.
9.6 Support Vector Regression (SVR)
SVM can also be used for regression!
Definition 9.22 (\(\epsilon\)-insensitive Loss). \[\ell_\epsilon(y, \hat{y}) = \begin{cases} 0 & \text{if } |y - \hat{y}| < \epsilon \\ |y - \hat{y}| - \epsilon & \text{otherwise} \end{cases}\] No penalty for predictions within \(\epsilon\) of the true value.
Definition 9.23 (SVR Formulation). \[\begin{aligned} \min_{\boldsymbol{w}, b,\boldsymbol{\xi},\boldsymbol{\xi}^*} \quad & \frac{1}{2}\left\lVert\boldsymbol{w}\right\rVert^2 + C\sum_{i=1}^n (\xi_i + \xi_i^*)\\ \text{subject to} \quad & y_i - (\boldsymbol{w}^\top\boldsymbol{x}_i + b) \leq \epsilon + \xi_i \\ & (\boldsymbol{w}^\top\boldsymbol{x}_i + b) - y_i \leq \epsilon + \xi_i^* \\ & \xi_i, \xi_i^* \geq 0 \end{aligned}\]
Intuition 151. SVR fits a “tube” of width \(2\epsilon\) around the data. Points inside the tube have no penalty. Points outside pay a linear penalty proportional to their distance from the tube.
9.6.1 Checking an \(\epsilon\)-Insensitive Regression Candidate
For residual \(r_i=y_i-f(x_i)\), the least feasible slacks are \(\xi_i=\max(0,r_i-\epsilon)\) and \(\xi_i^*=\max(0,-r_i-\epsilon)\). Their sum is \(\max(0,|r_i|-\epsilon)\). For candidate \(f(x)=x\), observations \((0,0.2),(1,1.8),(2,1.6)\), and \(\epsilon=0.5\), residuals are \((0.2,0.8,-0.4)\) and losses are \((0,0.3,0)\). With \(C=1\), its primal objective is \(\tfrac12(1)^2+0.3=0.8\). This evaluates a candidate; it does not claim that \(f(x)=x\) minimizes the objective over all lines.
9.7 Practical Considerations
Choosing SVM Parameters:
Kernel: Start with RBF (most flexible). Try linear if \(d\) is large.
\(C\): Controls regularization. Use grid search + CV.
\(\gamma\) (for RBF): Controls kernel width. Small \(\gamma\) = wide kernel (smooth), large \(\gamma\) = narrow kernel (complex boundary).
Feature Scaling: Critical for SVMs! Since they use distances, features should be normalized (e.g., to \([0,1]\) or standardized to mean 0, std 1).
Complexity for a dense kernel formulation:
Forming the Gram matrix takes \(O(n^2d)\) work for standard \(O(d)\) kernels and \(O(n^2)\) storage; additional solver cost depends on the algorithm, tolerance, and data
Kernel prediction takes \(O(n_{\text{sv}}d)\) for such kernels. A linear model can instead store its weight vector and predict in \(O(d)\)
When to use SVMs:
Medium-sized datasets (1000s to 100,000s of examples)
High-dimensional data (works well when \(d > n\))
When a margin-based inductive bias suits the task; generalization bounds still require explicit assumptions
Non-linear decision boundaries (with kernels)
When NOT to use SVMs:
Very large datasets (\(n > 1\)M) - use linear models or neural networks
When interpretability is critical - use decision trees or linear models
When probabilistic outputs are essential - use logistic regression or Naive Bayes
The CS229 lecture notes provide further treatments of likelihood-based models and SVM duality. The sum-versus-mean loss conversions above should be checked before transferring hyperparameters between formulations.
9.8 Summary of Part 2
Naive Bayes: Generative classifier using Bayes’ rule with conditional independence assumption. Fast, works well for text classification despite “naive” assumption.
Generative vs Discriminative: Generative classifiers model \(P(\boldsymbol{x},y)\); discriminative classifiers learn \(P(y\mid\boldsymbol{x})\) or a decision function. Performance and data requirements depend on the model assumptions and the task.
GDA: Gaussian class densities with a shared covariance imply linear log-odds. Separate covariances generally give quadratic boundaries (QDA).
SVM: Maximum margin classifier. Primal form maximizes margin; dual form enables kernel trick. Soft margin allows violations with penalty \(C\).
Kernel Trick: Uses inner products in a feature space without explicitly constructing that space. A valid kernel has positive-semidefinite Gram matrices; the RBF kernel is a common nonlinear choice.
SVR: Adapts SVM for regression using \(\epsilon\)-insensitive loss. Fits tube around data.
Next Steps: Part 3 explores ensemble methods (Bagging, Boosting, Stacking) that combine multiple models and can improve predictive performance when their errors and fitting procedures complement one another.
Exercise 9.25.
Given training data for spam (words: “free”=10, “money”=8) and ham (“free”=2, “money”=1), with priors \(P(\text{spam})=0.4\), compute \(P(\text{spam}|\text{``free money''})\) using Multinomial Naive Bayes with Laplace smoothing (\(\alpha=1\)).
Prove that if we assume Gaussian distributions with same covariance for both classes (GDA), the posterior \(P(y=1|\boldsymbol{x})\) has the form of logistic regression.
For the polynomial kernel \(K(\boldsymbol{x}, \boldsymbol{z}) = (\boldsymbol{x}^\top\boldsymbol{z} + 1)^2\), explicitly write out the feature map \(\boldsymbol{\phi}(\boldsymbol{x})\) for \(\boldsymbol{x} \in \mathbb{R}^2\).
Show that the RBF kernel \(K(\boldsymbol{x}, \boldsymbol{z}) = \exp(-\gamma\left\lVert\boldsymbol{x}-\boldsymbol{z}\right\rVert^2)\) satisfies the property \(K(\boldsymbol{x}, \boldsymbol{x}) = 1\) and \(K(\boldsymbol{x}, \boldsymbol{z}) \to 0\) as \(\left\lVert\boldsymbol{x}-\boldsymbol{z}\right\rVert \to \infty\).
Consider a 1D SVM with data \(\{(1, +1), (2, +1), (4, -1), (5, -1)\}\). Assuming hard margin is feasible, what are the support vectors?
Explain why feature scaling is critical for SVMs but not for decision trees.
Part 3: Ensemble Methods
10 Introduction to Ensemble Learning
Definition 10.1 (Ensemble Learning). An ensemble method combines predictions from multiple base models (learners, not necessarily weak classifiers). Improvement depends on their individual errors, dependence, aggregation rule, and fitting procedure.
Intuition 154. “Wisdom of crowds”: Just as a group of people can make better decisions than individuals, combining multiple models can reduce errors. Different models make different mistakes; by aggregating, we can cancel out individual errors.
Why Ensembles Work:
From the bias-variance perspective:
Reduce Variance: Average multiple high-variance models (e.g., deep trees) \(\to\) more stable predictions
Reduce Bias: Sequentially build models that correct errors of previous ones \(\to\) better fit
Improve Robustness: Different models capture different patterns; ensemble is less likely to fail
Three Main Paradigms:
Bagging: Train models independently on bootstrap samples, then average (reduces variance)
Boosting: Train models sequentially, each focusing on previous errors (reduces bias)
Stacking: Train a meta-model to combine base model predictions (learns optimal combination)
10.1 Averaging, Dependence, and the Bias That Remains
Fix an input \(\boldsymbol{x}\) and consider fitted predictions \(h_1,\ldots,h_M\) as random variables over training samples and algorithmic randomness. For weights \(\boldsymbol{a}\) with \(\sum_m a_m=1\), the prediction is \(H=\sum_m a_mh_m\) and \[\mathrm{Var}(H)=\boldsymbol{a}^\top\boldsymbol{C}\boldsymbol{a},\qquad C_{rs}=\mathrm{Cov}(h_r,h_s).\] For equal weights, identical marginal variance \(\sigma^2\), and common pairwise correlation \(\rho\), expanding the double sum gives \[\begin{equation} \tag{10.1} \mathrm{Var}(H)=\frac{M\sigma^2+M(M-1)\rho\sigma^2}{M^2} =\sigma^2\left(\rho+\frac{1-\rho}{M}\right). \end{equation}\] This derivation requires the stated covariance structure, not merely similar individual accuracies. If \(\mathbb{E}[h_m]=f(\boldsymbol{x})+b\) for every model, averaging preserves bias \(b\). It cannot remove a shared systematic error.
There is a useful conditional explanation for bagging. Conditional on one training dataset \(\mathcal D\), independently generated bootstrap fits may be independent over their random seeds. Unconditionally they still share \(\mathcal D\). Writing \(\mu_{\mathcal D}=\mathbb{E}[h_m\mid\mathcal D]\) and \(v_{\mathcal D}=\mathrm{Var}(h_m\mid\mathcal D)\) gives \[\mathrm{Var}(H)=\mathrm{Var}_{\mathcal D}(\mu_{\mathcal D})+\frac1M\mathbb{E}_{\mathcal D}[v_{\mathcal D}].\] The shared-data term remains even with infinitely many bootstrap fits. Thus “independent training jobs” does not imply statistically independent prediction errors.
Example 10.3 (A variance floor and a majority vote). With \(\sigma^2=4\), \(\rho=1/4\), and \(M=5\), variance is \(4(1/4+3/20)=1.6\), compared with 4 for one model. At \(M=20\) it is 1.15, and its limit is 1. For binary votes, a different calculation is needed: three independent classifiers with individual correctness probability \(0.9\) have majority accuracy \(0.9^3+3(0.9)^2(0.1)=0.972\). If their correctness indicators are identical, majority accuracy stays \(0.9\). Averaging variance and majority-vote error are related intuitions, not interchangeable formulas.
11 Bagging (Bootstrap Aggregating)
11.1 Bootstrap Sampling
Definition 11.1 (Bootstrap Sample). Given a dataset \(\mathcal{D}\) of size \(n\), a bootstrap sample \(\mathcal{D}_i\) is created by:
Randomly sample \(n\) examples from \(\mathcal{D}\) with replacement
Some examples appear multiple times, others not at all
The exact expected fraction of original examples included is \(1-(1-1/n)^n\), approaching about 63.2% as \(n\) grows.
Why 63.2%?. Probability that example \(i\) is NOT selected in one draw: \((1 - 1/n)\)
Probability NOT selected in \(n\) draws: \((1 - 1/n)^n\)
As \(n \to \infty\): \((1 - 1/n)^n \to e^{-1} \approx 0.368\)
So probability of being selected: \(1 - 0.368 = 0.632\) or 63.2%. ◻
11.2 Bagging Algorithm
Bagging for Classification/Regression
Input:
Training data \(\mathcal{D} = \{(\boldsymbol{x}_i, y_i)\}_{i=1}^n\)
Base learning algorithm \(\mathcal{A}\)
Number of models \(M\)
Training:
For \(m = 1\) to \(M\):
Create bootstrap sample \(\mathcal{D}_m\) by sampling \(n\) examples from \(\mathcal{D}\) with replacement
Train base learner: \(h_m = \mathcal{A}(\mathcal{D}_m)\)
Prediction for new example \(\boldsymbol{x}\):
Classification: \(\hat{y} = \text{majority\_vote}(h_1(\boldsymbol{x}), h_2(\boldsymbol{x}), \ldots, h_M(\boldsymbol{x}))\)
Regression: \(\hat{y} = \frac{1}{M}\sum_{m=1}^M h_m(\boldsymbol{x})\)
Output: Ensemble predictor \(H(\boldsymbol{x})\)
Theorem 11.2 (Variance Reduction in Bagging). Under the equal-variance and common-correlation assumptions of Section 10.1, the equal-weight variance is Equation (10.1); independence reduces it to \(\sigma^2/M\). For fixed nonnegative common correlation, its limit is \(\rho\sigma^2\). These statements concern the specified randomness and do not assert that bootstrap predictors sharing a dataset are unconditionally independent.
Bagging reduces variance most when:
Base learners have high variance (e.g., deep decision trees)
Base learners are diverse (low correlation \(\rho\))
Potential gain depends on estimator instability and prediction dependence. Deep trees are often unstable; a linear estimator can also be unstable under a poorly conditioned design. Averaging does not remove shared bias.
11.3 Random Forests
Random Forests extend bagging by adding another source of randomness.
Definition 11.3 (Random Forest). A Random Forest is an ensemble of decision trees where:
Each tree is trained on a bootstrap sample (like bagging)
Additional randomness: At each split, only a random subset of \(m\) features is considered (out of total \(d\) features)
Feature subset size \(m\):
Classification: \(m=\max(1,\lfloor\sqrt d\rfloor)\) is common; scikit-learn defaults to
"sqrt"Regression: \(m=\max(1,\lfloor d/3\rfloor)\) is a traditional heuristic. The scikit-learn regression forest defaults to
1.0, using all \(d\) featuresTune
max_featuresvia cross-validation; see the scikit-learn documentation for implementation defaults.
Intuition 159. Why limit features at each split?
Without this, trees in bagging would be similar—they’d all split on the strongest features first. By randomly limiting choices, we force trees to consider different features, increasing diversity and decorrelating predictions.
Random Forest Algorithm
Input: Data \(\mathcal{D}\), number of trees \(M\), feature subset size \(m\)
For \(i = 1\) to \(M\):
Draw bootstrap sample \(\mathcal{D}_i\) from \(\mathcal{D}\)
Grow tree \(T_i\) on \(\mathcal{D}_i\):
At each node, randomly select \(m\) features from \(d\) total
Choose best split among these \(m\) features only
Split and recurse until stopping criterion
Grow subject to the selected depth, leaf-size, and other tree constraints; classical forests typically use deep trees rather than post-pruning each tree
Prediction: Average (regression) or vote (classification) across all \(M\) trees.
11.4 Out-of-Bag (OOB) Error Estimation
Definition 11.5 (Out-of-Bag (OOB) Examples). For each bootstrap sample, approximately 37% of examples are not selected. These are called out-of-bag (OOB) examples for that tree.
For each data point \((\boldsymbol{x}_i, y_i)\), consider only trees where \(i\) was OOB. Average their predictions to get OOB prediction for \(\boldsymbol{x}_i\).
Definition 11.6 (OOB Error). Let \(\mathcal C=\{i:\text{at least one fitted tree omits row }i\}\). For \(|\mathcal C|>0\), \[\text{OOB Error} = \frac{1}{|\mathcal C|}\sum_{i\in\mathcal C} \ell(y_i, \hat{y}_i^{\text{OOB}}).\] Each prediction aggregates only trees for which row \(i\) was OOB. Report coverage \(|\mathcal C|/n\); when every row is covered this reduces to the usual \(1/n\) formula. No OOB risk is defined by this formula when coverage is zero.
OOB predictions provide an internal resampling estimate without fitting separate holdout forests. Check coverage and ensure learned preprocessing also excludes the evaluated row. OOB scores used repeatedly to choose settings are selection scores; independent test or outer validation data assess the selected complete procedure. Ordinary row bootstrap does not by itself solve group or time leakage.
11.5 Feature Importance in Random Forests
Definition 11.7 (Mean Decrease in Impurity (MDI)). For each feature \(j\), compute the total reduction in impurity (Gini or entropy) when splitting on feature \(j\), averaged over all trees and all nodes.
Each node decrease must be weighted by the fraction of training weight reaching that node, then summed over nodes and averaged over trees. Higher values indicate more importance according to this impurity criterion.
Definition 11.8 (Permutation Importance).
Compute baseline OOB error
For each feature \(j\):
Randomly permute feature \(j\) in OOB data
Compute new OOB error
Importance = increase in error
If permuting a feature greatly increases error, that feature is important.
11.6 Finite Bootstrap Probabilities and an OOB Calculation
For a bootstrap of \(n\) draws, the exact omission probability is \(q_n=(1-1/n)^n\). If \(I_i\) indicates that original example \(i\) appears at least once, linearity of expectation gives \[\mathbb{E}[\text{number of distinct examples}]=\sum_i\mathbb{E}[I_i] =n(1-q_n).\] The indicators need not be independent for this identity. The familiar 63.2% is a large-\(n\) approximation, not an exact percentage for every dataset.
Example 11.9 (Three bootstrap fits, with incomplete OOB coverage). Let four training targets be \((0,1,1,0)\). Use a constant regressor fitted as the mean of its bootstrap targets. The three draws are specified explicitly:
| Fit | Drawn original indices | Fitted constant | OOB indices |
|---|---|---|---|
| 1 | \(1,1,2,4\) | \(1/4\) | \(3\) |
| 2 | \(2,3,3,4\) | \(3/4\) | \(1\) |
| 3 | \(1,2,2,3\) | \(3/4\) | \(4\) |
These are actual fits of the chosen constant base learner, not decision-tree predictions. OOB predictions for rows \(1,3,4\) are \(3/4,1/4,3/4\) respectively. Each squared error is \(9/16\), so the covered-row OOB MSE is \(9/16\). Row 2 occurs in every draw and has no OOB prediction; it must not be given a fabricated zero or silently counted in a denominator of four. Coverage is \(3/4\).
For \(n=4\), \(q_n=81/256\) and the expected number of distinct rows per draw is \(175/64=2.734375\). For \(M\) independently drawn bootstraps, the probability a fixed row has no OOB fit is \((1-q_n)^M\). More trees improve coverage, but finite coverage must still be checked.
OOB and preprocessing. A row omitted from a tree can still influence it if a supervised feature selector, target encoder, imputer, or scaler was fitted on all rows before bootstrapping. An OOB interpretation of the complete procedure requires excluding that row from learned upstream steps too. Ordinary tree thresholds need no external scaling, which makes raw-feature forest OOB estimates particularly convenient. Repeatedly choosing settings using OOB scores also makes those scores selection data; use an independent test or an outer evaluation split for the selected procedure. Grouped observations and time-dependent examples need the splitting units defined in Section 1.3.
11.7 What Feature Importance Actually Measures
Example 11.10 (Held-out permutation and a redundant feature). On four held-out examples, let \(x_1=(0,0,1,1)\), \(x_2=x_1\), and \(y=x_1\). A fixed classifier \(f=\mathbb{1}_{\{x_1>1/2\}}\) has accuracy 1. Permuting \(x_1\) to \((0,1,0,1)\) while keeping labels and the fitted model fixed lowers accuracy to \(1/2\), giving a permutation importance of \(1/2\) for this specified permutation. Permuting \(x_2\) changes no predictions and gives importance zero, although \(x_2\) contains exactly the same target information as \(x_1\).
Permutation importance measures the reliance of a particular fitted predictor under the chosen perturbation and metric. It is not a causal effect or a guarantee of unique information. Correlated features can mask or redistribute importance, and independent permutation can produce feature combinations outside the observed joint distribution. Repeat permutations to characterize their randomness. MDI is a training impurity statistic and can favor features offering many candidate splits; it should not be interpreted as an unbiased held-out performance contribution.
For classification, a probability-averaging forest and a majority vote of hard tree labels are distinct rules. If three trees give positive-class probabilities \((0.51,0.51,0)\), hard votes predict positive, whereas their mean \(0.34\) predicts negative at threshold \(1/2\). The scikit-learn ensemble guide documents the probability-averaging rule used by its random-forest classifier.
11.8 Advantages and Limitations
Advantages of Random Forests:
Excellent performance: Often among the best off-the-shelf algorithms
Minimal tuning: Works well with default parameters
Ensemble stability: More trees reduce finite-ensemble randomness; depth, leaf size, feature handling, and selection still govern overfitting
Mixed data: Numerical features and suitably encoded categories; native categorical support depends on the implementation
Feature importance: Built-in importance measures
Parallelizable: Trees trained independently
OOB error: Internal resampling estimate subject to coverage and fitting boundaries
Limitations:
Less interpretable: Cannot visualize like a single tree
Memory intensive: Must store \(M\) trees
Slow prediction: Must query \(M\) trees
Regression extrapolation: Ordinary averages of training-target leaf means stay inside the training target range, even for inputs outside the observed feature range
Importance bias: Impurity-based importance can favor features with many candidate split points
Typical hyperparameters:
Number of trees \(M\): Increasing it reduces finite-ensemble Monte Carlo variability, with diminishing returns; a particular validation error need not decrease monotonically
Max features \(m\): Common heuristics are \(\sqrt d\) for classification and \(d/3\) for regression (rounded and at least 1); defaults are implementation-specific, as noted above
Min samples per leaf: 1-10 (larger = more regularization)
Max depth: Usually unlimited (full trees)
12 Boosting
12.1 Boosting Philosophy
Unlike bagging (parallel training), boosting trains models sequentially, with each new model focusing on examples that previous models got wrong.
Intuition 166. Think of boosting as learning from mistakes:
Train model 1 on data
Identify examples model 1 struggles with
Train model 2 to focus on those hard examples
Combine models 1 and 2
Repeat, always focusing on current ensemble’s weaknesses
This increases the fitted ensemble’s flexibility and can reduce its training objective; it does not force bias or test error to decrease on every task.
12.2 AdaBoost (Adaptive Boosting)
AdaBoost adjusts weights on training examples, increasing weights on misclassified examples.
AdaBoost for Binary Classification
Input: Data \(\{(\boldsymbol{x}_i, y_i)\}_{i=1}^n\) with \(y_i \in \{-1, +1\}\), number of rounds \(T\)
Initialize: Weights \(D_1(i) = 1/n\) for all \(i\)
For \(t = 1\) to \(T\):
Train weak classifier \(h_t\) on weighted data (minimizing weighted error): \[\epsilon_t = \sum_{i=1}^n D_t(i) \,\mathbb{1}_{\{h_t(\boldsymbol{x}_i)\neq y_i\}}\]
If \(\epsilon_t=0\), return the perfect weak classifier on the training set; the logarithmic formula below is not evaluated. If \(\epsilon_t\geq1/2\), stop this procedure or obtain a weak classifier with error below \(1/2\).
For \(0<\epsilon_t<1/2\), compute classifier weight: \[\alpha_t = \frac{1}{2}\ln\left(\frac{1-\epsilon_t}{\epsilon_t}\right)\] Higher \(\alpha_t\) for more accurate classifiers.
Update example weights: \[D_{t+1}(i) = D_t(i) \cdot \exp(-\alpha_t y_i h_t(\boldsymbol{x}_i))\]
If correct (\(y_i = h_t(\boldsymbol{x}_i)\)): weight decreases
If incorrect (\(y_i \neq h_t(\boldsymbol{x}_i)\)): weight increases
Normalize: \(D_{t+1}(i) = D_{t+1}(i) / \sum_j D_{t+1}(j)\)
Final classifier: \[H(\boldsymbol{x}) = \text{sign}\left(\sum_{t=1}^{\tau} \alpha_t h_t(\boldsymbol{x})\right)\] Here \(\tau\le T\) counts successfully completed finite-weight rounds. If no weak learner improves on chance, report that failure rather than treating the requested \(T\) rounds as fitted.
Example 12.2 (AdaBoost Iteration). Suppose after round 1:
Examples 1,2,3 correctly classified
Example 4 misclassified
In round 2:
Example 4 has much higher weight
Next classifier focuses on getting example 4 right
May sacrifice accuracy on 1,2,3 (which already work)
Final ensemble combines both classifiers, each weighted by \(\alpha_t\).
Theorem 12.3 (AdaBoost Training Error Bound). The training error of AdaBoost is bounded by: \[\frac{1}{n}\sum_{i=1}^n \mathbb{1}_{\{H(\boldsymbol{x}_i)\neq y_i\}} \;\leq\; \prod_{t=1}^T 2\sqrt{\epsilon_t(1-\epsilon_t)}\] For \(T\) completed finite-weight rounds, if every \(\epsilon_t\le1/2-\gamma\) with \(\gamma>0\), this training-error upper bound decreases exponentially in \(T\). Actual classification error need not decrease at every round.
Weak Learner Assumption: AdaBoost requires weak learners to be better than random guessing (\(\epsilon_t < 0.5\)). Even slightly better than random is enough!
Common weak learners:
Decision stumps: Trees with depth 1 (one split)
Shallow trees: Depth 2-5
Why AdaBoost works:
Sequentially reduces the exponential training objective when a weak-learning edge exists; bias, variance, and test error depend on the full fitted procedure
Focuses on hard examples
Adaptive weights emphasize misclassified examples; fitting every example is not guaranteed, especially with noise or contradictory labels
Potential issue: Sensitive to noise and outliers (keeps increasing their weights).
12.2.1 Deriving the Exponential Update and Its Bound
Let \(F_{t-1}=\sum_{s<t}\alpha_sh_s\). Define normalized example weights \(D_t(i)=e^{-y_iF_{t-1}(\boldsymbol{x}_i)}/\sum_j e^{-y_jF_{t-1}(\boldsymbol{x}_j)}\). For a fixed binary weak classifier, adding \(\alpha h_t\) multiplies the empirical exponential loss by \[Z_t(\alpha)=(1-\epsilon_t)e^{-\alpha}+\epsilon_t e^\alpha.\] The two terms group correctly and incorrectly classified examples. For \(0<\epsilon_t<1/2\), differentiating gives \[-(1-\epsilon_t)e^{-\alpha}+\epsilon_t e^\alpha=0, \quad \alpha_t=\tfrac12\log\frac{1-\epsilon_t}{\epsilon_t}, \quad Z_t=2\sqrt{\epsilon_t(1-\epsilon_t)}.\] Renormalizing \(D_t(i)e^{-\alpha_t y_ih_t(\boldsymbol{x}_i)}\) yields the stated weight update. Starting with \(F_0=0\) and uniform weights, telescoping yields \[\frac1n\sum_i e^{-y_iF_T(\boldsymbol{x}_i)}=\prod_{t=1}^T Z_t.\] A misclassified example has \(y_iF_T\le0\), so its indicator is at most its exponential loss. This proves the training-error bound, including either tie convention. If \(\epsilon_t\le1/2-\gamma\), then \(Z_t\le\sqrt{1-4\gamma^2}\le e^{-2\gamma^2}\), giving a bound \(e^{-2T\gamma^2}\). This is a training statement under a persistent weak-learning edge, not a test-error guarantee. The exponential score is not automatically a calibrated probability.
Example 12.4 (All three AdaBoost rounds). Take four labeled examples and three candidate weak-classifier prediction vectors: \[\boldsymbol{y}=(+,+,-,-),\quad \boldsymbol{h}_1=(+,+,-,+),\quad \boldsymbol{h}_2=(+,+,+,-),\quad \boldsymbol{h}_3=(-,+,-,-).\] Start with \(D_1=(1/4,1/4,1/4,1/4)\). The resulting complete updates are
| Round | \(\epsilon_t\) | \(\alpha_t\) | Next normalized weights |
|---|---|---|---|
| 1 | \(1/4\) | \(\tfrac12\log3\) | \((1/6,1/6,1/6,1/2)\) |
| 2 | \(1/6\) | \(\tfrac12\log5\) | \((1/10,1/10,1/2,3/10)\) |
| 3 | \(1/10\) | \(\tfrac12\log9\) | \((1/2,1/18,5/18,1/6)\) |
For example, at round 2 only row 3 is wrong, so its weighted error is \(1/6\), not its unweighted error \(1/4\). Final signed margins \(y_iF_3(\boldsymbol{x}_i)\) are approximately \[(0.255413,\ 2.452637,\ 0.843199,\ 1.354025),\] all positive. Training error is zero, while its exponential upper bound is \(Z_1Z_2Z_3=\sqrt{15}/10=0.387298\). A bound need not equal the realized error. These prescribed prediction vectors illustrate the update independently of a particular weak-learner fitting implementation.
The Freund–Schapire paper develops the weak-learning framework. The calculation here fixes the binary score and normalization conventions explicitly.
12.3 Gradient Boosting
Gradient Boosting generalizes boosting to arbitrary differentiable loss functions using gradient descent in function space.
Definition 12.5 (Gradient Boosting Framework). Goal: Minimize loss over training data: \[\mathcal{L}= \frac1n\sum_{i=1}^n \ell(y_i, F(\boldsymbol{x}_i))\] where \(F(\boldsymbol{x})\) is our ensemble model.
Key insight: At iteration \(t\), we have current model \(F_{t-1}\). Using the empirical inner product \(\langle\boldsymbol{u},\boldsymbol{v}\rangle_n=n^{-1}\sum_i u_iv_i\), the negative-gradient direction has components: \[-\nabla_F \mathcal{L}= -\left[\frac{\partial \ell(y_i, F(\boldsymbol{x}_i))}{\partial F(\boldsymbol{x}_i)}\right]_{F=F_{t-1}}\] These are the negative gradients or pseudo-residuals.
Gradient Boosting Machine (GBM)
Input: Data \(\{(\boldsymbol{x}_i, y_i)\}\), loss \(\ell\), number of iterations \(M\), learning rate \(\eta\)
Initialize: \(F_0(\boldsymbol{x}) = \mathop{\mathrm{arg\,min}}_c \sum_{i=1}^n \ell(y_i, c)\)
For \(m = 1\) to \(M\):
Compute pseudo-residuals: \[r_{im} = -\left[\frac{\partial \ell(y_i, F(\boldsymbol{x}_i))}{\partial F(\boldsymbol{x}_i)}\right]_{F=F_{m-1}}\]
Fit base learner \(h_m\) to pseudo-residuals: \(h_m \approx \{(\boldsymbol{x}_i, r_{im})\}\)
Find optimal step size: \[\rho_m = \mathop{\mathrm{arg\,min}}_\rho \sum_{i=1}^n \ell(y_i, F_{m-1}(\boldsymbol{x}_i) + \rho h_m(\boldsymbol{x}_i))\]
Update model: \[F_m(\boldsymbol{x}) = F_{m-1}(\boldsymbol{x}) + \eta \rho_m h_m(\boldsymbol{x})\] where \(\eta\) is the learning rate (typically 0.01-0.3).
Output: \(F_M(\boldsymbol{x})\)
Example 12.6 (Gradient Boosting for Regression). With squared loss \(\ell(y,F)=(y-F)^2\), the pseudo-residual is \(r_{im}=2(y_i-F_{m-1}(\boldsymbol{x}_i))\). It is twice the ordinary residual. The line search accounts for this scale; the detailed example below uses the same MSE convention as Part 1. A half-squared-loss formulation gives ordinary residuals but must use its corresponding steps and regularization.
Gradient Boosting vs AdaBoost:
AdaBoost: Adjusts example weights (specific to exponential loss)
Gradient Boosting: Fits negative derivatives for differentiable losses; nonsmooth losses require suitable subgradient/leaf-update conventions
Common loss functions:
Regression: Squared loss, absolute loss, Huber loss
Classification: Logistic loss (log-likelihood)
Ranking: Pairwise ranking loss
Base learners: Typically shallow decision trees (depth 3-8). Deeper trees capture interactions but may overfit.
12.3.1 Function-Space Descent with the Same MSE Convention
Write \(\widehat R(F)=n^{-1}\sum_i\ell(y_i,F(\boldsymbol{x}_i))\). In the finite vector of training predictions, its gradient is \(n^{-1}(\partial\ell_i/\partial F_i)_i\). Using the empirical inner product \(\langle\boldsymbol{u},\boldsymbol{v}\rangle_n=n^{-1}\sum_i u_iv_i\), the functional gradient has components \(\partial\ell_i/\partial F_i\). This explains why the pseudo-residual convention omits a separate \(1/n\): the averaging is in the inner product and the fitted risk. Fit a weak learner to the negative-gradient vector, then minimize the risk along that direction before shrinkage.
Here squared-error loss is \(\ell(y,F)=(y-F)^2\), exactly as in Part 1. Consequently \(r_i=2(y_i-F_i)\). A half-squared convention would give residual \(y_i-F_i\); with an exact unrestricted line search the compensating step size changes accordingly, while a fixed step or regularization must be rescaled. Do not silently combine one convention’s residuals with the other’s step size.
Example 12.7 (Two complete regression boosting rounds). Use \(x=(1,2,3,4)\), \(y=(1,2,4,5)\), and shrinkage \(\eta=1/2\). The best constant is \(F_0=\bar y=3\), with MSE \(2.5\). The first pseudo-residual vector is \((-4,-2,2,4)\). Among all three candidate stump thresholds, \(2.5\) gives the smallest fitting SSE, with leaf predictions \(h_1=(-3,-3,3,3)\). Squared loss has the exact line-search solution \[\rho_1=\frac{\sum_i(y_i-F_0)h_1(\boldsymbol{x}_i)}{\sum_i h_1(\boldsymbol{x}_i)^2}=\frac{18}{36}=\frac12.\] The first updated prediction vector is \[F_1=F_0+\eta\rho_1h_1=(2.25,2.25,3.75,3.75),\qquad\mathrm{MSE}=0.8125.\] At round 2, pseudo-residuals are \((-2.5,-0.5,0.5,2.5)\). The best stump again splits at \(2.5\) with \(h_2=(-1.5,-1.5,1.5,1.5)\); \(\rho_2=1/2\). Hence \[F_2=(1.875,1.875,4.125,4.125),\qquad \mathrm{MSE}=0.390625.\] The constant, direction-fitting, line-search, and shrinkage steps are separate optimizations. A leaf-wise line search can assign a different step to each leaf; the preceding algorithm instead uses one scalar \(\rho_t\) per fitted direction.
For binary logistic loss \(\ell(y,F)=\log(1+e^F)-yF\), the pseudo-residual is \(y-\sigma(F)\), and the constant optimum is the training log-odds when both classes occur. An unregularized line search may have no finite minimizer on a perfectly separating direction, just as the logistic MLE can diverge in Part 1. Implementations use finite, regularized, or leaf-wise updates. Early stopping selects the number of rounds on validation data; reserve final test data for the frozen selection procedure. See Friedman’s gradient-boosting paper for the stagewise optimization framework.
12.4 XGBoost (Extreme Gradient Boosting)
XGBoost is an optimized implementation of gradient boosting with several enhancements.
Definition 12.8 (XGBoost Objective). At iteration \(t\), minimize: \[\mathcal{L}^{(t)} = \sum_{i=1}^n \ell(y_i, F_{t-1}(\boldsymbol{x}_i) + h_t(\boldsymbol{x}_i)) + \Omega(h_t)\] where \(\Omega(h_t)\) is a regularization term: \[\Omega(h) = \gamma T + \frac{1}{2}\lambda\sum_{j=1}^T w_j^2\] \(T\) = number of leaves, \(w_j\) = leaf weights, \(\gamma\) and \(\lambda\) are regularization parameters.
Key innovations in XGBoost:
Regularization: Explicit control of tree complexity
Second-order approximation: Uses both gradients and Hessians for better optimization
Sparsity awareness: Handles missing values naturally
Column subsampling: Like Random Forest feature randomness
Parallel tree construction: Fast implementation
Cache-aware access patterns: Optimized for modern hardware
Key XGBoost Hyperparameters:
n_estimators: Number of boosting rounds (100-1000)
learning_rate (\(\eta\)): Step size shrinkage (0.01-0.3). Lower usually requires more rounds; the generalization effect needs validation
max_depth: Tree depth (3-10). Deeper \(\to\) more interactions but overfitting
subsample: Fraction of training rows sampled per boosting round (0.5-1.0). Standard uniform row subsampling is without replacement, unlike bootstrap bagging
colsample_bytree: Fraction of features per tree (0.5-1.0)
gamma: Minimum loss reduction for split (regularization)
lambda: L2 regularization on weights
alpha: L1 regularization on weights
Tuning strategy:
Fix learning rate (e.g., 0.1), tune tree parameters (max_depth, subsample, colsample)
Tune regularization (gamma, lambda, alpha)
Validate learning rate and round count jointly within the selection protocol, then freeze the chosen combination for the final model
12.4.1 Deriving Leaf Weights and Split Gain
The XGBoost objective above deliberately uses a sum of per-example losses, unlike reported MSE. Expand each loss around the current training score: \[\ell(y_i,F_i+h_i)=\ell(y_i,F_i)+g_ih_i+\tfrac12s_i h_i^2+\text{higher-order terms}, \quad g_i=\frac{\partial\ell_i}{\partial F_i},\quad s_i=\frac{\partial^2\ell_i}{\partial F_i^2}.\] Here \(s_i\) is scalar curvature, not a fitted weak learner. For a fixed tree with leaf index sets \(I_j\) and output weights \(w_j\), put \(G_j=\sum_{i\in I_j}g_i\) and \(S_j=\sum_{i\in I_j}s_i\). Dropping constants, the second-order objective is \[\widetilde{\mathcal{L}}=\sum_{j=1}^{T}\left[G_jw_j+\tfrac12(S_j+\lambda)w_j^2\right]+\gamma T.\] For \(S_j+\lambda>0\), differentiation gives \[w_j^*=-\frac{G_j}{S_j+\lambda},\qquad \widetilde{\mathcal{L}}^*=-\frac12\sum_j\frac{G_j^2}{S_j+\lambda}+\gamma T.\] Replacing one parent leaf by two child leaves therefore improves the approximation by \[\operatorname{Gain}=\frac12\left[\frac{G_L^2}{S_L+\lambda}+\frac{G_R^2}{S_R+\lambda} -\frac{(G_L+G_R)^2}{S_L+S_R+\lambda}\right]-\gamma.\] A split must pay for the additional leaf. For squared loss this Taylor expansion is exact; for other smooth losses it is a local approximation. An L1 leaf penalty \(\alpha\sum_j|w_j|\) replaces the numerator by soft-thresholding: \(w_j^*=-S(G_j,\alpha)/(S_j+\lambda)\), using the soft-threshold function defined in Part 1. Shrinking the optimized leaf outputs afterward generally changes their status as exact conditional minimizers.
Example 12.9 (Checking a split against the actual penalized objective). Use the same four targets \((1,2,4,5)\) and current prediction \(F_i=3\). For \(\ell=(y-F)^2\), gradients are \((4,2,-2,-4)\) and every curvature is 2. Splitting after row 2 gives \(G_L=6,G_R=-6,S_L=S_R=4\). With \(\lambda=2,\gamma=0.1\), optimal outputs are \(w_L=-1,w_R=1\), and split gain is \(\tfrac12(36/6+36/6)-0.1=5.9\).
The unsplit optimal output is zero, with objective \(10+0.1=10.1\). The split gives updated predictions \((2,2,4,4)\): SSE is 2, the quadratic penalty is \(\tfrac22(1+1)=2\), and two leaves cost \(0.2\). The new objective is 4.2, confirming the exact improvement \(10.1-4.2=5.9\).
To express this same objective with mean squared loss, divide the entire objective by \(n=4\): use \(\lambda'=\lambda/n=0.5\) and \(\gamma'=\gamma/n=0.025\). The leaf penalty still has form \((\lambda'/2)\sum_jw_j^2\): its actual squared-weight coefficient is \(0.25\), which matches the coefficient called \(\lambda\) in Part 1’s ridge convention. Retaining the original penalties while dividing only the loss changes the optimum. Library regression objectives may use half-squared loss; consult the documented definition before transferring these numbers.
The Chen–Guestrin paper derives tree scoring and system optimizations. The parameter documentation distinguishes growth policies and regularization controls; one library name does not imply a single fixed tree-growing policy.
12.5 LightGBM and CatBoost
Definition 12.10 (LightGBM). Microsoft’s gradient boosting framework with novel algorithms:
Leaf-wise tree growth: Splits the leaf with maximum gain; this contrasts with a depth-wise policy, not every possible XGBoost configuration. Depth and leaf constraints control capacity.
Gradient-based One-Side Sampling (GOSS): Keeps all large-gradient examples, randomly samples small-gradient ones. Uses reweighted sampled statistics to approximate split search; predictive accuracy still requires evaluation.
Exclusive Feature Bundling (EFB): Bundles mutually exclusive features (sparse features). Reduces dimensionality.
Advantage: Very fast training, especially on large datasets and high dimensions.
Definition 12.11 (CatBoost). Yandex’s gradient boosting with focus on categorical features:
Ordered boosting: Novel approach to prevent target leakage and prediction shift
Feature quantization: Uses training-fitted numerical bins; binning settings are part of the selected procedure
Native categorical feature support: No need for manual encoding
Symmetric trees: The default symmetric-tree policy uses the same split at each depth; other growth policies can be selected
Advantage: Robust to overfitting, works well out-of-the-box, excellent for categorical data.
| Aspect | XGBoost | LightGBM | CatBoost |
|---|---|---|---|
| Tree construction | Configurable depth- or loss-guided growth | Commonly leaf-wise with depth/leaf controls | Symmetric-tree default; other policies exist |
| Distinctive methods | Second-order leaf scoring, sparsity-aware splits | Histograms, GOSS, feature bundling | Ordered statistics and ordered boosting |
| Categorical inputs | Configured native support or encoding | Configured native support or encoding | Native categorical processing |
| Evaluation | Compare a fixed validation protocol, search budget, data representation, and hardware; speed, accuracy, memory, and robustness have no universal ordering. | ||
12.5.1 Why Ordered Statistics Matter
Example 12.12 (An ordered target statistic without a row’s own label). Suppose a training permutation has categories \((A,A,B,A,B)\) and labels \((1,0,0,1,1)\). Fix prior mean \(p_0=1/2\) and prior weight \(a=2\). Encode row \(i\) using only earlier training rows of its category: \[\operatorname{enc}_i=\frac{\sum_{j<i:\,c_j=c_i}y_j+ap_0}{|\{j<i:c_j=c_i\}|+a}.\] This gives \((1/2,2/3,1/2,1/2,1/3)\). At row 4, only the first two \(A\) labels contribute: \((1+1)/(2+2)=1/2\). Changing \(y_4\) cannot change its own encoding, but can affect later rows. A raw full-training category mean would use the row’s label inside its own feature.
For a new observation, the frozen full-training statistics give \(\operatorname{enc}(A)=(2+1)/(3+2)=3/5\) and \(\operatorname{enc}(B)=(1+1)/(2+2)=1/2\); an unseen category uses the fixed prior. No validation or test labels enter these calculations. This is one specified smoothed statistic, not a claim about every internal CatBoost configuration.
Ordered categorical statistics and ordered boosting solve related but distinct problems. The former restricts which labels contribute to an encoding; the latter constructs training predictions/residuals using preceding samples to reduce prediction shift. Neither replaces external group/time splits or an untouched final test set. The CatBoost paper develops both ideas.
Sampling and histograms in LightGBM. Histogram methods aggregate gradient and curvature statistics into feature bins. Leaf-wise growth spends a split where the current gain is largest; depth and leaf constraints control the resulting capacity. GOSS keeps a fraction \(a\) of large-gradient observations and samples a fraction \(b\) of the original sample size from the remaining fraction \(1-a\). Each sampled small-gradient observation represents weight \((1-a)/b\). For \(n=10,a=0.2,b=0.1\), retain the two largest-gradient rows and sample one of the other eight with multiplier 8. If those eight gradients are \(0.1,0.2,\ldots,0.8\), their sum is 3.6, whereas sampling the \(0.4\) row estimates it as 3.2. The estimate is unbiased over uniform sampling of that group, not exact on each draw; a nonlinear split-gain ratio is not automatically an unbiased estimate merely because gradient sums are. EFB combines mostly mutually exclusive sparse features using distinguishable bins. See the LightGBM paper and its feature documentation.
12.6 Regularization in Boosting
Boosting is prone to overfitting as we add more trees. Several regularization techniques:
1. Learning Rate (Shrinkage): \[F_m = F_{m-1} + \eta \cdot h_m, \quad 0 < \eta \leq 1\] Smaller \(\eta\) usually requires more trees; validation determines whether the resulting procedure generalizes better. Typical: \(\eta = 0.01\) to \(0.1\).
2. Early Stopping: Monitor validation error. Stop adding trees when validation error stops improving.
3. Subsampling:
Row subsampling: Use random fraction of examples per tree (0.5-1.0)
Column subsampling: Use random fraction of features per tree (0.5-1.0)
Adds randomness like Random Forest, reduces overfitting.
4. Tree Constraints:
Max depth: Limit tree complexity (3-8 typically)
Min samples per leaf: Require minimum examples in leaf nodes
Max number of leaves: Direct control on tree size
5. Explicit Regularization (XGBoost): Add penalty terms for tree complexity (number of leaves, L1/L2 on weights).
Best practice: Combine multiple techniques. Use cross-validation to tune.
12.7 When to Use Boosting vs Bagging
| Aspect | Bagging / random forests | Boosting |
|---|---|---|
| Construction | Bootstrap fits with independent random seeds conditional on data | Sequential additive corrections |
| Aggregation | Equal-weight prediction averaging or voting | Loss-dependent fitted corrections and shrinkage |
| Dependence | Shared dataset induces prediction correlation | Later fits depend on the preceding ensemble |
| Capacity controls | Feature sampling, depth, leaf size | Round count, shrinkage, tree constraints, penalties |
| Evaluation | OOB under its fitting assumptions, or held-out/outer evaluation | Validation for rounds/settings, then held-out/outer evaluation |
Choose candidates by feature types, data size, inference constraints, and a declared validation budget. Compare complete procedures under the same splits. Correlated errors, noisy labels, regularization, and feature handling matter more than a blanket library ranking.
13 Stacking and Blending
13.1 Stacking (Stacked Generalization)
Definition 13.1 (Stacking). Train a meta-model (or blender) to combine predictions from multiple base models.
Two levels:
Level 0: Train diverse base models on training data
Level 1: Train meta-model on base model predictions
Stacking with Cross-Validation
Training:
Step 1: Train level-0 models with CV
Split training data into \(K\) folds
For each base model \(m\) and fold \(k\):
Train \(m\) on folds \(\{1, \ldots, K\} \setminus \{k\}\)
Predict on fold \(k\) (out-of-fold predictions)
Concatenate out-of-fold predictions to get \(\hat{\boldsymbol{y}}_m^{\text{OOF}}\) for each model
Retrain each model on full training set for final level-0 models
Step 2: Train level-1 meta-model
Meta-features: \([\hat{\boldsymbol{y}}_1^{\text{OOF}}, \hat{\boldsymbol{y}}_2^{\text{OOF}}, \ldots, \hat{\boldsymbol{y}}_M^{\text{OOF}}]\)
Meta-target: Original labels \(\boldsymbol{y}\)
Train meta-model: \(f_{\text{meta}}(\hat{y}_1, \ldots, \hat{y}_M) \to y\)
Prediction:
Get predictions from all level-0 models
Feed to meta-model for final prediction
Intuition 179. Stacking fits a combining rule from data; the optimum is relative to its meta-model class and training objective. If model 1 is good at some types of examples and model 2 at others, the meta-model learns when to trust each one.
Why cross-validation? Training base models on full data and then meta-model on training predictions would overfit—base models have seen these examples. CV creates out-of-fold predictions that base models haven’t seen, giving more honest signals to the meta-model.
13.2 A Fully Worked OOF Meta-Training Matrix
Example 13.3 (Fit, assemble, refit, predict). Use four regression observations \(x=(0,1,2,3)\) and \(y=(0,1,1,2)\). Fix two base procedures: a constant mean and an affine OLS fit. Hold out rows \(\{1,3\}\) in fold A and rows \(\{2,4\}\) in fold B.
Training on rows 2 and 4 gives constant \(1.5\) and OLS line \(0.5+0.5x\). Predictions for held-out rows 1 and 3 are therefore \((1.5,0.5)\) and \((1.5,1.5)\). Training on rows 1 and 3 gives constant \(0.5\) and line \(0.5x\), giving held-out rows 2 and 4 the pairs \((0.5,0.5)\) and \((0.5,1.5)\). Restoring original row order yields \[\boldsymbol{Z}_{\rm OOF}=\begin{bmatrix}1.5&0.5\\0.5&0.5\\1.5&1.5\\0.5&1.5\end{bmatrix}, \qquad\boldsymbol{y}=\begin{bmatrix}0\\1\\1\\2\end{bmatrix}.\] OLS meta-regression with an intercept gives \(f_{\rm meta}(z_1,z_2)=1-z_1+z_2\), exactly fitting these four meta-training rows. The negative weight is allowed; ordinary stacking does not constrain weights to a convex average.
For deployment, refit the constant and affine base procedures on all four training rows. They become \(h_1=1\) and \(h_2(x)=0.1+0.6x\). A new \(x=4\) produces meta-features \((1,2.5)\) and final prediction \(1-1+2.5=2.5\). The zero meta-training error is not a held-out evaluation of this stack. OOF base fits used two rows, while the refitted bases use four; this feature-distribution difference is one source of finite-sample uncertainty.
Every base learner includes its preprocessing. A scaler, PCA fit, feature selection, or target encoding must be fitted inside the base learner’s training fold. If a base procedure tunes its own hyperparameters, the tuning data must also stay within that fold when constructing genuinely held-out base predictions. To assess stack selection and final performance, put the entire stack inside an outer validation protocol. An OOF meta-training matrix is not itself a set of held-out predictions from the fitted meta-model.
The StackingClassifier documentation distinguishes its internal CV for meta-features from performance evaluation. Passing prefit bases that already saw the meta-training rows does not reproduce the OOF construction. For grouped or temporal problems, use a compatible fold-construction strategy at every level; ordinary random internal folds do not acquire group/time safety merely because the outer split is safe. Furthermore, StackingClassifier constructs its meta-training inputs using cross_val_predict, which requires validation indices to form a partition. An ordinary expanding TimeSeriesSplit leaves an initial prefix without validation predictions and is not a direct drop-in replacement. For forward stacking, explicitly construct OOF features only for eligible later rows with strictly earlier base fits, and fit the meta-model on those rows; do not fill the initial prefix with in-sample predictions. Test the complete construction outside that meta-training period. The example below treats rows as independent and uses the SVM’s decision scores; enabling built-in probability calibration would introduce another internal split design to audit.
13.3 Blending
Definition 13.4 (Blending). Simplified version of stacking:
Split data: training set + hold-out validation set
Train base models on training set only
Generate predictions on hold-out set
Train meta-model on hold-out predictions
The holdout here is a meta-training set, not a held-out performance evaluation of the fitted blend. Keep the base models frozen under this specified procedure. Selecting meta-model settings needs validation or an outer evaluation; report final performance on a separate test set. Refitting bases later changes the meta-feature distribution and must be assessed as a new complete procedure.
Difference from stacking: Uses one meta-training holdout instead of OOF construction.
Blending vs Stacking:
Blending: Simpler, faster, but wastes data (hold-out not used for base model training)
Stacking: More complex, uses all data efficiently, more robust
13.4 Choosing Base Models
Diversity is key! Choose base models that make different types of errors.
Good base model combinations:
Different algorithms: Linear models, tree-based, neural networks, SVMs
Different feature sets: Some models with all features, some with subsets
Different hyperparameters: Multiple trees with different depths
Different preprocessing: Some with PCA, some without; different scalings
Poor combination: 5 XGBoost models with similar hyperparameters (too correlated).
Meta-model choices:
Linear/Logistic Regression: Simple, interpretable weights show model contributions
Shallow tree: Can capture interactions between base models
Neural network: Can learn complex combinations
Usually simple meta-models work best—base models already do the heavy lifting.
13.5 Practical Implementation
Stacking in Practice:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.svm import SVC
# Independent-row demonstration; X_train/X_test are already separated.
# SVC supplies decision scores, avoiding an internal probability CV.
# Define base models
base_models = [
('rf', RandomForestClassifier(n_estimators=100, random_state=42)),
('xgb', XGBClassifier(n_estimators=100, random_state=42, n_jobs=1)),
('svm', make_pipeline(StandardScaler(), SVC()))
]
# Define meta-model
meta_model = LogisticRegression()
# Create stacking ensemble
stacking = StackingClassifier(
estimators=base_models,
final_estimator=meta_model,
cv=5 # 5-fold CV for out-of-fold predictions
)
# Train
stacking.fit(X_train, y_train)
# Predict
y_pred = stacking.predict(X_test)Tips:
Use 5-10 fold CV for stacking
Include original features as inputs to meta-model (optional, often helps)
For competitions: Stack multiple levels (3-4 levels possible)
Ensure no information leakage between levels
Select settings on validation data and report the frozen complete stack on a separate final test set
13.6 Multi-Level Stacking
Definition 13.5 (Multi-Level Stacking). Extend to more than 2 levels:
Level 0: Many diverse base models
Level 1: Mid-level models on level-0 predictions
Level 2: Top-level meta-model on level-1 predictions
... (can continue)
Caution: Diminishing returns after 2-3 levels. More levels increase:
Complexity and computational cost
Risk of overfitting
Difficulty in debugging
Used mainly in competitions where every 0.01% matters.
13.7 Summary of Part 3
Ensemble Learning: Combine multiple models for better performance. Three paradigms: bagging, boosting, stacking.
Bagging/Random Forests: Average bootstrap fits; feature randomness can reduce shared errors. OOB estimates require coverage and honest preprocessing, and do not replace independent evaluation after selection.
AdaBoost: Sequential training with adaptive example weights. Focuses on hard examples. Requires weak learners better than random.
Gradient Boosting: Generalizes boosting to arbitrary losses via functional gradient descent. XGBoost, LightGBM, CatBoost are modern optimized implementations with regularization.
Boosting Regularization: Learning rate, early stopping, subsampling, tree constraints. Essential to prevent overfitting.
Stacking: Fit a meta-model on OOF base predictions, refit bases on non-test training data, and evaluate the whole procedure outside meta-training.
Model Selection: Compare candidates and search budgets on compatible validation splits; no model family guarantees maximum accuracy.
Next Steps: Part 4 covers neural networks and deep learning: perceptrons, backpropagation, CNNs, RNNs, Transformers, and modern optimization techniques.
Exercise 13.6.
Show that the probability of a specific example appearing in a bootstrap sample approaches \(1 - e^{-1} \approx 0.632\) as \(n \to \infty\).
Under the explicit assumption of independent errors, let 101 binary classifiers each be correct with probability \(0.9\). Express the majority-vote accuracy using a binomial sum. Explain why individual accuracies and pairwise correlations alone do not generally determine majority-vote accuracy.
In AdaBoost, suppose a weak learner has error rate \(\epsilon_t = 0.4\). Compute its weight \(\alpha_t\). What happens if \(\epsilon_t = 0.5\) (random guessing)?
For the stated squared loss, derive pseudo-residuals \(2(y-F)\). Show how an exact line search compensates for this factor compared with half-squared loss, and explain what changes if a fixed step is used.
Design a stacking ensemble with 4 base models for a classification task. What would you choose as base models and meta-model? Justify your choices.
Compare computational complexity: training 100 decision trees in Random Forest vs XGBoost. Which is faster and why?
Compare validation curves for learning rates \(0.01\) and \(0.3\) while varying the number of trees. Explain why the learning rate alone does not determine the required number of boosting rounds.
Part 4: Neural Networks and Deep Learning
14 The Perceptron
14.1 The Perceptron Model
Definition 14.1 (Perceptron). The perceptron is the simplest neural network unit, proposed by Rosenblatt (1958). For binary classification with \(y \in \{-1, +1\}\): \[\hat{y} = \text{sign}(\boldsymbol{w}^\top\boldsymbol{x} + b) = \text{sign}\left(\sum_{i=1}^d w_i x_i + b\right)\] where \(\boldsymbol{w}\) are weights, \(b\) is bias, and \(\text{sign}(z) = \begin{cases} +1 & z \geq 0 \\ -1 & z < 0 \end{cases}\).
Intuition 185. The perceptron is a linear classifier: it separates data with a hyperplane. Think of it as a simplified neuron that “fires” (+1) when the weighted input exceeds a threshold, and doesn’t fire (-1) otherwise.
14.2 Perceptron Learning Algorithm
Perceptron Learning Rule
Input: Training data \(\{(\boldsymbol{x}_i, y_i)\}_{i=1}^n\) with \(y_i \in \{-1, +1\}\)
Initialize: \(\boldsymbol{w} = \boldsymbol{0}\), \(b = 0\)
Repeat until convergence (or max iterations):
For each training example \((\boldsymbol{x}_i, y_i)\):
Compute prediction: \(\hat{y}_i = \text{sign}(\boldsymbol{w}^\top\boldsymbol{x}_i + b)\)
If \(\hat{y}_i \neq y_i\) (misclassified): \[\boldsymbol{w} \leftarrow \boldsymbol{w} + y_i\boldsymbol{x}_i, \quad b \leftarrow b + y_i\]
Output: Learned weights \(\boldsymbol{w}\) and bias \(b\)
Intuition 186. The update rule is intuitive:
If true label is \(+1\) but we predicted \(-1\): increase \(\boldsymbol{w}\) in direction of \(\boldsymbol{x}\)
If true label is \(-1\) but we predicted \(+1\): decrease \(\boldsymbol{w}\) in direction of \(\boldsymbol{x}\)
Correct predictions: no update
This gradually rotates the hyperplane to correctly classify examples.
Theorem 14.4 (Perceptron Convergence Theorem). Use augmented inputs \(\tilde{\boldsymbol{x}}_i=[\boldsymbol{x}_i^\top,1]^\top\) and parameters \(\boldsymbol{u}=[\boldsymbol{w}^\top,b]^\top\), so the stated weight and bias updates together are \(\boldsymbol{u}\leftarrow\boldsymbol{u}+y_i\tilde{\boldsymbol{x}}_i\). If \(\left\lVert\tilde{\boldsymbol{x}}_i\right\rVert\leq R\) and a unit vector \(\boldsymbol{u}^*\) satisfies \(y_i\boldsymbol{u}^{*\top}\tilde{\boldsymbol{x}}_i\geq\gamma>0\) for every example, zero initialization yields at most \((R/\gamma)^2\) mistakes.
Proof. At an update, the misclassified example has \(y_i\boldsymbol{u}_k^\top\tilde{\boldsymbol{x}}_i\le0\). Hence \[\begin{align*} \boldsymbol{u}_{k+1}^\top\boldsymbol{u}^*&\ge\boldsymbol{u}_k^\top\boldsymbol{u}^*+\gamma,\\ \|\boldsymbol{u}_{k+1}\|^2 &=\|\boldsymbol{u}_k\|^2+2y_i\boldsymbol{u}_k^\top\tilde{\boldsymbol{x}}_i+ \|\tilde{\boldsymbol{x}}_i\|^2\le\|\boldsymbol{u}_k\|^2+R^2. \end{align*}\] From zero initialization, after \(k\) mistakes these bounds imply \(k\gamma\le\boldsymbol{u}_k^\top\boldsymbol{u}^*\le\|\boldsymbol{u}_k\| \le\sqrt{k}R\), so \(k\le(R/\gamma)^2\) when \(k>0\). The inputs include the bias coordinate. Nonseparable data need not terminate. ◻
14.3 Limitations of the Perceptron
The XOR Problem:
Perceptron can only learn linearly separable functions. The XOR function is not linearly separable:
| \(x_1\) | \(x_2\) | XOR |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
No single line can separate the 1s from the 0s!
Solution: Use multiple perceptrons in layers \(\to\) Multi-Layer Perceptron (MLP) can learn XOR.
Historical note: Minsky and Papert (1969) analyzed limitations of perceptron architectures. XOR is a representational limitation of one affine unit; it does not establish a single-cause explanation for the broader history of neural-network research.
14.4 A Complete AND Training Trace
The following trace uses the update and tie conventions of the preceding theorem; it is not a maximum-margin fit.
Example 14.5 (Every update in an AND perceptron). Cycle through the rows of \[\boldsymbol{X}=\begin{bmatrix}0&0\\0&1\\1&0\\1&1\end{bmatrix},\qquad\boldsymbol{y}=(-1,-1,-1,+1)^\top.\] Start at zero and use the earlier convention \(\operatorname{sign}(0)=+1\). Correct predictions cause no update; all updates are shown below.
| Epoch | Updated row | \(w_1\) | \(w_2\) | \(b\) |
|---|---|---|---|---|
| 1 | 1 | 0 | 0 | -1 |
| 1 | 4 | 1 | 1 | 0 |
| 2 | 1 | 1 | 1 | -1 |
| 2 | 2 | 1 | 0 | -2 |
| 2 | 4 | 2 | 1 | -1 |
| 3 | 2 | 2 | 0 | -2 |
| 3 | 3 | 1 | 0 | -3 |
| 3 | 4 | 2 | 1 | -2 |
| 4 | 3 | 1 | 1 | -3 |
| 4 | 4 | 2 | 2 | -2 |
| 5 | 2 | 2 | 1 | -3 |
Epoch 6 makes no changes. Final scores are \((-3,-2,-1,0)\) and all labels are correct under the stated tie rule. A positive example lies exactly on the boundary; the perceptron did not optimize a positive geometric margin. This differs from SVM’s maximum-margin objective.
15 Artificial Neural Networks
15.1 The Neuron Model
Definition 15.1 (Artificial Neuron). A neuron computes: \[a = f\left(\sum_{i=1}^d w_i x_i + b\right) = f(\boldsymbol{w}^\top\boldsymbol{x} + b)\] where:
\(\boldsymbol{x} = [x_1, \ldots, x_d]^\top\) are inputs
\(\boldsymbol{w} = [w_1, \ldots, w_d]^\top\) are weights
\(b\) is bias
\(f\) is the activation function
\(a\) is the neuron’s output (activation)
15.2 Activation Functions
Definition 15.2 (Common Activation Functions). 1. Sigmoid: \[\sigma(z) = \frac{1}{1 + e^{-z}}, \quad \sigma'(z) = \sigma(z)(1-\sigma(z))\] Range: \((0, 1)\). Used in output layer for binary classification.
2. Hyperbolic Tangent (Tanh): \[\tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}}, \quad \tanh'(z) = 1 - \tanh^2(z)\] Range: \((-1, 1)\). Zero-centered (better than sigmoid for hidden layers).
3. ReLU (Rectified Linear Unit): \[\text{ReLU}(z) = \max(0, z), \quad \text{ReLU}'(z) = \begin{cases} 1 & z > 0 \\ 0 & z < 0 \end{cases}\] At zero ReLU is nondifferentiable; select the conventional backpropagation value 0. It is widely used in hidden layers and avoids saturation on its positive branch, but does not by itself guarantee stable gradients.
4. Leaky ReLU: \[\text{LeakyReLU}(z) = \max(\alpha z, z), \quad \alpha \in (0, 1) \text{ typically } 0.01\] Provides a nonzero negative-input slope, which can reduce the zero-local-gradient problem of inactive ReLU units.
5. GELU (Gaussian Error Linear Unit): \[\text{GELU}(z) = z \cdot \Phi(z)\] where \(\Phi\) is the Gaussian CDF. Smooth, used in Transformers (BERT, GPT).
6. Softmax (for output layer, multi-class): \[\text{softmax}(\boldsymbol{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}\] Converts logits to probability distribution.
Why non-linear activations?
Without non-linearity, stacking layers is useless: \[\boldsymbol{W}_2(\boldsymbol{W}_1\boldsymbol{x}+\boldsymbol{b}_1)+\boldsymbol{b}_2 = (\boldsymbol{W}_2\boldsymbol{W}_1)\boldsymbol{x}+(\boldsymbol{W}_2\boldsymbol{b}_1+\boldsymbol{b}_2)\] Multiple affine layers collapse to a single affine transformation. With suitable non-linear activations and sufficient width, networks can approximate continuous functions on compact domains arbitrarily well; this existence result does not guarantee that training finds such an approximation.
Choosing activation:
Hidden layers: ReLU (default), Leaky ReLU, GELU
Output layer:
Binary classification: Sigmoid
Multi-class: Softmax
Regression: Linear (no activation)
15.3 Multi-Layer Perceptron (MLP)
Definition 15.3 (Feedforward Neural Network). An MLP with \(L\) layers has:
Input layer: \(\boldsymbol{x} = \boldsymbol{a}^{(0)} \in \mathbb{R}^{d_0}\)
Hidden layers \(\ell = 1, \ldots, L-1\): \[\boldsymbol{z}^{(\ell)} = \boldsymbol{W}^{(\ell)}\boldsymbol{a}^{(\ell-1)} + \boldsymbol{b}^{(\ell)}, \quad \boldsymbol{a}^{(\ell)} = f^{(\ell)}(\boldsymbol{z}^{(\ell)})\]
Output layer \(\ell = L\): \[\boldsymbol{z}^{(L)} = \boldsymbol{W}^{(L)}\boldsymbol{a}^{(L-1)} + \boldsymbol{b}^{(L)}, \quad \hat{\boldsymbol{y}} = \boldsymbol{a}^{(L)} = f^{(L)}(\boldsymbol{z}^{(L)})\]
where \(\boldsymbol{W}^{(\ell)} \in \mathbb{R}^{d_\ell \times d_{\ell-1}}\), \(\boldsymbol{b}^{(\ell)} \in \mathbb{R}^{d_\ell}\).
15.4 Forward Propagation
Forward Propagation Algorithm
Input: Example \(\boldsymbol{x}\), network parameters \(\{\boldsymbol{W}^{(\ell)}, \boldsymbol{b}^{(\ell)}\}_{\ell=1}^L\)
Initialize: \(\boldsymbol{a}^{(0)} = \boldsymbol{x}\)
For \(\ell = 1\) to \(L\):
Compute pre-activation: \(\boldsymbol{z}^{(\ell)} = \boldsymbol{W}^{(\ell)}\boldsymbol{a}^{(\ell-1)} + \boldsymbol{b}^{(\ell)}\)
Compute activation: \(\boldsymbol{a}^{(\ell)} = f^{(\ell)}(\boldsymbol{z}^{(\ell)})\)
Output: Prediction \(\hat{\boldsymbol{y}} = \boldsymbol{a}^{(L)}\)
15.5 Loss Functions
Definition 15.4 (Common Loss Functions). Regression (continuous output):
Mean Squared Error: \(\mathcal{L}= \frac{1}{n}\sum_{i=1}^n \left\lVert\boldsymbol{y}_i - \hat{\boldsymbol{y}}_i\right\rVert_2^2\)
Mean Absolute Error: \(\mathcal{L}= \frac{1}{n}\sum_{i=1}^n \left\lVert\boldsymbol{y}_i - \hat{\boldsymbol{y}}_i\right\rVert_1\)
Binary Classification:
Binary Cross-Entropy: \[\mathcal{L}= -\frac{1}{n}\sum_{i=1}^n [y_i\log(\hat{y}_i) + (1-y_i)\log(1-\hat{y}_i)]\]
Multi-Class Classification:
Categorical Cross-Entropy: \[\mathcal{L}= -\frac{1}{n}\sum_{i=1}^n \sum_{k=1}^K y_{ik}\log(\hat{y}_{ik})\] where \(\boldsymbol{y}_i\) is one-hot encoded.
15.6 Backpropagation
Backpropagation efficiently computes gradients using the chain rule.
Theorem 15.5 (Backpropagation Equations). For a single example, let \(\ell\) denote its loss. Index layers by \(r=1,\ldots,L\) and define \(\boldsymbol{\delta}^{(r)}=\nabla_{\boldsymbol{z}^{(r)}}\ell\). The dataset loss remains the mean of per-example losses.
For activation \(f^{(r)}\), let \(\boldsymbol{J}_{f^{(r)}}\) be its output-by-input Jacobian at \(\boldsymbol{z}^{(r)}\). The output equation and hidden-layer recurrence (\(r=1,\ldots,L-1\)) are \[\boldsymbol{\delta}^{(L)}=\boldsymbol{J}_{f^{(L)}}^\top\nabla_{\boldsymbol{a}^{(L)}}\ell, \qquad \boldsymbol{\delta}^{(r)}=\boldsymbol{J}_{f^{(r)}}^\top (\boldsymbol{W}^{(r+1)})^\top\boldsymbol{\delta}^{(r+1)}.\] For element-wise activations, \(\boldsymbol{J}_f=\operatorname{diag}(f'(\boldsymbol{z}))\), so these expressions reduce to Hadamard products. Softmax is not element-wise: \(\boldsymbol{J}_{\rm softmax}=\operatorname{diag}(\boldsymbol{a})-\boldsymbol{a}\boldsymbol{a}^\top\). With softmax and per-example categorical cross-entropy, \(\boldsymbol{\delta}^{(L)}=\hat{\boldsymbol{y}}-\boldsymbol{y}\); the analogous sigmoid/binary-cross-entropy result is \(\delta^{(L)}=\hat y-y\).
For every layer, including the output layer, \[\nabla_{\boldsymbol{W}^{(r)}}\ell=\boldsymbol{\delta}^{(r)}(\boldsymbol{a}^{(r-1)})^\top, \qquad \nabla_{\boldsymbol{b}^{(r)}}\ell=\boldsymbol{\delta}^{(r)}.\] For a mini-batch mean loss, average these per-example parameter gradients over the batch.
Derivation Sketch. The vector chain rule gives \(\nabla_{\boldsymbol{a}^{(r)}}\ell=(\boldsymbol{W}^{(r+1)})^\top\boldsymbol{\delta}^{(r+1)}\), followed by multiplication by \(\boldsymbol{J}_{f^{(r)}}^\top\). Component-wise, \(z_j^{(r)}=\sum_k W_{jk}^{(r)}a_k^{(r-1)}+b_j^{(r)}\), so \(\partial\ell/\partial W_{jk}^{(r)}=\delta_j^{(r)}a_k^{(r-1)}\) and \(\partial\ell/\partial b_j^{(r)}=\delta_j^{(r)}\), giving the stated outer product. ◻
Backpropagation for One Example
Forward: Store \(\boldsymbol{z}^{(r)},\boldsymbol{a}^{(r)}\) for \(r=1,\ldots,L\).
Backward:
Compute \(\boldsymbol{\delta}^{(L)}\) using the output activation and loss, as above.
For \(r=L,L-1,\ldots,1\):
Compute \(\boldsymbol{G}_W^{(r)}=\boldsymbol{\delta}^{(r)}(\boldsymbol{a}^{(r-1)})^\top\) and \(\boldsymbol{G}_b^{(r)}=\boldsymbol{\delta}^{(r)}\).
If \(r>1\), compute \(\boldsymbol{\delta}^{(r-1)}=\boldsymbol{J}_{f^{(r-1)}}^\top(\boldsymbol{W}^{(r)})^\top\boldsymbol{\delta}^{(r)}\) using the forward-pass weights.
After the entire backward pass, update every layer: \(\boldsymbol{W}^{(r)}\leftarrow\boldsymbol{W}^{(r)}-\eta\boldsymbol{G}_W^{(r)}\) and \(\boldsymbol{b}^{(r)}\leftarrow\boldsymbol{b}^{(r)}-\eta\boldsymbol{G}_b^{(r)}\).
For a mini-batch, average gradients before updating parameters.
Efficiency: Reverse-mode differentiation reuses intermediate values and accumulates gradients through the computation graph. For standard differentiable operations, the backward pass costs a constant-factor multiple of the forward pass. This is a statement about graph operations, not an unconditional \(O(p)\) bound in the number of parameters: batch size, sequence length and parameter reuse also matter.
15.7 A Complete Forward Pass, Backward Pass, and Update
Example 15.6 (Nine parameters and one MSE observation). Use a two-input, two-ReLU, one-linear-output network with \[\boldsymbol{x}=\begin{bmatrix}1\\2\end{bmatrix},\quad y=1,\quad \boldsymbol{W}^{(1)}=\begin{bmatrix}1&-1\\1/2&1/2\end{bmatrix},\quad \boldsymbol{b}^{(1)}=\boldsymbol{0},\quad \boldsymbol{W}^{(2)}=\begin{bmatrix}1&-1\end{bmatrix},\quad b^{(2)}=1/2.\] Forward computation gives \(\boldsymbol{z}^{(1)}=(-1,1.5)^\top\), \(\boldsymbol{a}^{(1)}=(0,1.5)^\top\), and \(\hat y=-1\). With the Part 1 convention \(\ell=(\hat y-y)^2\), the loss is 4 and the output derivative is \(\delta^{(2)}=2(\hat y-y)=-4\). The entire backward calculation is \[\begin{align*} \nabla_{\boldsymbol{W}^{(2)}}\ell&=\begin{bmatrix}0&-6\end{bmatrix},& \nabla_{b^{(2)}}\ell&=-4,\\ \boldsymbol{\delta}^{(1)}&=\begin{bmatrix}0\\4\end{bmatrix},& \nabla_{\boldsymbol{W}^{(1)}}\ell&=\begin{bmatrix}0&0\\4&8\end{bmatrix},\qquad \nabla_{\boldsymbol{b}^{(1)}}\ell=\begin{bmatrix}0\\4\end{bmatrix}. \end{align*}\] For example, the inactive first ReLU blocks its local gradient; the active second unit receives \((-1)(-4)=4\). Every gradient uses the forward-pass parameters. With \(\eta=0.01\), update all parameters together: \[\boldsymbol{W}^{(1)}_{\rm new}=\begin{bmatrix}1&-1\\.46&.42\end{bmatrix},\quad \boldsymbol{b}^{(1)}_{\rm new}=\begin{bmatrix}0\\-.04\end{bmatrix},\quad \boldsymbol{W}^{(2)}_{\rm new}=\begin{bmatrix}1&-.94\end{bmatrix},\quad b^{(2)}_{\rm new}=.54.\] The new active hidden value is \(1.26\), prediction is \(-0.6444\), and loss is \(2.70405136\). This is a verified single gradient step, not a claim of convergence.
15.8 Batch Shapes and Averaging Exactly Once
For a batch of \(B\) row-stacked examples, let \(\boldsymbol{A}^{(r-1)}\in\mathbb{R}^{B\times d_{r-1}}\). The single-example column convention implies \[\boldsymbol{Z}^{(r)}=\boldsymbol{A}^{(r-1)}(\boldsymbol{W}^{(r)})^\top+\boldsymbol{1}_B(\boldsymbol{b}^{(r)})^\top.\] If row \(i\) of \(\boldsymbol{\Delta}^{(r)}\) contains the unaveraged derivative of its own per-example loss, then \[\nabla_{\boldsymbol{W}^{(r)}}\mathcal{L}=\frac1B(\boldsymbol{\Delta}^{(r)})^\top\boldsymbol{A}^{(r-1)},\qquad \nabla_{\boldsymbol{b}^{(r)}}\mathcal{L}=\frac1B(\boldsymbol{\Delta}^{(r)})^\top\boldsymbol{1}_B.\] Alternatively, insert \(1/B\) into the output derivatives and propagate the scaled derivatives; do not divide again. For vector regression, the loss here sums squared output-coordinate errors and averages examples, \(B^{-1}\sum_i\|\hat{\boldsymbol{y}}_i-\boldsymbol{y}_i\|^2\), rather than averaging all \(B d_L\) scalar entries. A library’s default reduction may differ by \(d_L\). A penalty \(\lambda\|\boldsymbol{W}\|_F^2\) adds \(2\lambda\boldsymbol{W}\), independent of this batch reduction once the objective has been declared. Batch normalization introduces cross-example dependence, so its training derivative additionally differentiates the batch statistics.
A central finite-difference check is \(g_j\approx[\mathcal{L}(\theta+\varepsilon\boldsymbol{e}_j)-\mathcal{L}(\theta-\varepsilon\boldsymbol{e}_j)]/(2\varepsilon)\). Check all parameter types, including biases, at points away from ReLU kinks; disable stochastic masks or hold them fixed during the comparison. The validation script checks all nine parameters above independently of the symbolic derivation.
15.9 Vanishing and Exploding Gradients
Definition 15.7 (Gradient Vanishing). In deep networks with sigmoid/tanh activations, gradients can become very small as they propagate backward, making early layers learn very slowly.
Why? \(\sigma'(z) = \sigma(z)(1-\sigma(z)) \leq 0.25\). For a network with \(L\) layers: \[\left\lVert\nabla_{\boldsymbol{a}^{(0)}}\ell\right\rVert_2 \leq \left\lVert\nabla_{\boldsymbol{a}^{(L)}}\ell\right\rVert_2 \prod_{r=1}^{L}\left\lVert\boldsymbol{W}^{(r)}\right\rVert_2\left\lVert\boldsymbol{D}^{(r)}\right\rVert_2, \quad \boldsymbol{D}^{(r)}=\operatorname{diag}(\sigma'(\boldsymbol{z}^{(r)}))\] If the products of weight and activation-Jacobian norms are consistently below 1, this bound decays with depth. Small sigmoid derivatives alone do not determine the gradient; the weights and saturation pattern also matter.
Definition 15.8 (Gradient Exploding). Products of layer Jacobians can also amplify gradients, depending on their magnitudes and alignment. The recurrence is: \[\nabla_{\boldsymbol{a}^{(r-1)}}\ell=(\boldsymbol{W}^{(r)})^\top(\boldsymbol{D}^{(r)})^\top\nabla_{\boldsymbol{a}^{(r)}}\ell\] Causes numerical instability, NaN values.
Solutions to Vanishing/Exploding Gradients:
1. Better Activation Functions:
ReLU: \(f'(z) = 1\) for \(z > 0\) (no vanishing in positive region)
Leaky ReLU, ELU: Address “dying ReLU” problem
2. Careful Weight Initialization:
Xavier/Glorot: \(\boldsymbol{W} \sim \mathcal{N}(0, 2/(d_{\text{in}} + d_{\text{out}}))\)
He initialization (for ReLU): \(\boldsymbol{W} \sim \mathcal{N}(0, 2/d_{\text{in}})\)
3. Batch Normalization: Normalize activations at each layer
4. Residual Connections (ResNet): Skip connections allow gradients to flow directly
5. Gradient Clipping: Cap gradients at a maximum value (for exploding)
6. LSTM/GRU: Specifically designed for RNNs to address vanishing gradients
15.10 Signal Scale, Initialization, and Residual Paths
Assume independent, zero-mean weights of variance \(v\) and independence from incoming activations with second moment \(q\). For a width-\(d_{\rm in}\) affine unit with zero bias, \[\mathbb{E}[z^2]=\mathrm{Var}(z)=d_{\rm in}v q.\] If the pre-activation distribution is symmetric about zero, ReLU retains half its second moment: \(\mathbb{E}[\operatorname{ReLU}(z)^2]=\mathbb{E}[z^2]/2\). Preserving this second moment suggests \(v=2/d_{\rm in}\) (He initialization). Balancing approximate forward and backward scales for near-linear symmetric activations motivates Glorot variance \(2/(d_{\rm in}+d_{\rm out})\). These approximations concern second moments under assumptions; a ReLU output has positive mean, so second moment is not the same as variance.
Example 15.9 (Distinguishing a variance from a standard deviation). For \(d_{\rm in}=100\) and \(q=1\), weights of variance \(0.01\) give pre-activation variance 1 and ReLU second moment \(0.5\). Variance \(0.02\) gives pre-activation variance 2 and ReLU second moment 1. Sampling a normal distribution for the latter uses standard deviation \(\sqrt{0.02}\), not \(0.02\). This is a scale calculation, not an assertion that trained layers remain independent or Gaussian.
For a residual block \(\boldsymbol{a}_{r+1}=\boldsymbol{a}_r+\mathcal F_r(\boldsymbol{a}_r)\) with matching shapes, its Jacobian is \(\boldsymbol{I}+\boldsymbol{J}_{\mathcal F_r}\). The identity provides a direct derivative path; the other term can still amplify or cancel it. If a post-addition ReLU is used, its Jacobian also multiplies the sum. Neither residual connections nor positive ReLU derivatives alone guarantee stable end-to-end gradients.
Global-norm clipping replaces a gradient \(\boldsymbol{g}\) by \(\min(1,c/\|\boldsymbol{g}\|_2)\boldsymbol{g}\), preserving direction when clipping is active; define the clipping factor as 1 when \(\boldsymbol{g}=0\). For \(\boldsymbol{g}=(3,4)\) and \(c=2\), the result is \((1.2,1.6)\). Apply it to the declared batch-averaged gradient before the optimizer update; it is different from independently clipping each coordinate. Clipping limits one source of exploding updates but does not repair vanishing gradients.
16 Optimization in Deep Learning
16.1 Stochastic Gradient Descent Variants
16.1.1 Momentum
Definition 16.1 (SGD with Momentum). Use step index \(s\ge1\), \(g_s=\nabla\mathcal{L}(\boldsymbol{w}_{s-1})\), and zero initial velocity. The scaled-velocity convention used here and in Part 0 is \[\boldsymbol{v}_s=\beta\boldsymbol{v}_{s-1}+\eta_{s-1}\boldsymbol{g}_s,\qquad \boldsymbol{w}_s=\boldsymbol{w}_{s-1}-\boldsymbol{v}_s.\] A common alternative stores \(\boldsymbol{u}_s=\beta\boldsymbol{u}_{s-1}+\boldsymbol{g}_s\) and updates \(\boldsymbol{w}_s=\boldsymbol{w}_{s-1}-\eta_{s-1}\boldsymbol{u}_s\). With constant \(\eta\), zero states, and \(\boldsymbol{v}_s=\eta\boldsymbol{u}_s\), they are equivalent. With a varying learning rate they generally weight past gradients differently; switching conventions or optimizer checkpoints needs care. Typical momentum coefficient: \(\beta=.9\).
Intuition 200. Momentum accelerates in directions with consistent gradients and dampens oscillations. Think of a ball rolling down a hill—it builds up speed in the downhill direction.
16.1.2 RMSProp
Definition 16.3 (RMSProp (Root Mean Square Propagation)). For \(s\ge1\), compute \(\boldsymbol{g}_s=\nabla\mathcal{L}(\boldsymbol{w}_{s-1})\) and start \(\boldsymbol{r}_0=0\). All squares, roots, and divisions below are coordinatewise: \[\boldsymbol{r}_s=\beta\boldsymbol{r}_{s-1}+(1-\beta)\boldsymbol{g}_s^2,\qquad \boldsymbol{w}_s=\boldsymbol{w}_{s-1} -\eta_{s-1}\frac{\boldsymbol{g}_s}{\sqrt{\boldsymbol{r}_s}+\epsilon}.\] Here the stabilizer is outside the square root, as in the Adam convention below; \(\sqrt{r+\epsilon}\) is a different numerical convention. Typical \(\beta=.9\), \(\epsilon=10^{-8}\).
Intuition 202. RMSProp divides the learning rate by a running average of the gradient magnitude. Parameters with large gradients get smaller effective learning rates; parameters with small gradients get larger effective rates. This helps with different scales across parameters.
16.1.3 Adam
Definition 16.5 (Adam (Adaptive Moment Estimation)). For \(s\ge1\), let \(\boldsymbol{g}_s=\nabla\mathcal{L}(\boldsymbol{w}_{s-1})\) and \(\boldsymbol{m}_0=\boldsymbol{v}_0=0\). Coordinatewise moments and updates are \[\begin{align} \boldsymbol{m}_s&=\beta_1\boldsymbol{m}_{s-1}+(1-\beta_1)\boldsymbol{g}_s,\\ \boldsymbol{v}_s&=\beta_2\boldsymbol{v}_{s-1}+(1-\beta_2)\boldsymbol{g}_s^2,\\ \hat{\boldsymbol{m}}_s&=\frac{\boldsymbol{m}_s}{1-\beta_1^s},\qquad \hat{\boldsymbol{v}}_s=\frac{\boldsymbol{v}_s}{1-\beta_2^s},\\ \boldsymbol{w}_s&=\boldsymbol{w}_{s-1}-\eta_{s-1} \frac{\hat{\boldsymbol{m}}_s}{\sqrt{\hat{\boldsymbol{v}}_s}+\epsilon}. \end{align}\] Here \(\boldsymbol{v}\) is a second-moment state, not momentum’s scaled velocity. Typical \(\beta_1=.9\), \(\beta_2=.999\), \(\eta=.001\), \(\epsilon=10^{-8}\).
Adam is a widely used optimizer for deep learning:
Combines benefits of momentum (acceleration) and RMSProp (adaptive rates)
Works well across a wide range of problems
Bias correction removes zero-initialization attenuation under the relevant moment assumptions
Still requires suitable learning rates, schedules and regularization for the task
Variants:
AdamW: Decoupled weight decay; generally different from adding an L2 loss penalty inside Adam’s adaptive update
AMSGrad: Fixes potential convergence issues in Adam
Nadam: Nesterov + Adam
16.2 Momentum, Bias Correction, and Decoupled Decay by Hand
Example 16.6 (Five momentum steps). For \(f(x)=x^2\), take \(x_0=10\), \(v_0=0\), \(\eta=0.1\), \(\beta=0.9\). At step \(s\), use \(g_s=2x_{s-1}\), \(v_s=0.9v_{s-1}+0.1g_s\), and \(x_s=x_{s-1}-v_s\):
| Step | \(v_s\) | \(x_s\) | \(f(x_s)\) |
|---|---|---|---|
| 1 | 2.0000 | 8.0000 | 64.000000 |
| 2 | 3.4000 | 4.6000 | 21.160000 |
| 3 | 3.9800 | 0.6200 | 0.384400 |
| 4 | 3.7060 | -3.0860 | 9.523396 |
| 5 | 2.7182 | -5.8042 | 33.688738 |
The iterate crosses the optimum and the loss rises on later steps. Momentum changes optimization dynamics; it does not promise monotone loss decrease or improvement for every parameter choice.
Expanding an exponential moving average initialized at zero gives \[\boldsymbol{m}_s=(1-\beta_1)\sum_{r=1}^s\beta_1^{s-r}\boldsymbol{g}_r.\] Its coefficients sum to \(1-\beta_1^s\). Dividing by this sum removes the initial attenuation; under stationary first moments it gives the correct expectation. The analogous second-moment correction divides by \(1-\beta_2^s\). It does not make nonstationary training gradients an independent stationary sample.
Example 16.7 (Two Adam steps). Use \(f(\theta)=\theta^2\), \(\theta_0=1\), \(m_0=v_0=0\), \(\beta_1=0.9\), \(\beta_2=0.999\), and \(\eta=0.1\). Set \(\epsilon=0\) only for this arithmetic example, where corrected second moments are positive. Step 1 has \(g_1=2\), \(m_1=0.2\), \(v_1=0.004\), hence \(\hat m_1=2\), \(\hat v_1=4\), and \(\theta_1=0.9\). At step 2, \[g_2=1.8,\quad m_2=0.36,\quad v_2=0.007236,\quad \hat m_2=1.894737,\quad\hat v_2=3.619810,\] so \(\theta_2=0.9-0.1\hat m_2/\sqrt{\hat v_2}=0.800412\). Practical implementations retain a positive numerical stabilizer. This fixes the step indexing explicitly: \(g_s\) is computed at \(\theta_{s-1}\).
Example 16.8 (Why AdamW is not an L2 penalty inside Adam). Let the loss gradient be \(\boldsymbol{g}=(1,2)\) at \(\boldsymbol{w}=(2,-1)\), with \(\eta=0.1\) and decay coefficient \(d=0.2\). Adding loss penalty \((d/2)\|\boldsymbol{w}\|^2\) changes the gradient to \((1.4,1.8)\). In the first bias-corrected Adam step with zero moments and \(\epsilon=0\), component normalization gives a step \((0.1,0.1)\), so the coupled update is \((1.9,-1.1)\).
A decoupled step instead applies \((1-\eta d)\boldsymbol{w}-\eta\,\hat{\boldsymbol{m}}/\sqrt{\hat{\boldsymbol{v}}}\) using moments of \(\boldsymbol{g}\) only, yielding \((1.86,-1.08)\). The updates differ. In Part 1’s \(\lambda\|\boldsymbol{w}\|^2\) notation, this penalty has \(\lambda=d/2\); the factor of two must not be dropped. Plain SGD without momentum or adaptive normalization gives the same coupled and decoupled update for the matched coefficient, but Adam generally does not.
See the Adam paper and decoupled weight-decay paper. Optimizer state, loss reduction, learning-rate schedule, and decay convention jointly specify an update.
16.3 Learning Rate Schedules
Definition 16.9 (Learning Rate Decay Strategies). 1. Step Decay: \[\eta_t = \eta_0 \cdot \gamma^{\lfloor t / k \rfloor}\] Drop learning rate by factor \(\gamma\) every \(k\) epochs.
2. Exponential Decay: \[\eta_t = \eta_0 e^{-\lambda t}\]
3. Cosine Annealing: \[\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\left(\frac{t}{T}\pi\right)\right)\] Smoothly decreases from \(\eta_{\max}\) to \(\eta_{\min}\) over \(T\) steps.
4. Warm-up + Decay:
Linearly increase LR from 0 to \(\eta_0\) over first few epochs (warm-up)
Then apply decay schedule
Used in Transformers.
16.4 Batch Normalization
Definition 16.10 (Batch Normalization). For a mini-batch \(\mathcal{B} = \{\boldsymbol{x}_1, \ldots, \boldsymbol{x}_m\}\), normalize each feature: \[\begin{align} \mu_{\mathcal{B}} &= \frac{1}{m}\sum_{i=1}^m x_i \\ \sigma_{\mathcal{B}}^2 &= \frac{1}{m}\sum_{i=1}^m (x_i - \mu_{\mathcal{B}})^2 \\ \hat{x}_i &= \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^2 + \epsilon}} \\ y_i &= \gamma \hat{x}_i + \beta \end{align}\] where \(\gamma\) and \(\beta\) are learnable parameters (scale and shift).
Benefits of Batch Normalization:
Faster training: Can use higher learning rates
Optimization effect: Can improve training stability. Reducing internal covariate shift was the original motivation, not a complete established explanation of its success
Regularization effect: Adds noise (batch statistics), reduces overfitting
Less sensitive to initialization: Makes training more robust
Where to apply: After linear transformation, before activation: \[\boldsymbol{z} = \boldsymbol{W}\boldsymbol{a}^{(\ell-1)} + \boldsymbol{b} \to \text{BatchNorm}(\boldsymbol{z}) \to f(\cdot)\]
At test time: In the usual inference mode, use running statistics collected during training rather than recomputing them from the test batch.
16.4.1 Training Statistics, Evaluation Statistics, and Derivatives
Example 16.11 (The same input under two different modes). For a scalar training batch \((1,3)\), mean is 2 and population-form variance is 1. Ignore \(\epsilon\) for this nonconstant arithmetic example and set learned scale \(\gamma=2\) and shift \(\beta=-1\). Normalized values are \((-1,1)\) and outputs are \((-3,1)\). Suppose the frozen running statistics at evaluation are also mean 2 and variance 1. A new input 5 then gives \(2(5-2)-1=5\).
If evaluation incorrectly recomputes statistics from the single input 5, its normalized value is zero (using positive \(\epsilon\)) and its output becomes \(-1\). The predictor has changed because it has consumed evaluation-batch statistics. Set evaluation mode and freeze the training buffers under the ordinary inductive protocol. Explicit test-time adaptation is a different procedure that requires its own evaluation design.
During training, the mean and variance depend on every batch input. For one feature over a batch of size \(m\), let \(g_i=\partial\mathcal{L}/\partial y_i\) already include the declared loss reduction. Differentiating through the batch statistics gives \[\frac{\partial\mathcal{L}}{\partial x_i} =\frac{\gamma}{m\sqrt{\sigma_{\mathcal B}^2+\epsilon}} \left[m g_i-\sum_j g_j-\hat x_i\sum_j g_j\hat x_j\right], \quad \frac{\partial\mathcal{L}}{\partial\gamma}=\sum_i g_i\hat x_i, \quad \frac{\partial\mathcal{L}}{\partial\beta}=\sum_i g_i.\] Do not apply another batch averaging factor when \(g_i\) already contains it. A batch-normalized training unit is not an independent scalar transform per example. The original BN paper describes the batch-dependent transformation and inference statistics.
Layer normalization uses a different axis: it normalizes a single example’s feature coordinates (typically one token’s hidden dimension) rather than mixing different examples. It usually uses current per-example statistics during both training and evaluation, not BN’s running batch statistics. Parameter shapes and normalization axes must be specified; the two operations are not interchangeable.
16.5 Dropout
Definition 16.12 (Dropout). During training, randomly set activations to zero with probability \(0\le p<1\) (often 0.5): \[\tilde{a}_i = \begin{cases} 0 & \text{with probability } p \\ a_i / (1-p) & \text{with probability } 1-p \end{cases}\] At test time, use all neurons (no dropout).
Intuition 211. Dropout prevents co-adaptation of neurons. By randomly dropping neurons, the network cannot rely on any specific neurons, forcing it to learn robust features. It’s like training an ensemble of networks that share weights.
Dropout as Regularization:
Prevents overfitting, especially in fully-connected layers
Typical \(p\): 0.2-0.5 for hidden layers, 0-0.2 for input layer
Convolutional variants may drop activations or feature maps; placement and rates are architecture-dependent
Certain specified dropout objectives admit variational Bayesian interpretations; a dropout mask alone does not define a calibrated posterior
Variants:
DropConnect: Drop weights instead of activations
Spatial Dropout: For CNNs, drop entire feature maps
16.5.1 What Inverted Dropout Preserves
Let \(M\sim\operatorname{Bernoulli}(1-p)\) independently of a fixed activation \(a\), and \(\tilde a=Ma/(1-p)\). Direct calculation gives \[\mathbb{E}[\tilde a\mid a]=a,\qquad \mathrm{Var}(\tilde a\mid a)=\frac{p}{1-p}a^2.\] Thus inverted dropout preserves an activation’s conditional mean, while adding multiplicative noise whose size depends on that activation. Evaluation disables the mask and uses \(a\) itself.
Example 16.14 (Enumerating every dropout mask). For activations \((2,-1)\) and dropout probability \(p=1/2\), the four equally likely independent masks give outputs \[(0,0),\quad(0,-2),\quad(4,0),\quad(4,-2).\] Their mean is \((2,-1)\) and coordinate variances are \((4,1)\). Mean preservation before a nonlinearity does not imply mean preservation after it: for scalar activation 2, \(\mathbb{E}[\sigma(\tilde a)]=[\sigma(0)+\sigma(4)]/2=0.741007\), whereas \(\sigma(\mathbb{E}[\tilde a])=\sigma(2)=0.880797\). A dropout-disabled network is therefore not generally the exact arithmetic average of all masked nonlinear networks.
Train/evaluation mode is part of the predictor definition. During validation, disable ordinary dropout and freeze BN running updates. Checkpoint selection, early stopping, architecture choice, and any fitted calibration use validation data as in Part 0; test losses do not select an epoch. If batches are shuffled, fit preprocessing only on the training split before constructing training batches. Sequence/group splits precede window construction where overlapping windows could otherwise cross the evaluation boundary.
17 Deep Architectures
17.1 Convolutional Neural Networks (CNNs)
17.1.1 Motivation for CNNs
Problem with fully-connected networks for images:
A \(32\times32\) image with three channels has 3072 scalar input values. Hidden layer with 1000 neurons \(\to\) 3M parameters just in first layer!
No spatial structure: treats pixels far apart the same as nearby pixels
Not translation invariant: must learn same feature at every location
CNNs exploit:
Local connectivity: Neurons connect to small spatial regions
Weight sharing: Same filter applied across entire image
Translation equivariance: A shared stride-1 filter is equivariant on an infinite grid or away from boundaries; finite padding and subsampling can break exact equivariance
17.1.2 Convolutional Layer
Definition 17.1 (Convolution Operation). For input \(\boldsymbol{X} \in \mathbb{R}^{H \times W \times C}\) and filter \(\boldsymbol{K} \in \mathbb{R}^{F \times F \times C}\): \[Y[i,j]=\sum_{u=0}^{F-1}\sum_{v=0}^{F-1}\sum_{c=1}^C X_{\rm pad}[iS+u,jS+v,c]K[u,v,c]+b\] Here \(X_{\rm pad}\) is the input padded with \(P\) zeros on each spatial side, \(S\) is the stride, and spatial output indices begin at zero. This is cross-correlation, conventionally called convolution in neural-network libraries. Apply it at every valid output position.
With \(D\) filters, output has shape \((H', W', D)\) where: \[H'=\left\lfloor\frac{H-F+2P}{S}\right\rfloor+1,\quad W'=\left\lfloor\frac{W-F+2P}{S}\right\rfloor+1\] \(P\) = padding, \(S\) = stride.
Key Concepts:
1. Receptive Field: Region of input that affects one output neuron. Deeper layers have larger receptive fields.
2. Padding:
Valid (no padding): Output size decreases
Same spatial size at stride 1: Total padding per axis is \(F-1\). Symmetric padding \(P=(F-1)/2\) is integral for odd \(F\); even filters require asymmetric padding to preserve size
3. Stride: Step size. Larger stride \(\to\) smaller output, reduces computation.
4. Number of Parameters: For filter \(F \times F \times C\) with \(D\) filters: \[\text{params} = (F \times F \times C + 1) \times D\] Much smaller than fully-connected layer!
17.1.3 An Exact Convolution and Its Backward Accumulation
Example 17.2 (A \(4\times4\) input and a \(2\times2\) filter). Use one channel, stride 1, no padding, bias zero, and \[\boldsymbol{X}=\begin{bmatrix}1&2&3&4\\5&6&7&8\\9&10&11&12\\13&14&15&16\end{bmatrix},\qquad \boldsymbol{K}=\begin{bmatrix}1&0\\-1&1\end{bmatrix}.\] The first output is \(1(1)+2(0)+5(-1)+6(1)=2\). Applying the same filter everywhere gives \[\boldsymbol{Y}=\begin{bmatrix}2&3&4\\6&7&8\\10&11&12\end{bmatrix}.\] This is cross-correlation as declared above: do not flip the kernel in the forward operation. For one observation with a nine-coordinate regression target of zero, the notes’ MSE convention gives \(\ell=\|\boldsymbol{Y}\|_F^2=543\), summing its output coordinates. Thus the upstream derivative is \(G_{ij}=\partial\ell/\partial Y_{ij}=2Y_{ij}\).
Weight sharing requires summing contributions from every spatial use: \[\frac{\partial\ell}{\partial K_{uv}}=\sum_{i,j}G_{ij}X_{i+u,j+v},\qquad \frac{\partial\ell}{\partial X_{ab}}=\sum_{\substack{i,j:\,0\le a-i,b-j<2}}G_{ij}K_{a-i,b-j}.\] The input formula accumulates all overlapping receptive fields. For example, \(\partial\ell/\partial K_{00}=960\), while the interior input \(X_{11}\) receives \(2(2-3+7)=12\). The bias gradient is \(\sum_{i,j}G_{ij}\). A library that instead averages these nine output-coordinate errors would report loss \(543/9=60.333333\) and divide each gradient by 9. This is a loss-reduction choice, not an architectural difference.
Example 17.3 (Output shape, parameters, and receptive field). For input \(32\times32\times3\), 64 filters of spatial size \(5\times5\), stride 1, and symmetric padding 2, the output is \(32\times32\times64\). The number of learned parameters is \((5\cdot5\cdot3+1)64=4864\), including one bias per filter. Parameter count does not multiply by the number of output positions.
For a chain of layers without dilation, define input jump \(j_0=1\) and receptive-field width \(r_0=1\). A layer with kernel width \(k_s\) and stride \(s_s\) gives \(j_s=s_sj_{s-1}\) and \(r_s=r_{s-1}+(k_s-1)j_{s-1}\). A \(3\)-wide stride-1 convolution, \(2\)-wide stride-2 pool, and another \(3\)-wide stride-1 convolution have \((r,j)=(3,1),(4,2),(8,2)\). The final unit depends on eight input positions along each axis, with adjacent outputs two input positions apart. Padding introduces boundary conventions; it does not create new observed information.
For max pooling, backpropagation routes an upstream derivative to a selected maximizing input; ties require a convention. Average pooling distributes it equally over the contributing entries. These are different Jacobians despite the same output shape.
17.1.4 Pooling Layers
Definition 17.4 (Pooling). Downsampling operation to reduce spatial dimensions:
Max Pooling: Take maximum in each region \[Y[i,j] = \max_{di,dj} X[i \cdot S + di, j \cdot S + dj]\]
Average Pooling: Take average \[Y[i,j] = \frac{1}{F^2}\sum_{di,dj} X[i \cdot S + di, j \cdot S + dj]\]
Common: \(2 \times 2\) pooling with stride 2 (halves dimensions).
Benefits of pooling:
Reduces computation and memory
Can provide limited robustness to small translations; general translation invariance is not guaranteed
Increases receptive field
17.1.5 Common CNN Architectures
Example 17.5 (LeNet-5 (1998) - Digit Recognition).
Input\((32\times32)\)\(\to\)Conv(6,\(5\times5\))\(\to\)Pool(\(2\times2\))
\(\to\)Conv(16,\(5\times5\))\(\to\)Pool(\(2\times2\))
\(\to\)FC(120)\(\to\)FC(84)\(\to\)FC(10)
An influential early CNN for digit recognition, illustrating local filters and parameter sharing.
Example 17.6 (AlexNet (2012) - ImageNet Winner).
8 layers (5 conv, 3 FC)
ReLU activations in a historically influential large-scale CNN
Dropout for regularization
Data augmentation
About 60M parameters in the described architecture. The ILSVRC-2012 winning ensemble had top-5 test error 15.3%, versus 26.2% for the second-best entry; these are competition-entry results, not a single-network ablation
See Table 2 of the original AlexNet paper for the different single-network, validation, and ensemble test results.
Example 17.7 (VGGNet (2014)).
Very deep (16-19 layers)
Only \(3 \times 3\) convolutions (smaller filters, stacked)
Showed depth is crucial
138M parameters (VGG-16)
Example 17.8 (ResNet (2015) - 152 Layers). Key innovation: Residual Connections
Instead of learning \(\mathcal{H}(\boldsymbol{x})\), learn residual \(\mathcal{F}(\boldsymbol{x})\) where: \[\mathcal{H}(\boldsymbol{x}) = \mathcal{F}(\boldsymbol{x}) + \boldsymbol{x}\] Skip connections allow gradients to flow directly, enabling very deep networks.
The original ResNet paper reports 3.57% top-5 test error for an ensemble in the ILSVRC-2015 classification task. This is not a single-152-layer-network result or a general comparison with human visual ability.
17.2 Recurrent Neural Networks (RNNs)
17.2.1 Sequence Modeling
Motivation: Many problems involve sequences:
Text: “The cat sat on the ___” (predict next word)
Time series: Stock prices, weather data
Speech: Audio to text
Video: Frame-by-frame analysis
Challenge: Variable-length inputs and dependencies between timesteps.
17.2.2 Vanilla RNN
Definition 17.9 (Recurrent Neural Network). At timestep \(t\): \[\begin{align} \boldsymbol{h}_t &= f(\boldsymbol{W}_{hh}\boldsymbol{h}_{t-1} + \boldsymbol{W}_{xh}\boldsymbol{x}_t + \boldsymbol{b}_h) \\ \hat{\boldsymbol{y}}_t &= \boldsymbol{W}_{hy}\boldsymbol{h}_t + \boldsymbol{b}_y \end{align}\] where:
\(\boldsymbol{x}_t\): input at time \(t\)
\(\boldsymbol{h}_t\): hidden state (memory)
\(\hat{\boldsymbol{y}}_t\): predicted linear output at time \(t\); a classification head applies the declared output link
\(f\): activation (typically tanh or ReLU)
17.2.3 Backpropagation Through Time (BPTT)
Training RNNs: Unfold network through time and apply backpropagation. Gradients flow backward through all timesteps.
Repeated-state Jacobians: Long recurrent paths can contract or amplify derivatives: \[\frac{\partial\boldsymbol{h}_T}{\partial\boldsymbol{h}_1} =(\boldsymbol{D}_T\boldsymbol{W}_{hh})(\boldsymbol{D}_{T-1}\boldsymbol{W}_{hh})\cdots(\boldsymbol{D}_2\boldsymbol{W}_{hh}), \quad\boldsymbol{D}_t=\operatorname{diag}(f'(\boldsymbol{z}_t))\] For long sequences, this ordered Jacobian product can shrink or grow rapidly. A scalar-loss gradient uses its transpose; losses at multiple timesteps contribute a sum of such paths.
17.2.5 LSTM (Long Short-Term Memory)
Definition 17.11 (LSTM Cell). LSTM uses gates to control information flow:
Forget gate: What to forget from cell state \[\boldsymbol{f}_t = \sigma(\boldsymbol{W}_f[\boldsymbol{h}_{t-1}, \boldsymbol{x}_t] + \boldsymbol{b}_f)\]
Input gate: What new information to add \[\boldsymbol{i}_t = \sigma(\boldsymbol{W}_i[\boldsymbol{h}_{t-1}, \boldsymbol{x}_t] + \boldsymbol{b}_i)\] \[\tilde{\boldsymbol{c}}_t = \tanh(\boldsymbol{W}_c[\boldsymbol{h}_{t-1}, \boldsymbol{x}_t] + \boldsymbol{b}_c)\]
Cell state update: \[\boldsymbol{c}_t = \boldsymbol{f}_t \odot \boldsymbol{c}_{t-1} + \boldsymbol{i}_t \odot \tilde{\boldsymbol{c}}_t\]
Output gate: What to output \[\boldsymbol{o}_t = \sigma(\boldsymbol{W}_o[\boldsymbol{h}_{t-1}, \boldsymbol{x}_t] + \boldsymbol{b}_o)\] \[\boldsymbol{h}_t = \boldsymbol{o}_t \odot \tanh(\boldsymbol{c}_t)\]
Why LSTM works:
Cell state \(\boldsymbol{c}_t\) acts as a “conveyor belt” for information
Gates (sigmoid \(\in [0,1]\)) control what flows through
Forget gate can preserve gradients over long sequences
Addresses vanishing gradient problem
When to use LSTM:
Long sequences (>50-100 timesteps)
Long-term dependencies matter
Text generation, machine translation, speech recognition
17.2.6 GRU (Gated Recurrent Unit)
Definition 17.12 (GRU). Simplified version of LSTM with fewer parameters:
Update gate: \[\boldsymbol{z}_t = \sigma(\boldsymbol{W}_z[\boldsymbol{h}_{t-1}, \boldsymbol{x}_t])\]
Reset gate: \[\boldsymbol{r}_t = \sigma(\boldsymbol{W}_r[\boldsymbol{h}_{t-1}, \boldsymbol{x}_t])\]
Candidate hidden state: \[\tilde{\boldsymbol{h}}_t = \tanh(\boldsymbol{W}[\boldsymbol{r}_t \odot \boldsymbol{h}_{t-1}, \boldsymbol{x}_t])\]
Hidden state update: \[\boldsymbol{h}_t = (1 - \boldsymbol{z}_t) \odot \boldsymbol{h}_{t-1} + \boldsymbol{z}_t \odot \tilde{\boldsymbol{h}}_t\]
GRU vs LSTM:
GRU: Simpler, fewer parameters, faster training
LSTM: Separate cell and hidden states provide an additional gated path; relative predictive performance requires task-specific evaluation
Performance often similar—try both!
17.2.7 Computing Gates and Interpreting Their Derivative Paths
Example 17.13 (One scalar LSTM step). Let \(c_{t-1}=2\), forget gate \(f_t=0.8\), input gate \(i_t=0.25\), candidate \(\tilde c_t=-0.4\), and output gate \(o_t=0.6\). Then \[c_t=0.8(2)+0.25(-0.4)=1.5,\qquad h_t=0.6\tanh(1.5)=0.543089.\] Holding the gates and candidate fixed, the direct cell-state derivative is \(\partial c_t/\partial c_{t-1}=0.8\). In the full recurrent graph, gates can depend on previous hidden states, creating additional derivative paths; the total derivative is not generally just the forget gate. Along the direct path, 20 constant forget factors of \(0.9\) give \(0.9^{20}=0.121577\), whereas factors of \(0.99\) give \(0.817907\). Gates can help retain information but do not guarantee preservation of every long-range gradient.
Example 17.14 (The stated GRU convention). In the equations above, \(z_t\) weights the new candidate. Set \(h_{t-1}=1\), \(z_t=1/4\), \(r_t=1/2\), and candidate pre-activation \(r_th_{t-1}=1/2\) (zero input contribution). Then \(\tilde h_t=\tanh(1/2)=0.462117\) and \(h_t=3/4+(1/4)\tilde h_t=0.865529\). Some implementations define the update gate as the retained-old-state weight or place reset multiplication after a recurrent affine map. Check that convention, bias terms, and parameter shapes before translating formulas or checkpoints.
17.3 Transformers and Attention
17.3.1 Limitations of RNNs
Sequential state updates: Hidden states depend on earlier states, even when input projections and batching can be parallelized
Long-range dependencies: Still struggle despite LSTM/GRU
Fixed hidden state: Must compress entire history into \(\boldsymbol{h}_t\)
Solution: Attention mechanism—directly access any part of the input.
17.3.2 Attention Mechanism
Definition 17.15 (Attention). Given query \(\boldsymbol{q}\in\mathbb{R}^{d_k}\), keys \(\boldsymbol{k}_i\in\mathbb{R}^{d_k}\) and values \(\boldsymbol{v}_i\in\mathbb{R}^{d_v}\), stack keys and values as rows: \(\boldsymbol{K}=[\boldsymbol{k}_1^\top;\ldots;\boldsymbol{k}_n^\top]\) and \(\boldsymbol{V}=[\boldsymbol{v}_1^\top;\ldots;\boldsymbol{v}_n^\top]\).
1. Compute attention scores: \[e_i = \text{score}(\boldsymbol{q}, \boldsymbol{k}_i)\] Common: \(\text{score}(\boldsymbol{q}, \boldsymbol{k}) = \boldsymbol{q}^\top\boldsymbol{k}\) (dot product)
2. Normalize to get attention weights: \[\alpha_i = \frac{\exp(e_i)}{\sum_j \exp(e_j)} \quad \text{(softmax)}\]
3. Compute weighted sum: \[\text{context} = \sum_{i=1}^n \alpha_i \boldsymbol{v}_i\]
Intuition 228. Attention allows the model to “focus” on relevant parts of the input. For translation, when generating word \(t\), attention looks at all source words and focuses on the most relevant ones.
17.3.3 Scaled Dot-Product Attention
Definition 17.17 (Scaled Dot-Product Attention). \[\text{Attention}(\boldsymbol{Q}, \boldsymbol{K}, \boldsymbol{V}) = \text{softmax}\left(\frac{\boldsymbol{Q}\boldsymbol{K}^\top}{\sqrt{d_k}}\right)\boldsymbol{V}\] where \(\boldsymbol{Q} \in \mathbb{R}^{n \times d_k}\), \(\boldsymbol{K} \in \mathbb{R}^{m \times d_k}\), \(\boldsymbol{V} \in \mathbb{R}^{m \times d_v}\).
Softmax is applied row-wise over the \(m\) keys. Under the usual approximately independent, unit-variance component model, a query-key dot product has variance \(d_k\); scaling by \(\sqrt{d_k}\) controls its scale. It reduces a source of saturation rather than guaranteeing saturation never occurs.
17.3.4 Transformer Architecture
Definition 17.18 (Transformer (Vaswani et al., 2017)). Uses attention for token mixing, together with positionwise feed-forward layers, normalization, and residual paths (no recurrent state in the original architecture):
Key components:
Multi-Head Attention: Multiple attention operations in parallel \[\text{MultiHead}(\boldsymbol{Q}, \boldsymbol{K}, \boldsymbol{V}) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)\boldsymbol{W}^O\] where \(\text{head}_i = \text{Attention}(\boldsymbol{Q}\boldsymbol{W}_i^Q, \boldsymbol{K}\boldsymbol{W}_i^K, \boldsymbol{V}\boldsymbol{W}_i^V)\)
Positional Encoding: Add position information (since no recurrence) \[PE_{(pos, 2i)} = \sin(pos/10000^{2i/d_{\rm model}}),\quad PE_{(pos, 2i+1)} = \cos(pos/10000^{2i/d_{\rm model}})\]
Here \(d_{\rm model}\) is the (even, in this paired form) token width and \(i=0,\ldots,d_{\rm model}/2-1\).
Feed-Forward Networks: Applied position-wise \[\text{FFN}(\boldsymbol{x}) = \boldsymbol{W}_2\max(0,\boldsymbol{W}_1\boldsymbol{x}+\boldsymbol{b}_1)+\boldsymbol{b}_2\]
Layer Normalization and Residual Connections
Why Transformers Revolutionized NLP:
Parallel training: Positions can be processed together with appropriate masks; autoregressive generation still depends on previously generated tokens
Long-range dependencies: Direct connections between any positions
Scalability: Can train on massive datasets efficiently
Transfer learning: Pre-train on large corpus, fine-tune on task
Impact:
BERT (2018): Bidirectional Transformer for language understanding
GPT series (2018-2023): Decoder-only Transformers for generation
Vision Transformers (ViT): Applied to images
Now the dominant architecture in NLP and increasingly in vision
17.3.5 An Entire Attention Matrix with and without a Causal Mask
Example 17.19 (Three tokens, explicit scores, weights, and outputs). Use row-stacked keys, queries, and values as in the preceding attention definition: \[\boldsymbol{Q}=\boldsymbol{K}=\begin{bmatrix}1&0\\0&1\\1&1\end{bmatrix},\qquad \boldsymbol{V}=\begin{bmatrix}1&0\\0&2\\1&1\end{bmatrix},\qquad d_k=2.\] The scaled score matrix is \[\boldsymbol{S}=\frac1{\sqrt2}\begin{bmatrix}1&0&1\\0&1&1\\1&1&2\end{bmatrix}.\] For a causal decoder, add a mask \(M_{ij}=0\) for \(j\le i\) and \(-\infty\) otherwise before row softmax. The resulting attention weights and output are \[\boldsymbol{A}=\begin{bmatrix}1&0&0\\.330238&.669762&0\\.248255&.248255&.503490\end{bmatrix},\qquad \boldsymbol{A}\boldsymbol{V}=\begin{bmatrix}1&0\\.330238&1.339523\\.751745&1\end{bmatrix}.\] Each row sums to one. Without the mask, the first attention row is \[\boldsymbol{A}_{1,:}^{\rm unmasked}=(0.401112,0.197776,0.401112),\] and reads the third value, which is in its future. With the causal mask, changing \(\boldsymbol{v}_3\) cannot change output rows 1 or 2 in this operation. Multiplying a probability matrix by a zero/one mask after softmax without renormalizing does not implement this operation. A row with every key masked has no valid softmax denominator and needs an explicit handling convention.
17.3.6 Positions, Targets, and the Evaluation Boundary
Multi-head self-attention starts from row-stacked token features \(\boldsymbol{X}\in\mathbb{R}^{n\times d_{\rm model}}\). Each head uses \(\boldsymbol{Q}_h=\boldsymbol{X}\boldsymbol{W}_h^Q\), \(\boldsymbol{K}_h=\boldsymbol{X}\boldsymbol{W}_h^K\), and \(\boldsymbol{V}_h=\boldsymbol{X}\boldsymbol{W}_h^V\), with \[\boldsymbol{W}_h^Q,\boldsymbol{W}_h^K\in\mathbb{R}^{d_{\rm model}\times d_k},\qquad \boldsymbol{W}_h^V\in\mathbb{R}^{d_{\rm model}\times d_v}.\] Its output has shape \(n\times d_v\); concatenating \(h\) heads gives \(n\times(hd_v)\), followed by \(\boldsymbol{W}^O\in\mathbb{R}^{hd_v\times d_{\rm model}}\). These are right-multiplying row-projection matrices. Their transposes play the role of column-affine weight matrices in the MLP convention; mixing these orientations is a shape error.
Without positions or an order-dependent mask, self-attention is permutation equivariant: for permutation matrix \(\boldsymbol{P}\), replacing \((\boldsymbol{Q},\boldsymbol{K},\boldsymbol{V})\) by \((\boldsymbol{P}\boldsymbol{Q},\boldsymbol{P}\boldsymbol{K},\boldsymbol{P}\boldsymbol{V})\) gives \(\boldsymbol{P}\boldsymbol{A}\boldsymbol{V}\). The attention operation alone cannot distinguish two different orderings except by permuting its output. Position encodings and masks supply ordering information.
A teacher-forced next-token training example has \[\text{inputs }(\mathrm{BOS},u_1,u_2),\qquad\text{targets }(u_1,u_2,u_3),\] with a lower-triangular self-attention mask. Position \(i\) may read its own input token, which is the previous target token, but cannot read the target \(u_i\) from a later input position. A bidirectional encoder instead allows both directions when the task permits them. Choose masks by information availability, not by a blanket rule that every transformer must be causal.
For self-attention on \(n\) tokens with model width \(d\), dense score/value work costs \(O(n^2d)\), projection and positionwise feed-forward work typically cost \(O(nd^2)\), and explicitly materializing the attention matrix uses \(O(n^2)\) entries per head. These are dense-operation costs, not a universal wall-clock ranking against RNNs. Autoregressive generation still depends on previous generated tokens. Validation also freezes training-only preprocessing and model state; masking future tokens does not prevent leakage from a globally fitted vocabulary, future-derived feature, or an incorrectly split sequence dataset.
The original Transformer paper specifies scaled attention, masking, multi-head projections, position encoding, and residual/normalization structure. The column-vector feed-forward convention here remains \(\boldsymbol{W}_2\operatorname{ReLU}(\boldsymbol{W}_1\boldsymbol{x}+\boldsymbol{b}_1)+\boldsymbol{b}_2\); a row-stacked batch transposes the weight matrices as in Section 15.7.
17.4 Summary of Part 4
Perceptron: An early trainable linear classifier with a mistake bound for separable augmented data. One affine unit cannot represent XOR.
MLPs: Stack layers with non-linear activations. Universal approximators. Trained via backpropagation—efficient gradient computation using chain rule.
Activation Functions: ReLU is default for hidden layers (addresses vanishing gradients). Sigmoid/Softmax for output. GELU in modern architectures.
Optimization: Adam is widely used but requires tuning. Learning-rate schedules can help; batch normalization changes optimization and has regularizing effects, while dropout explicitly randomizes activations during training.
CNNs: Exploit spatial structure via convolution and pooling. Weight sharing reduces parameters. ResNet’s skip connections enable very deep networks.
RNNs: Process sequences with recurrent connections. Vanilla RNNs suffer from vanishing gradients. LSTM/GRU use gates to maintain long-term memory.
Transformers: Attention connects permitted input positions directly. Training can parallelize positions with suitable masks; autoregressive decoding still has sequential token dependencies.
Next Steps: Part 5 explores unsupervised learning: clustering, dimensionality reduction, and methods for discovering structure without labels.
Exercise 17.20.
Prove that a single-layer perceptron cannot learn the XOR function. Show that a two-layer network with 2 hidden neurons can learn it.
Derive the backpropagation equations for a 3-layer network with sigmoid activations and MSE loss.
For a conv layer with input \(32 \times 32 \times 3\), filter size \(5 \times 5\), 64 filters, stride 1, padding 2: compute output dimensions and number of parameters.
Explain why ReLU helps with vanishing gradients compared to sigmoid. What is the “dying ReLU” problem?
Implement gradient descent with momentum by hand for \(f(x) = x^2\), starting from \(x_0 = 10\), with \(\eta = 0.1\), \(\beta = 0.9\). Show 5 iterations.
In an LSTM, what happens if the forget gate outputs all 1s? All 0s?
For scaled dot-product attention with \(d_k = 64\), why do we divide by \(\sqrt{64} = 8\)? What happens without scaling?
Compare computational complexity: training a 10-layer RNN vs a 10-layer Transformer on a sequence of length 100. Which is faster and why?
Part 5: Unsupervised Learning
18 Introduction to Unsupervised Learning
Definition 18.1 (Unsupervised Learning). In unsupervised learning, we have only input data \(\mathcal{D} = \{\boldsymbol{x}_1, \boldsymbol{x}_2, \ldots, \boldsymbol{x}_n\}\) without labels. The goal is to discover hidden structure or patterns in the data.
Main Tasks in Unsupervised Learning:
Clustering: Group similar examples together
Dimensionality Reduction: Find lower-dimensional representations
Density Estimation: Model the probability distribution \(P(\boldsymbol{x})\)
Anomaly Detection: Identify unusual or outlier examples
Association Rules: Discover relationships between variables
Why Unsupervised Learning?
Labeled data is expensive; unlabeled data is abundant
Discover hidden structures humans might miss
Preprocessing for supervised learning (feature extraction)
Understand data distribution and relationships
18.1 Descriptive Structure versus Prediction on New Observations
“Unsupervised” means that a fitting objective does not use target labels; it does not mean that a transformation is fixed independently of its inputs. Means, principal directions, cluster centers, neighbor graphs, reconstruction models, and anomaly thresholds are all learned from data.
For descriptive analysis of one stated dataset, fitting an embedding or clustering on all of that dataset is a coherent analysis of those observations. For inductive prediction on future observations, first split the data using the units and time boundaries in Section 1.3, then fit every transformation on training data only. If test inputs participate in fitting, describe the procedure as transductive rather than reporting it as an ordinary unseen-input evaluation. Repeatedly choosing an embedding, cluster count, or anomaly threshold by inspecting final test labels also spends the test set.
An executable PCA pipeline with fold-local fitting
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
procedure = Pipeline([
("scale", StandardScaler()),
("reduce", PCA(svd_solver="full")),
("model", LogisticRegression(max_iter=1000))
])
folds = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
search = GridSearchCV(
procedure, {"reduce__n_components": [1, 2, 3],
"model__C": [0.1, 1.0]},
cv=folds, scoring="accuracy", refit=True
)
search.fit(X_train, y_train)
# Every CV fit learns both scaler and PCA on its training fold.
# The selected entire procedure is then refitted on X_train.
final_test_accuracy = search.score(X_test, y_test)
print(final_test_accuracy) # final evaluation after choices are frozenHere PCA is unsupervised but its dimension is selected for a supervised task; the complete procedure is evaluated. There are 18 candidate/fold fits and one refit. As in Part 6, the final test score must not be used to revise the grid. Grouped or temporal data require matching splitters instead of this independent-row demonstration.
19 Clustering
19.1 K-Means Clustering
19.1.1 Problem Formulation
Definition 19.1 (K-Means Objective). Given data \(\{\boldsymbol{x}_i\}_{i=1}^n\) and desired number of clusters \(K\), find:
Cluster centers (centroids) \(\{\boldsymbol{\mu}_k\}_{k=1}^K\)
Cluster assignments \(\{c_i\}_{i=1}^n\) where \(c_i \in \{1, \ldots, K\}\)
to minimize within-cluster sum of squares: \[J = \sum_{i=1}^n \left\lVert\boldsymbol{x}_i - \boldsymbol{\mu}_{c_i}\right\rVert_2^2 = \sum_{k=1}^K \sum_{i: c_i=k} \left\lVert\boldsymbol{x}_i - \boldsymbol{\mu}_k\right\rVert_2^2\]
Intuition 235. K-means finds \(K\) cluster centers and assigns each point to its nearest center. The objective minimizes the total squared Euclidean distance from points to their assigned centers—we want tight, compact clusters.
19.1.2 Lloyd’s Algorithm
K-Means Algorithm (Lloyd’s Algorithm)
Input: Data \(\{\boldsymbol{x}_i\}_{i=1}^n\), number of clusters \(K\), max iterations \(T\)
Initialize: Randomly select \(K\) points as initial centroids \(\{\boldsymbol{\mu}_k\}_{k=1}^K\)
Repeat until convergence (or \(T\) iterations):
Assignment step: Assign each point to nearest centroid \[c_i = \mathop{\mathrm{arg\,min}}_{k \in \{1,\ldots,K\}} \left\lVert\boldsymbol{x}_i - \boldsymbol{\mu}_k\right\rVert_2^2\]
Update step: Recompute centroids as mean of assigned points \[\boldsymbol{\mu}_k = \frac{1}{|C_k|}\sum_{i \in C_k} \boldsymbol{x}_i\] where \(C_k=\{i:c_i=k\}\). If \(C_k\) is empty, retain its previous center instead of dividing by zero. For distance ties, retain the previous assignment if it is a minimizer; otherwise choose the smallest minimizing index.
Check convergence: If assignments don’t change, stop
Output: Cluster centers \(\{\boldsymbol{\mu}_k\}\) and assignments \(\{c_i\}\)
Theorem 19.3 (K-Means Convergence). With the specified empty-cluster and tie rules, Lloyd’s algorithm reaches a fixed assignment in finitely many iterations in exact arithmetic. Its objective does not increase:
Assignment step: Each point moves to nearest center \(\to\) \(J\) decreases
Update step: Each center moves to mean of its cluster \(\to\) \(J\) decreases
After a mean update, changing an assignment under these tie rules strictly decreases the objective. There are finitely many assignments, so cycling is excluded. The resulting fixed point need not be globally optimal; degeneracies require care when describing it as a local minimum.
Initialization Matters!
K-means reaches an initialization-dependent fixed point (generically a local solution); a global optimum is not guaranteed.
K-Means++ Initialization:
Choose first center uniformly at random
For each subsequent center, choose point with probability proportional to squared distance from nearest existing center
Repeat until \(K\) centers chosen
This spreads out initial centers, leading to better final clusters.
Multiple Runs: Run K-means multiple times (10-100) with different initializations, keep the best result (lowest \(J\)).
19.1.3 Deriving Both Lloyd Steps and Following Every Objective Value
For fixed centers, each assignment minimizes one nonnegative summand independently, so choosing a nearest center cannot raise \(J\). For a fixed nonempty cluster \(C\) with mean \(\bar{\boldsymbol{x}}_C\), expand \[\sum_{i\in C}\|\boldsymbol{x}_i-\boldsymbol{\mu}\|^2 =\sum_{i\in C}\|\boldsymbol{x}_i-\bar{\boldsymbol{x}}_C\|^2 +|C|\|\boldsymbol{\mu}-\bar{\boldsymbol{x}}_C\|^2.\] The cross term vanishes because centered deviations sum to zero. The second term is minimized exactly at the mean, proving the update rule and its monotonicity. The objective here is a sum of squared Euclidean distances; dividing the entire unregularized objective by \(n\) changes its scale but not either minimizing step.
Example 19.4 (Two assignment/update rounds). Use one-dimensional training observations \((0,2,3,10,11,12)\) and initial centers \((0,3)\). Initial nearest-center assignments are \(\{0\}\) and \(\{2,3,10,11,12\}\), with \(J=0+1+0+49+64+81=195\). Updating their means gives centers \((0,7.6)\) and \(J=89.2\). Reassigning with these centers yields \(\{0,2,3\}\) and \(\{10,11,12\}\), reducing \(J\) to \(49.68\). Updating again gives centers \((5/3,11)\) and \[J=\frac{25+1+16}{9}+1+0+1=\frac{20}{3}.\] The next assignment changes nothing. The complete objective sequence is \(195\to89.2\to49.68\to20/3\to20/3\). A new input is assigned using the frozen centers, not by recomputing them with that input.
A fixed point need not be globally optimal. For data \((0,1,2,10,11,12,30)\) and \(K=2\), centers \((1,15.75)\) with clusters \(\{0,1,2\}\) and \(\{10,11,12,30\}\) are stable and have \(J=274.75\). The alternative stable centers \((6,30)\) have \(J=154\). Initialization and multiple restarts therefore matter even in one dimension.
With K-means++ and the first center fixed at 0 in the six-point example, the next-center probabilities are proportional to \((0,4,9,100,121,144)\), whose sum is 378. This makes distant observations more likely, not certain. If every remaining distance is zero, there are fewer distinct locations than requested centers and the ordinary probability formula needs a fallback.
19.1.4 Cluster Count and the Geometry of Evaluation
At the global optimum, allowing another center cannot increase within-cluster SSE, because the old centers remain a feasible configuration. Independently initialized local fits can nevertheless produce nonmonotone observed values; use reliable restarts and disclose the fitting procedure. An elbow is a descriptive feature of an objective curve, not a proof of a true number of populations. Reusing labels to choose \(K\) turns that choice into supervised model selection.
Example 19.5 (Silhouette, Davies–Bouldin, and Calinski–Harabasz). Use points \((0,2,10,12)\) with clusters \(\{0,2\}\) and \(\{10,12\}\). Each within-cluster average distance to the other member is 2. Mean distances to the other cluster are \((11,9,9,11)\), so silhouettes are \((9/11,7/9,7/9,9/11)\) and their mean is \(79/99=0.797980\). Silhouette uses the minimum mean distance to an entire other cluster, not merely the nearest other centroid. A singleton is conventionally assigned silhouette zero; an overall silhouette requires at least two clusters and fewer clusters than observations.
For Davies–Bouldin, centroid locations are 1 and 11, mean within-cluster distances to centroids are both 1, and the score is \((1+1)/10=0.2\). For Calinski–Harabasz, within-cluster SSE \(W=4\) and between-cluster scatter \(B=100\) give \([B/(K-1)]/[W/(n-K)]=50\). These metrics reward the declared geometry; a high compactness score is not external evidence that the groups match a scientific or business category.
19.1.5 Choosing K (Number of Clusters)
Definition 19.6 (Elbow Method). Plot \(J\) (within-cluster sum of squares) vs \(K\). Look for an “elbow”—a point where \(J\) stops decreasing rapidly.
Definition 19.7 (Silhouette Score). For each point \(i\), compute:
\(a_i\): Average distance to other points in same cluster
\(b_i\): Minimum, over all other clusters, of the mean distance to all members of that cluster
Silhouette coefficient: \[s_i = \frac{b_i - a_i}{\max(a_i, b_i)} \in [-1, 1]\]
\(s_i \approx 1\): Well clustered (far from other clusters)
\(s_i \approx 0\): On boundary between clusters
\(s_i < 0\): Possibly assigned to wrong cluster
Silhouette score: Average \(s_i\) over all points. Larger values favor separation under this metric. Use the singleton convention \(s_i=0\); define \(s_i=0\) when \(a_i=b_i=0\) as well.
19.1.6 Advantages and Limitations
Advantages of K-Means:
Simple, intuitive, easy to implement
Fast: \(O(nKdT)\) where \(T\) is number of iterations (usually small)
Scales to large datasets
Works well for spherical, well-separated clusters
Limitations:
Must specify \(K\) in advance
Squared Euclidean Voronoi geometry favors compact groups and does not fit general component covariance shapes
Sensitive to outliers
Sensitive to initialization (local minima)
Only uses Euclidean distance
Poor with non-convex cluster shapes
Variants:
K-Medoids: Use actual data points as centers (more robust to outliers)
Fuzzy C-Means: Soft assignments (points can belong to multiple clusters)
K-Means||: Parallelizable version for big data
19.2 Hierarchical Clustering
Definition 19.8 (Hierarchical Clustering). Build a tree (dendrogram) of nested clusters. Two approaches:
Agglomerative (bottom-up): Start with each point as its own cluster, merge closest pairs
Divisive (top-down): Start with all points in one cluster, recursively split
Agglomerative is more common.
19.2.1 Agglomerative Clustering
Agglomerative Hierarchical Clustering
Input: Data \(\{\boldsymbol{x}_i\}_{i=1}^n\), linkage criterion
Initialize: Each point is its own cluster: \(C_i = \{\boldsymbol{x}_i\}\) for \(i=1,\ldots,n\)
Repeat until one cluster remains:
Find the two closest clusters \(C_i\) and \(C_j\) according to linkage criterion
Merge them: \(C_{\text{new}} = C_i \cup C_j\)
Remove \(C_i\) and \(C_j\), add \(C_{\text{new}}\)
Output: Dendrogram (tree of merges)
Definition 19.9 (Linkage Criteria). How to measure distance between clusters?
1. Single Linkage (minimum): \[d(C_i, C_j) = \min_{\boldsymbol{x} \in C_i, \boldsymbol{z} \in C_j} \left\lVert\boldsymbol{x} - \boldsymbol{z}\right\rVert\] Distance between closest points. Tends to create long, chain-like clusters.
2. Complete Linkage (maximum): \[d(C_i, C_j) = \max_{\boldsymbol{x} \in C_i, \boldsymbol{z} \in C_j} \left\lVert\boldsymbol{x} - \boldsymbol{z}\right\rVert\] Distance between farthest points; it discourages large merged-cluster diameters without guaranteeing a spherical shape.
3. Average Linkage: \[d(C_i, C_j) = \frac{1}{|C_i||C_j|}\sum_{\boldsymbol{x} \in C_i}\sum_{\boldsymbol{z} \in C_j} \left\lVert\boldsymbol{x} - \boldsymbol{z}\right\rVert\] Average distance between all pairs.
4. Ward’s Method: Minimize the increase in within-cluster sum of squares when merging. This Ward criterion assumes Euclidean geometry: \[d(C_i, C_j) = \frac{|C_i||C_j|}{|C_i| + |C_j|} \left\lVert\boldsymbol{\mu}_i - \boldsymbol{\mu}_j\right\rVert^2\]
Advantages of Hierarchical Clustering:
No need to specify \(K\) in advance
Dendrogram provides full hierarchy
Deterministic once the dissimilarity, linkage, and tie-breaking convention are fixed
Single, complete and average linkage allow many dissimilarities; Ward linkage requires Euclidean geometry
Intuitive visualization
Limitations:
Computational cost: Naive repeated pair searches cost \(O(n^3)\) time; optimized single/complete/average/Ward implementations can achieve \(O(n^2)\) time. Common dense implementations use \(O(n^2)\) memory
Cannot scale to large datasets (millions of points)
Greedy: Cannot undo merges
Sensitive to noise and outliers
When to use:
Small to medium datasets (\(n < 10,000\))
When you want to explore different numbers of clusters
When hierarchy itself is meaningful (taxonomy, phylogenetic trees)
19.2.2 A Numeric Dendrogram and the Ward Identity
Example 19.10 (Every merge for four points). Let \(A=(0,0),B=(1,0),C=(0,1),D=(5,5)\). Distances are \(d_{AB}=d_{AC}=1\), \(d_{BC}=\sqrt2\), \(d_{AD}=\sqrt{50}\), and \(d_{BD}=d_{CD}=\sqrt{41}\). Resolve the first tie lexicographically as \(A,B\).
Complete linkage first merges \(\{A,B\}\) at height 1, then adds \(C\) at height \(\max(1,\sqrt2)=\sqrt2\), then joins \(D\) at height \(\sqrt{50}\). A cut between \(\sqrt2\) and \(\sqrt{50}\) yields \(\{A,B,C\}\) and \(\{D\}\). With single linkage, the final distance would instead be \(\sqrt{41}\); the linkage rule changes the hierarchy’s heights and can change its partition.
For Ward, write \(\operatorname{SSE}(C)=\sum_{i\in C}\|\boldsymbol{x}_i-\boldsymbol{\mu}_C\|^2\). Substituting the merged mean \(\boldsymbol{\mu}_{A\cup B}=(n_A\boldsymbol{\mu}_A+n_B\boldsymbol{\mu}_B)/(n_A+n_B)\) into the previous centered-sum identity gives \[\operatorname{SSE}(A\cup B)-\operatorname{SSE}(A)-\operatorname{SSE}(B) =\frac{n_An_B}{n_A+n_B}\|\boldsymbol{\mu}_A-\boldsymbol{\mu}_B\|^2.\] This is an increase in SSE, not an ordinary Euclidean distance. On the four-point dataset, Ward’s increases are \(1/2\), \(5/6\), and \(98/3\). They sum to 34, the total scatter about the overall mean \((1.5,1.5)\). Some software plots a transformed Ward height such as \(\sqrt{2\Delta\mathrm{SSE}}\); label the convention instead of substituting raw SSE increases into an unexplained distance scale.
19.3 DBSCAN (Density-Based Clustering)
Definition 19.11 (DBSCAN). DBSCAN (Density-Based Spatial Clustering of Applications with Noise) clusters based on density. Two parameters:
\(\epsilon\): Neighborhood radius
\(\text{minPts}\): Minimum points to form a dense region
Point types:
Core point: Its closed \(\epsilon\)-neighborhood contains at least minPts points, counting the point itself
Border point: Within \(\epsilon\) of a core point, but not core itself
Noise point: Neither core nor border
DBSCAN Algorithm
Input: Data \(\{\boldsymbol{x}_i\}\), radius \(\epsilon\), minPts. Let \(N_\epsilon(i)=\{j:\left\lVert\boldsymbol{x}_i-\boldsymbol{x}_j\right\rVert\leq\epsilon\}\), including \(i\).
Initialize: Every point is unvisited with label UNASSIGNED; cluster counter \(C=0\).
For each index \(i\):
If \(i\) is visited, skip it. Otherwise mark it visited and compute \(N_\epsilon(i)\).
If \(|N_\epsilon(i)|<\text{minPts}\), label \(i\) NOISE and continue to the next index.
Otherwise increment \(C\), assign \(i\) to \(C\), initialize a queue \(Q\) with \(N_\epsilon(i)\setminus\{i\}\), and initialize the set of queued indices \(S=N_\epsilon(i)\).
While \(Q\) is not empty, pop \(j\):
If \(j\) is unvisited, mark it visited and compute \(N_\epsilon(j)\). If \(j\) is core, append only \(N_\epsilon(j)\setminus S\) to \(Q\), then set \(S\leftarrow S\cup N_\epsilon(j)\).
If \(j\) has label UNASSIGNED or NOISE, assign it to \(C\). Do not overwrite membership in a previously formed cluster.
Visited points are never expanded twice, and each index enters a given cluster’s queue at most once. A point provisionally labeled NOISE may later become a border point.
Output: Cluster labels and remaining NOISE points.
Advantages of DBSCAN:
Discovers arbitrary shapes: Not limited to spherical clusters
Handles noise: Explicitly identifies outliers
No need to specify \(K\): Number of clusters determined automatically
Only two parameters: \(\epsilon\) and minPts
Limitations:
Sensitive to \(\epsilon\) and minPts (hard to tune)
Struggles with varying densities
Worst-case neighborhood-search work can be \(O(n^2)\); spatial indexes can improve typical performance in favorable low-dimensional data, but do not guarantee \(O(n\log n)\) in every case
A non-core point reachable from core points in different clusters may be assigned according to traversal order; equal distances are not required
Parameter selection:
minPts: Often set to \(2d\) where \(d\) is dimensionality, or 4-5 for 2D data
\(\epsilon\): Plot k-distance graph (distance to \(k\)-th nearest neighbor), look for “knee”
19.3.1 Neighborhoods, Queue Expansion, and Provisional Noise
Example 19.12 (Following DBSCAN in index order). Use \(x=(0,0.4,0.5,0.6,3)\), \(\epsilon=0.45\), and minPts\(=3\), counting the point itself. The full closed-neighborhood table is
| Index | Value | Neighbor indices | Final type |
|---|---|---|---|
| 1 | 0 | \(1,2\) | border |
| 2 | 0.4 | \(1,2,3,4\) | core |
| 3 | 0.5 | \(2,3,4\) | core |
| 4 | 0.6 | \(2,3,4\) | core |
| 5 | 3 | \(5\) | noise |
Visit row 1 first: its count is two, so mark it provisional NOISE. Row 2 is core; start cluster 1 and queue rows \(1,3,4\). Popping row 1 assigns it to cluster 1, without expanding its non-core neighborhood. Rows 3 and 4 are core; their neighborhoods add no unqueued indices after deduplication. Row 5 stays noise. Final labels are \((1,1,1,1,\mathrm{NOISE})\).
The core-point graph has vertices \(2,3,4\) joined by within-\(\epsilon\) edges. Its connected component defines the dense cluster; row 1 attaches as a border point. Border points do not expand connectivity and cannot serve as bridges between two core components. The example also shows why an early NOISE label must remain eligible for reassignment.
If a nearest-neighbor distance plot excludes the point itself, minPts includes one more point than that neighbor count: the relevant neighbor is the \((\text{minPts}-1)\)th other observation. Declare this convention before using a knee plot. DBSCAN’s noise label expresses isolation under its chosen scale and metric, not a causal explanation of an anomaly. Standard DBSCAN specifies clustering of the fitted dataset rather than a universal out-of-sample prediction rule; define a frozen nearest-core assignment policy explicitly if an application needs one.
19.4 Gaussian Mixtures and Expectation–Maximization
K-means makes hard assignments under squared Euclidean geometry. A Gaussian mixture instead models a density \[p(\boldsymbol{x}\mid\theta)=\sum_{k=1}^K\pi_k\mathcal N(\boldsymbol{x};\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k), \qquad \pi_k\ge0,\quad\sum_k\pi_k=1.\] A latent class \(z_i\) identifies the component. Unlike GDA in Part 2, these component labels are not observed during fitting, and mixture components need not correspond to externally meaningful classes.
Why EM alternates. For any categorical probabilities \(r_{ik}\), Jensen’s inequality gives \[\log\sum_k\pi_kp_k(\boldsymbol{x}_i) \ge\sum_k r_{ik}\log\frac{\pi_kp_k(\boldsymbol{x}_i)}{r_{ik}}.\] The bound is tight when \(r_{ik}\) equals the current posterior component probability. Summing over examples defines a lower bound on the log-likelihood. The E-step makes it tight at the old parameters; the M-step increases it with respect to parameters. Thus the new likelihood is at least the new bound, which is at least the old likelihood, for exact unmodified EM steps with valid densities. The guarantee is nondecrease, not convergence to a global maximum.
EM for a Gaussian mixture
Initialize weights summing to one, means, and positive-definite covariances.
E-step: \(r_{ik}=\pi_k\mathcal N(\boldsymbol{x}_i;\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k)/\sum_s\pi_s\mathcal N(\boldsymbol{x}_i;\boldsymbol{\mu}_s,\boldsymbol{\Sigma}_s)\).
Put \(N_k=\sum_i r_{ik}\) and \(\pi_k=N_k/n\). If \(N_k=0\), retain that component’s previous mean and covariance; otherwise use the updates below. A singular covariance update must be reported or handled by a separately declared constraint/regularization rule. For nonzero \(N_k\), the unconstrained M-step is \[\pi_k=\frac{N_k}{n},\qquad \boldsymbol{\mu}_k=\frac1{N_k}\sum_i r_{ik}\boldsymbol{x}_i,\qquad \boldsymbol{\Sigma}_k=\frac1{N_k}\sum_i r_{ik}(\boldsymbol{x}_i-\boldsymbol{\mu}_k)(\boldsymbol{x}_i-\boldsymbol{\mu}_k)^\top.\]
Check the same declared log-likelihood for convergence. Compute responsibilities using log densities and log-sum-exp for stability.
Example 19.13 (One full scalar EM iteration). Use \(x=(-1,1,3)\), equal initial weights \(1/2\), initial means \((0,2)\), and initial variances \((1,1)\). Initial component-1 log-odds are \(2-2x\), so the responsibility matrix is \[\boldsymbol{R}=\begin{bmatrix}.982014&.017986\\.5&.5\\.017986&.982014\end{bmatrix}.\] Both effective counts equal \(1.5\). The M-step gives \[\begin{align*} \boldsymbol{\pi}&=(0.5,0.5),\\ \boldsymbol{\mu}&=(-0.285370,2.285370),\\ \boldsymbol{\sigma}^2&=(1.014490,1.014490). \end{align*}\] For instance, the first updated mean is \([-.982014+.5+3(.017986)]/1.5\), using unrounded responsibilities in the actual computation. Summed log-likelihood rises from \(-5.606810\) to \(-5.469830\). Dividing both values by three would report a mean log-likelihood with the same maximizing parameters.
With equal priors and a shared fixed isotropic covariance \(\sigma^2\boldsymbol{I}\), responsibilities approach nearest-center assignments as \(\sigma^2\to0\) away from distance ties, connecting mixture fitting to K-means. General mixtures permit unequal shapes and soft membership. Unconstrained mixture likelihood can become unbounded when a component covariance collapses onto a data point; initialization, covariance constraints, or regularization are essential practical choices. Such changes alter the optimization problem and its guarantees. Select component count and regularization within training/validation boundaries, not by refitting to final test observations. The Gaussian-mixture documentation describes implemented covariance choices and regularization.
19.5 Cluster Evaluation Metrics
When ground truth labels are unavailable:
Definition 19.14 (Davies-Bouldin Index). \[\text{DB} = \frac{1}{K}\sum_{i=1}^K \max_{j \neq i} \left(\frac{s_i + s_j}{d_{ij}}\right)\] where \(s_i=|C_i|^{-1}\sum_{\boldsymbol{x}\in C_i}\|\boldsymbol{x}-\boldsymbol{\mu}_i\|\) is mean distance to its own centroid and \(d_{ij}=\|\boldsymbol{\mu}_i-\boldsymbol{\mu}_j\|\). Coincident centroids require an explicit zero-denominator convention.
Lower is better (smaller within-cluster spread, larger between-cluster separation).
Definition 19.15 (Calinski-Harabasz Index (Variance Ratio)). \[\text{CH} = \frac{B/(K-1)}{W/(n-K)},\quad B=\sum_k|C_k|\|\boldsymbol{\mu}_k-\bar{\boldsymbol{x}}\|^2,\quad W=\sum_k\sum_{i\in C_k}\|\boldsymbol{x}_i-\boldsymbol{\mu}_k\|^2\] Higher is better (better separation).
When ground truth labels are available:
Definition 19.16 (Adjusted Rand Index (ARI)). Measures agreement between predicted clusters and true labels, adjusted for chance. \[\text{ARI} \in [-1, 1]\]
ARI = 1: Perfect agreement
ARI has chance expectation zero under the fixed-marginal adjustment model; individual random partitions can differ
ARI < 0: Worse than random
19.5.1 Adjusted Agreement Is Invariant to Cluster Names
Let \(n_{ij}\) count observations in predicted cluster \(i\) and reference class \(j\), with row totals \(a_i\), column totals \(b_j\), and \(N=\binom n2\). For the usual fixed-marginal chance model, \[\operatorname{ARI}=\frac{\sum_{ij}\binom{n_{ij}}2-\frac{\sum_i\binom{a_i}2\sum_j\binom{b_j}2}{N}} {\frac12\left[\sum_i\binom{a_i}2+\sum_j\binom{b_j}2\right]-\frac{\sum_i\binom{a_i}2\sum_j\binom{b_j}2}{N}}.\] The adjusted expected agreement is zero under that chance model; a single random assignment need not have score exactly zero. Degenerate zero-denominator partitions require an explicit convention.
Example 19.17 (A negative ARI and a harmless label permutation). Reference labels \((0,0,1,1)\) and predicted labels \((0,1,0,1)\) have a \(2\times2\) contingency table of all ones. Thus the joint within-cell pair count is zero, each marginal within-group pair count is two, and \(N=6\). The expected pair count is \(4/6\), giving ARI \(=(0-2/3)/(2-2/3)=-1/2\). In contrast, predicted labels \((7,7,3,3)\) encode the same partition as the reference and give ARI 1. Numerical cluster IDs are arbitrary; ordinary classification accuracy without label alignment is not a clustering agreement metric.
If reference labels guide the choice of representation or clustering settings, they are validation information rather than a final independent assessment. Report whether density-clustering noise points are excluded, treated as one label, or evaluated separately; these choices can change every reported metric.
20 Dimensionality Reduction
20.1 Motivation
The Curse of Dimensionality:
For uniform hypercube data, most volume lies near the boundary; high-dimensional sparsity and distance concentration depend on the data distribution
Distance metrics become less meaningful
Overfitting becomes severe
Computational cost depends on the algorithm; maintaining a fixed sampling resolution can require exponentially many points as dimension grows
Benefits of Dimensionality Reduction:
Visualization (reduce to 2D or 3D)
Noise reduction (eliminate irrelevant features)
Faster training (fewer features)
Storage efficiency
Avoid overfitting
Two approaches:
Feature Selection: Select subset of original features
Feature Extraction: Create new features as combinations of originals
20.2 Principal Component Analysis (PCA)
20.2.1 Intuition and Formulation
Definition 20.1 (PCA Goal). Find a low-dimensional linear subspace that captures maximum variance in the data.
Formally, find \(k\) orthogonal directions \(\{\boldsymbol{u}_1, \ldots, \boldsymbol{u}_k\}\) that maximize: \[\max_{\boldsymbol{u}_1, \ldots, \boldsymbol{u}_k} \sum_{j=1}^k \mathrm{Var}(\boldsymbol{x}^\top \boldsymbol{u}_j)\] subject to \(\left\lVert\boldsymbol{u}_j\right\rVert = 1\) and \(\boldsymbol{u}_i \perp \boldsymbol{u}_j\) for \(i \neq j\).
Intuition 252. PCA finds new coordinate axes (principal components) along which data has maximum spread. The first component captures the most variance, the second captures the most remaining variance (orthogonal to the first), and so on.
Think of a 3D cloud of points shaped like a pancake. PCA finds the plane that best fits the pancake, and potentially a line within that plane.
Theorem 20.3 (PCA via Eigendecomposition). Given centered data (mean subtracted), the principal components are the eigenvectors of the covariance matrix \(\boldsymbol{\Sigma} = \frac{1}{n}\boldsymbol{X}^\top\boldsymbol{X}\).
Steps:
Center data: \(\tilde{\boldsymbol{x}}_i = \boldsymbol{x}_i - \bar{\boldsymbol{x}}\) where \(\bar{\boldsymbol{x}} = \frac{1}{n}\sum_i \boldsymbol{x}_i\)
Compute covariance: \(\boldsymbol{\Sigma} = \frac{1}{n}\sum_{i=1}^n \tilde{\boldsymbol{x}}_i\tilde{\boldsymbol{x}}_i^\top\)
Eigendecomposition: \(\boldsymbol{\Sigma} = \boldsymbol{U}\boldsymbol{\Lambda}\boldsymbol{U}^\top\)
Sort eigenvalues \(\lambda_1 \geq \lambda_2 \geq \cdots \geq \lambda_d\)
Top \(k\) eigenvectors \(\{\boldsymbol{u}_1, \ldots, \boldsymbol{u}_k\}\) are principal components
Projection: \(\boldsymbol{z}_i = \boldsymbol{U}_k^\top \tilde{\boldsymbol{x}}_i \in \mathbb{R}^k\) where \(\boldsymbol{U}_k = [\boldsymbol{u}_1, \ldots, \boldsymbol{u}_k]\).
Reconstruction: \(\hat{\boldsymbol{x}}_i = \boldsymbol{U}_k \boldsymbol{z}_i + \bar{\boldsymbol{x}}\).
Sketch. We want to maximize \(\sum_i (\boldsymbol{u}_1^\top \tilde{\boldsymbol{x}}_i)^2 = \boldsymbol{u}_1^\top \left(\sum_i \tilde{\boldsymbol{x}}_i\tilde{\boldsymbol{x}}_i^\top\right)\boldsymbol{u}_1 = n\boldsymbol{u}_1^\top \boldsymbol{\Sigma} \boldsymbol{u}_1\).
Maximizing this sum is equivalent to maximizing the sample variance \(\boldsymbol{u}_1^\top\boldsymbol{\Sigma}\boldsymbol{u}_1\). Using Lagrange multipliers for \(\left\lVert\boldsymbol{u}_1\right\rVert=1\): \[\mathcal{L} = \boldsymbol{u}_1^\top \boldsymbol{\Sigma} \boldsymbol{u}_1 - \lambda(\boldsymbol{u}_1^\top\boldsymbol{u}_1 - 1)\] Taking derivative and setting to zero: \[\boldsymbol{\Sigma}\boldsymbol{u}_1 = \lambda\boldsymbol{u}_1\] So \(\boldsymbol{u}_1\) is an eigenvector of \(\boldsymbol{\Sigma}\). To maximize variance, choose eigenvector with largest eigenvalue \(\lambda_1\). The variance captured is \(\lambda_1\). Repeat for subsequent components (orthogonal eigenvectors). ◻
PCA Algorithm
Input: Data \(\boldsymbol{X} \in \mathbb{R}^{n \times d}\), target dimension \(k\)
Center data: \(\tilde{\boldsymbol{X}}=\boldsymbol{X}-\mathbf{1}_n\bar{\boldsymbol{x}}^\top\) where \(\bar{\boldsymbol{x}} = \frac{1}{n}\sum_i \boldsymbol{x}_i\)
Compute covariance: \(\boldsymbol{\Sigma} = \frac{1}{n}\tilde{\boldsymbol{X}}^\top\tilde{\boldsymbol{X}}\)
Compute eigenvectors/eigenvalues: \(\boldsymbol{\Sigma} = \boldsymbol{U}\boldsymbol{\Lambda}\boldsymbol{U}^\top\)
Sort eigenvalues in descending order
Select top \(k\) eigenvectors: \(\boldsymbol{U}_k = [\boldsymbol{u}_1, \ldots, \boldsymbol{u}_k]\)
Project data: \(\boldsymbol{Z} = \tilde{\boldsymbol{X}}\boldsymbol{U}_k\)
Output: Reduced data \(\boldsymbol{Z} \in \mathbb{R}^{n \times k}\), transformation \(\boldsymbol{U}_k\)
20.2.2 Reconstruction Optimality, SVD, and a Complete Projection
For centered rows \(\tilde{\boldsymbol{X}}\) and orthonormal columns \(\boldsymbol{U}_k\), reconstruction is \(\tilde{\boldsymbol{X}}\boldsymbol{U}_k\boldsymbol{U}_k^\top\). Expanding its squared Frobenius error gives \[\frac1n\|\tilde{\boldsymbol{X}}-\tilde{\boldsymbol{X}}\boldsymbol{U}_k\boldsymbol{U}_k^\top\|_F^2 =\operatorname{tr}(\boldsymbol{\Sigma})-\operatorname{tr}(\boldsymbol{U}_k^\top\boldsymbol{\Sigma}\boldsymbol{U}_k).\] In an eigenbasis \(\boldsymbol{\Sigma}=\sum_j\lambda_j\boldsymbol{u}_j\boldsymbol{u}_j^\top\), captured variance is \(\sum_j\lambda_j\|\boldsymbol{U}_k^\top\boldsymbol{u}_j\|^2\). These weights lie in \([0,1]\) and sum to \(k\), so selecting the \(k\) largest eigenvalues maximizes the trace and minimizes reconstruction error. The minimum mean squared reconstruction error is \(\sum_{j>k}\lambda_j\), with squared coordinates summed per example as in Parts 1 and 4.
If \(\tilde{\boldsymbol{X}}=\boldsymbol{L}\boldsymbol{S}\boldsymbol{V}^\top\) is an SVD (here \(\boldsymbol{L}\) denotes left singular vectors), then \(\boldsymbol{\Sigma}=\boldsymbol{V}\boldsymbol{S}^\top\boldsymbol{S}\boldsymbol{V}^\top/n\). Principal directions are the right singular vectors, eigenvalues are \(s_j^2/n\), and scores are \(\tilde{\boldsymbol{X}}\boldsymbol{V}_k\). This avoids explicitly forming a covariance matrix and connects directly to the SVD in Part 0. Eigenvector signs and rotations within repeated-eigenvalue subspaces are not uniquely identified.
Example 20.4 (Four points, one principal component, and reconstruction). Take training mean \(\bar{\boldsymbol{x}}=(2,1)^\top\) and centered points \[(\sqrt3,\sqrt3),\quad(-\sqrt3,-\sqrt3),\quad(1,-1),\quad(-1,1).\] Add the mean to obtain the actual observations. Their covariance with divisor four is \[\boldsymbol{\Sigma}=\begin{bmatrix}2&1\\1&2\end{bmatrix},\quad \lambda_1=3,\ \boldsymbol{u}_1=\frac1{\sqrt2}(1,1)^\top,\quad \lambda_2=1,\ \boldsymbol{u}_2=\frac1{\sqrt2}(1,-1)^\top.\] Retaining \(\boldsymbol{u}_1\) gives scores \((\sqrt6,-\sqrt6,0,0)\) and explained variance \(3/(3+1)=75\%\). The first two points reconstruct exactly; the last two reconstruct to the mean, each with squared error 2. Total reconstruction SSE is 4 and mean squared error is 1, exactly the discarded eigenvalue.
For a new input \((4,1)\), center using the training mean to get \((2,0)\), project to \(z=\sqrt2\), and reconstruct to \((3,2)\). Do not refit the mean or axis on this input. Omitting centering would diagonalize the second-moment matrix \(\boldsymbol{\Sigma}+\bar{\boldsymbol{x}}\bar{\boldsymbol{x}}^\top=\left[\begin{smallmatrix}6&3\\3&3\end{smallmatrix}\right]\), a different problem whose leading direction need not equal \(\boldsymbol{u}_1\).
Whitening further rescales score coordinate \(j\) by \(1/\sqrt{\lambda_j}\), giving unit empirical variance under this \(1/n\) convention. It changes distances and discards the original variance scale; zero eigenvalues cannot be inverted. Implementations may report covariance eigenvalues using divisor \(n-1\), changing numerical variances by \(n/(n-1)\) while leaving directions and explained-variance ratios unchanged. Match the covariance convention when checking outputs against the PCA API. Centering, optional scaling, component count, and any whitening regularization all belong inside the current training fold.
For the exercise covariance \(\left[\begin{smallmatrix}4&2\\2&2\end{smallmatrix}\right]\), the characteristic polynomial is \(\lambda^2-6\lambda+4\), giving eigenvalues \(3\pm\sqrt5\). A corresponding eigenvector is proportional to \((2,\lambda-4)^\top\); the first explained-variance ratio is \((3+\sqrt5)/6\). This is a second covariance example, not the covariance of the four plotted points.
20.2.3 Choosing Number of Components
Definition 20.5 (Explained Variance Ratio). Proportion of total variance captured by first \(k\) components: \[\text{EVR}_k = \frac{\sum_{j=1}^k \lambda_j}{\sum_{j=1}^d \lambda_j}\] Common threshold: Keep enough components to explain 90-95% of variance.
20.2.4 PCA Properties and Limitations
Key Properties of PCA:
Linear transformation: \(\boldsymbol{z} = \boldsymbol{U}_k^\top(\boldsymbol{x} - \bar{\boldsymbol{x}})\)
Optimal reconstruction: Minimizes reconstruction error \(\sum_i \left\lVert\boldsymbol{x}_i - \hat{\boldsymbol{x}}_i\right\rVert^2\)
Uncorrelated coordinates: \(n^{-1}\boldsymbol{Z}^\top\boldsymbol{Z}\) is diagonal; this refers to different component columns, not different sample rows
Ordered by importance: First component captures most variance
Advantages:
Fast, closed-form solution (eigendecomposition)
Interpretable (variance explained)
Few structural choices: retained dimension, input scaling, and optional whitening; numerical solver settings also matter
Allows approximate reconstruction; exact recovery for \(k<d\) requires the centered data to lie in the retained subspace
Limitations:
Linear only: Cannot capture non-linear structure
Assumes variance = importance: High variance might be noise
Sensitive to scaling: Center the data; decide whether to standardize based on units and which variances should count as important
No Gaussian requirement: Ordinary PCA is a geometric variance/reconstruction method; Gaussian assumptions belong to particular probabilistic interpretations
Interpretability: Components are linear combinations, hard to interpret
When to use PCA:
Preprocessing for supervised learning
Visualization (project to 2D/3D)
Noise reduction
When features are correlated
20.3 Linear Discriminant Analysis (LDA)
Definition 20.6 (LDA). Unlike PCA (unsupervised), LDA is supervised dimensionality reduction. It finds directions that maximize separation between classes.
Goal: Find projection \(\boldsymbol{w}\) that maximizes: \[J(\boldsymbol{w}) = \frac{\text{Between-class variance}}{\text{Within-class variance}} = \frac{\boldsymbol{w}^\top \boldsymbol{S}_B \boldsymbol{w}}{\boldsymbol{w}^\top \boldsymbol{S}_W \boldsymbol{w}}\] where:
\(\boldsymbol{S}_W = \sum_{c=1}^K \sum_{i \in C_c} (\boldsymbol{x}_i - \boldsymbol{\mu}_c)(\boldsymbol{x}_i - \boldsymbol{\mu}_c)^\top\) (within-class scatter)
\(\boldsymbol{S}_B = \sum_{c=1}^K n_c (\boldsymbol{\mu}_c - \boldsymbol{\mu})(\boldsymbol{\mu}_c - \boldsymbol{\mu})^\top\) (between-class scatter)
Theorem 20.7 (LDA Solution). When \(\boldsymbol{S}_W\) is nonsingular, solve \(\boldsymbol{S}_B\boldsymbol{w}=\lambda\boldsymbol{S}_W\boldsymbol{w}\) and retain directions with the largest eigenvalues. Equivalently these are eigenvectors of \(\boldsymbol{S}_W^{-1}\boldsymbol{S}_B\); singular within-class scatter requires regularization or another appropriate solver.
Maximum number of components: \(\min(d, K-1)\) where \(K\) is number of classes.
PCA vs LDA:
PCA: Unsupervised, maximizes input variance using only the current training inputs for inductive evaluation
LDA: Supervised, maximizes class separation, uses labels
When to use LDA:
Dimensionality reduction before classification
When classes are well-separated
When you have class labels
Label information changes the projection objective; whether LDA improves classification requires held-out evaluation.
20.3.1 Fisher’s Criterion and a Case Where Variance Loses the Labels
Constrain \(\boldsymbol{w}^\top\boldsymbol{S}_W\boldsymbol{w}=1\) when \(\boldsymbol{S}_W\) is positive definite. A Lagrange multiplier for maximizing \(\boldsymbol{w}^\top\boldsymbol{S}_B\boldsymbol{w}\) gives \(\boldsymbol{S}_B\boldsymbol{w}=\lambda\boldsymbol{S}_W\boldsymbol{w}\), proving the generalized eigenproblem. Since the class-mean deviations satisfy \(\sum_c n_c(\boldsymbol{\mu}_c-\boldsymbol{\mu})=0\), their span has dimension at most \(K-1\), which bounds the number of nonzero discriminant directions. In the binary case the optimal direction is proportional to \(\boldsymbol{S}_W^{-1}(\boldsymbol{\mu}_1-\boldsymbol{\mu}_0)\). The shared-covariance GDA boundary normal in Part 2 points in the same direction; a projection criterion alone does not specify its prior-dependent decision threshold.
Example 20.8 (High variance is not necessarily class information). Use four class-0 points \((x_1,x_2)=(-1\pm0.2,\pm3)\), taking all four sign combinations, and four class-1 points \((1\pm0.2,\pm3)\). The overall mean is zero and \[\boldsymbol{S}_W=\begin{bmatrix}.32&0\\0&72\end{bmatrix},\qquad \boldsymbol{S}_B=\begin{bmatrix}8&0\\0&0\end{bmatrix},\qquad \boldsymbol{\Sigma}=\frac{\boldsymbol{S}_W+\boldsymbol{S}_B}{8}=\begin{bmatrix}1.04&0\\0&9\end{bmatrix}.\] PCA keeps the vertical direction first, explaining \(9/10.04\) of total variance but mapping both classes to the same repeated values \(\pm3\). Fisher LDA keeps the horizontal direction, with Rayleigh quotient \(8/0.32=25\) and perfect separation in these eight training observations. Shared-covariance GDA has covariance \(\operatorname{diag}(0.04,9)\) and boundary normal \((50,0)^\top\), agreeing in direction. This example shows an objective difference, not universal superiority of supervised projection on unseen data.
LDA uses training labels in fitting its transformation and must be fitted inside every training fold. PCA does not use labels in its objective but still learns from inputs; neither can be fitted globally before an inductive held-out evaluation.
20.4 Non-Linear Methods
20.4.1 t-SNE (t-Distributed Stochastic Neighbor Embedding)
Definition 20.9 (t-SNE). Non-linear method that preserves local structure. Particularly good for visualization.
Idea:
In high-dimensional space, compute pairwise similarities: \[\begin{gathered} p_{j\mid i}=\frac{\exp(-\left\lVert\boldsymbol{x}_i-\boldsymbol{x}_j\right\rVert^2/(2\sigma_i^2))}{\sum_{k\neq i}\exp(-\left\lVert\boldsymbol{x}_i-\boldsymbol{x}_k\right\rVert^2/(2\sigma_i^2))},\quad j\neq i,\\ p_{ij}=\frac{p_{j\mid i}+p_{i\mid j}}{2n},\quad p_{ii}=0. \end{gathered}\]
Each \(\sigma_i\) is chosen to match the specified perplexity of the conditional neighbor distribution.
In low-dimensional space, use a one-degree-of-freedom Student-t kernel for \(i\neq j\), with \(q_{ii}=0\): \[q_{ij} = \frac{(1 + \left\lVert\boldsymbol{z}_i - \boldsymbol{z}_j\right\rVert^2)^{-1}}{\sum_{k \neq l} (1 + \left\lVert\boldsymbol{z}_k - \boldsymbol{z}_l\right\rVert^2)^{-1}}\]
Minimize KL divergence: \(\text{KL}(P||Q) = \sum_{i\neq j} p_{ij}\log\frac{p_{ij}}{q_{ij}}\)
Optimized via gradient descent.
t-SNE Properties:
Produces low-dimensional layouts for exploratory visualization; visual separation is not proof of distinct populations
Its objective emphasizes local neighborhood affinities; finite embeddings and optimization can still distort neighbors
Non-linear (can capture complex manifolds)
Stochastic (different runs give different results)
A standard coordinate-only t-SNE fit supplies no general fitted encoder; out-of-sample extensions are separate methods
Exact t-SNE uses quadratic pairwise work; approximate algorithms can reduce the cost
Hyperparameter sensitive (perplexity, learning rate)
When to use:
Visualization of high-dimensional data
Exploratory analysis
Not for preprocessing (use PCA for that)
Interpretation caution:
Plotted cluster area is not a calibrated measure of original-space density or importance
Distances between plotted clusters need not reflect original-space distances
Local neighborhood relationships also need validation and sensitivity checks
20.4.2 Perplexity, Normalization, and a Three-Point Objective
For one conditional neighborhood distribution, perplexity is \(\exp\{-\sum_{j\ne i}p_{j\mid i}\log p_{j\mid i}\}\), equivalently \(2^{H_2}\) when entropy uses base two. Adaptive bandwidth search tries to match this effective neighbor count at each point; it is not a fixed geometric radius. The symmetric \(p_{ij}\) and embedding \(q_{ij}\) are joint probabilities over ordered distinct pairs: each entire matrix sums to one, while individual rows need not.
Example 20.10 (Compute both affinity matrices and one gradient). Take input positions \((0,1,2)\) and, solely for this illustration, a shared bandwidth \(\sigma^2=1/(2\log2)\). Unnormalized off-diagonal similarities are \(2^{-d_{ij}^2}\), so endpoint conditional probabilities are \((8/9,1/9)\), and the middle point assigns \((1/2,1/2)\) to its neighbors. Symmetrization gives \[\boldsymbol{P}=\begin{bmatrix}0&25/108&1/27\\25/108&0&25/108\\1/27&25/108&0\end{bmatrix}.\] This fixed-bandwidth example does not impose a common perplexity; endpoint and middle entropies differ. For candidate embedding positions \(\boldsymbol{z}=(-1,0,1)\), the Student-t weights for neighboring pairs are \(1/2\) and for endpoints \(1/5\). Summing over ordered pairs gives normalization \(12/5\), hence \[\boldsymbol{Q}=\begin{bmatrix}0&5/24&1/12\\5/24&0&5/24\\1/12&5/24&0\end{bmatrix}.\] The objective is \[C=\frac{25}{27}\log\frac{10}{9}+\frac2{27}\log\frac49=0.037487.\] Differentiating the normalized kernel, including its denominator, yields \[\frac{\partial C}{\partial\boldsymbol{z}_i}=4\sum_{j\ne i}(p_{ij}-q_{ij})\frac{\boldsymbol{z}_i-\boldsymbol{z}_j}{1+\|\boldsymbol{z}_i-\boldsymbol{z}_j\|^2}.\] For these scalar positions, the gradient is \((1/36,0,-1/36)\). A small descent step moves the endpoints outward, reducing their excessive embedding affinity. This is an objective/gradient calculation at a candidate embedding, not a converged visualization.
The t-SNE paper defines this affinity-matching objective. A standard fitted coordinate set does not by itself define an encoder for a new input; the standard scikit-learn TSNE API exposes fitting/embedding rather than a general fitted transform. Parametric and other out-of-sample extensions exist and must be evaluated as their own procedures. Apparent cluster area, spacing, or isolation can depend strongly on perplexity, initialization, and optimization. Inspect neighborhood preservation and sensitivity before inferring population structure from an attractive two-dimensional layout.
20.4.3 UMAP (Uniform Manifold Approximation and Projection)
Definition 20.11 (UMAP). A neighbor-graph-based embedding method motivated by manifold geometry and fuzzy set constructions. Its theory and objective differ from t-SNE; this does not establish universal superiority.
Practical properties:
Often fast with approximate neighbor search; runtime depends on sample size, dimension, metric and implementation. A universal \(O(n)\) versus \(O(n^2)\) comparison is not justified
Can reveal different scales of structure, but global geometry is not guaranteed to be preserved
Supports a fitted transform for new inputs; standard coordinate-only t-SNE requires a separate out-of-sample extension
Scales to larger datasets
Neighbor-graph and embedding parameters control the apparent separation; separation alone is not clustering validation
Popular for single-cell RNA-seq visualization and other large-scale applications.
20.4.4 From a Fuzzy Neighbor Graph to an Embedding
UMAP first constructs local neighbor memberships with per-point scales, then combines directed strengths into an undirected fuzzy graph. For two directed strengths \(w_{ij}\) and \(w_{ji}\), the fuzzy-union rule is \[w_{ij}^{\rm union}=w_{ij}+w_{ji}-w_{ij}w_{ji}=1-(1-w_{ij})(1-w_{ji}).\] A low-dimensional membership curve has form \(q_{ij}=[1+a\|\boldsymbol{z}_i-\boldsymbol{z}_j\|^{2b}]^{-1}\) for fitted positive curve parameters. An idealized graph cross-entropy, up to terms independent of the embedding, sums \(-w_{ij}\log q_{ij}-(1-w_{ij})\log(1-q_{ij})\) over pairs. Attractive and repulsive terms compete. Practical training uses edge sampling and negative sampling; this simplified full-pair expression is not a claim that every implementation computes all pairs each step.
Example 20.12 (One graph edge and its competing targets). If directed strengths are \(0.8\) and \(0.5\), their union is \(0.9\), not their arithmetic mean \(0.65\). Set \(a=b=1\) for a transparent curve example. Distance 1 gives \(q=1/2\) and edge cross-entropy \(\log2=0.693147\). Distance \(1/3\) gives \(q=0.9\) and cross-entropy \(-0.9\log0.9-0.1\log0.1=0.325083\). This edge alone prefers its high target membership, but a shared embedding cannot independently realize arbitrary preferred distances for every pair.
The UMAP paper develops the neighbor graph and embedding objective. Neighbor count and minimum-distance settings change the representation’s emphasis; a visually separated group is not automatically a verified cluster. The UMAP transform documentation describes placing new observations in a learned space. Fit that space only on training inputs for an inductive test, then transform validation/test inputs without refitting. Using labels in a supervised UMAP fit changes the learning problem and requires training-only labels as well.
20.4.5 Autoencoders
Definition 20.13 (Autoencoder). Neural network that learns to compress and reconstruct data.
Architecture:
Encoder: \(\boldsymbol{z} = f_{\text{enc}}(\boldsymbol{x}; \boldsymbol{\theta}_{\text{enc}})\) maps \(\boldsymbol{x} \in \mathbb{R}^d\) to \(\boldsymbol{z} \in \mathbb{R}^k\) (bottleneck)
Decoder: \(\hat{\boldsymbol{x}} = f_{\text{dec}}(\boldsymbol{z}; \boldsymbol{\theta}_{\text{dec}})\) reconstructs from \(\boldsymbol{z}\)
Training: Minimize reconstruction error: \[\mathcal{L}= \frac1n\sum_{i=1}^n \left\lVert\boldsymbol{x}_i - \hat{\boldsymbol{x}}_i\right\rVert^2\]
Types of Autoencoders:
Undercomplete: Bottleneck \(k < d\) (forced to compress)
Sparse: Regularize activations in bottleneck
Denoising: Train to reconstruct from corrupted input
Variational (VAE): Learn probability distribution in latent space (generative model)
Advantages:
Non-linear (can capture complex structure)
Flexible architecture
Architectures and reconstruction likelihoods can be designed for different data types
Can be applied to new data (just run encoder)
Limitations:
Requires training (no closed form)
Many hyperparameters
Can be slow to train
May overfit with limited data
20.4.6 The Linear Autoencoder–PCA Connection
For centered column input \(\tilde{\boldsymbol{x}}\), take an orthonormal matrix \(\boldsymbol{U}_k\) and tied linear encoder/decoder \[\boldsymbol{z}=\boldsymbol{U}_k^\top\tilde{\boldsymbol{x}},\qquad \hat{\boldsymbol{x}}=\boldsymbol{U}_k\boldsymbol{z}+\bar{\boldsymbol{x}}.\] Their mean reconstruction objective is exactly the PCA objective in Section 20.2.2. Choosing principal directions therefore minimizes it. More general unregularized linear encoder/decoder products can span the same optimal subspace while using different latent coordinates: an invertible latent change of basis can be undone by the decoder. Latent axes are not automatically identified as principal components unless the relevant constraints fix them.
Example 20.14 (An autoencoder using the same four PCA points). For the four-point PCA dataset, let the encoder be \((1,1)/\sqrt2\) on centered inputs and the decoder its transpose, with output bias equal to the training mean \((2,1)\). Latent values are \((\sqrt6,-\sqrt6,0,0)\). Reconstructions and mean squared error are exactly those computed earlier: SSE 4, MSE 1. The encoder maps the centered input \((1,-1)\) to zero and reconstructs the mean; its squared error is 2. This explicitly connects a neural architecture, a geometric projection, and the same loss scaling.
A nonlinear decoder changes the model family; a narrow bottleneck alone does not prevent memorization of finitely many observations. For a denoising autoencoder, corrupt a training input \(\tilde{\boldsymbol{x}}\sim C(\cdot\mid\boldsymbol{x})\) and minimize \(\mathbb{E}_C\|\boldsymbol{x}-f_{\rm dec}(f_{\rm enc}(\tilde{\boldsymbol{x}}))\|^2\) against the clean training target. Fitting a corruption rule, tuning the bottleneck, or selecting a reconstruction/anomaly threshold uses training/validation data, with final test examples excluded from fitting. Low reconstruction error need not mean that a latent feature is useful for a downstream label.
20.4.7 A VAE Bound with an Analytically Checkable Scalar Example
A variational autoencoder specifies a prior \(p(\boldsymbol{z})\), decoder density \(p_\theta(\boldsymbol{x}\mid\boldsymbol{z})\), and approximate posterior \(q_\phi(\boldsymbol{z}\mid\boldsymbol{x})\). Rearranging the nonnegative divergence to the true posterior gives \[\log p_\theta(\boldsymbol{x}) =\underbrace{\mathbb{E}_q[\log p_\theta(\boldsymbol{x}\mid\boldsymbol{z})]-D_{\rm KL}(q_\phi(\boldsymbol{z}\mid\boldsymbol{x})\|p(\boldsymbol{z}))}_{\mathrm{ELBO}} +D_{\rm KL}(q_\phi(\boldsymbol{z}\mid\boldsymbol{x})\|p_\theta(\boldsymbol{z}\mid\boldsymbol{x})).\] Thus maximizing the evidence lower bound (ELBO) trades reconstruction likelihood against a prior-matching cost, not merely MSE against an unexplained penalty. For diagonal Gaussian \(q\) and standard-normal prior, \[D_{\rm KL}(q\|p)=\tfrac12\sum_j(\mu_j^2+\sigma_j^2-1-\log\sigma_j^2).\] Reparameterizing \(\boldsymbol{z}=\boldsymbol{\mu}+\boldsymbol{\sigma}\odot\boldsymbol{\epsilon}\) with \(\boldsymbol{\epsilon}\sim\mathcal N(\boldsymbol{0},\boldsymbol{I})\) permits differentiation through a sample using parameter-independent noise. With a Gaussian decoder of fixed observation variance \(\tau^2\), the negative reconstruction log-likelihood contains \(\|\boldsymbol{x}-\hat{\boldsymbol{x}}(\boldsymbol{z})\|^2/(2\tau^2)\) plus a normalization constant. Its scale is determined by a declared density model, not silently identified with Part 1’s unweighted MSE.
Example 20.15 (Compute the bound, exact evidence, and gap). Let scalar prior \(z\sim\mathcal N(0,1)\), decoder \(x\mid z\sim\mathcal N(z,1)\), observed \(x=1\), and candidate variational posterior \(q(z\mid1)=\mathcal N(1,1/4)\). Then \[D_{\rm KL}(q\|p)=\tfrac12(1+\tfrac14-1-\log\tfrac14)=0.818147.\] Under \(q\), \(\mathbb{E}[(1-z)^2]/2=1/8\). Including the Gaussian normalization gives ELBO \(=-1/8-\tfrac12\log(2\pi)-0.818147=-1.862086\). The exact marginal is \(x\sim\mathcal N(0,2)\), so \(\log p(1)=-\tfrac12\log(4\pi)-1/4=-1.515512\). The nonnegative gap is \(\tfrac12\log2=0.346574\), equal to the divergence between \(q\) and the exact posterior \(\mathcal N(1/2,1/2)\). These are properties of the specified scalar model and candidate posterior, not measured training results.
The auto-encoding variational Bayes paper introduces this variational/reparameterized approach. A VAE is a probabilistic generative model; an ordinary deterministic autoencoder does not acquire a sampling distribution merely by having a bottleneck.
21 Association Rule Learning
21.1 Market Basket Analysis
Definition 21.1 (Association Rules). Given transactions (sets of items), find rules of the form: \[X \Rightarrow Y\] meaning “if \(X\) is purchased, then \(Y\) is likely to be purchased.”
Example: \(\{\text{bread, butter}\} \Rightarrow \{\text{milk}\}\)
Definition 21.2 (Key Metrics). For nonempty disjoint itemsets \(X,Y\), let \(E_X\) be the event that a transaction contains every item in \(X\) (and similarly for \(Y\)). Then \(E_{X\cup Y}=E_X\cap E_Y\). For rule \(X\Rightarrow Y\):
1. Support: \[\text{support}(X \Rightarrow Y) = P(E_X\cap E_Y) = \frac{\text{transactions containing } X \text{ and } Y}{\text{total transactions}}\] Measures how frequently the rule occurs.
2. Confidence: \[\text{confidence}(X \Rightarrow Y) = P(E_Y\mid E_X) = \frac{\text{support}(X \cup Y)}{\text{support}(X)}\] Measures reliability: if \(X\) is purchased, how often is \(Y\) also purchased?
3. Lift: \[\text{lift}(X \Rightarrow Y) = \frac{P(E_X\cap E_Y)}{P(E_X)P(E_Y)} = \frac{\text{confidence}(X \Rightarrow Y)}{\text{support}(Y)}\] Measures how much more likely \(Y\) is given \(X\) compared to \(Y\) alone.
Lift > 1: \(X\) and \(Y\) are positively correlated
Lift = 1: Independent
Lift < 1: Negatively correlated
Example 21.3 (Market Basket). Store with 1000 transactions:
Bread purchased: 600 times
Milk purchased: 500 times
Bread AND Milk: 400 times
For rule \(\{\text{bread}\} \Rightarrow \{\text{milk}\}\): \[\begin{align} \text{support} &= \frac{400}{1000} = 0.4 \\ \text{confidence} &= \frac{400}{600} = 0.67 \\ \text{lift} &= \frac{0.4}{0.6 \times 0.5} = 1.33 \end{align}\] People who buy bread are 33% more likely to buy milk than average.
21.2 Apriori Algorithm
Theorem 21.4 (Apriori Principle). If an itemset is frequent, then all of its subsets must also be frequent. Equivalently: \[\text{If }X\subseteq Y\text{ and }X\text{ is infrequent, then }Y\text{ is infrequent}\] This allows pruning the search space.
Apriori Algorithm
Input: Transactions \(\mathcal{T}\), minimum support threshold \(\text{minsup}\)
Initialize: \(L_1 = \{\text{frequent 1-itemsets}\}\) (items with support \(\geq\) minsup)
For \(k = 2, 3, \ldots\) until \(L_k = \emptyset\):
Generate candidates: \(C_k = \text{generate}(L_{k-1})\)
Join pairs in \(L_{k-1}\) that share \(k-2\) items
Prune candidates whose \((k-1)\)-subsets are not in \(L_{k-1}\)
Count support: Scan database to count support of each candidate in \(C_k\)
Filter: \(L_k = \{c \in C_k : \text{support}(c) \geq \text{minsup}\}\)
Output: All frequent itemsets \(L = \bigcup_k L_k\)
Generate rules: For each frequent itemset \(X\), use nonempty proper subsets \(\varnothing\ne Y\subsetneq X\) to generate \((X\setminus Y)\Rightarrow Y\), retaining the confidence threshold. Confidence requires positive antecedent support; lift additionally requires positive consequent support.
Apriori Advantages:
Can prune many of the \(2^V\) itemsets over \(V\) distinct items; worst-case candidate growth is still exponential
Guarantees finding all rules above thresholds
Simple and interpretable
Limitations:
Multiple database scans (one per level)
Generates many candidates
Not efficient for very large databases or low support thresholds
FP-Growth: More efficient alternative
Builds compressed data structure (FP-tree)
Only 2 database scans
No candidate generation
Faster than Apriori, especially for large dense datasets
21.3 A Complete Apriori Run and All Qualifying Rules
For itemsets \(A\subseteq B\), every transaction containing \(B\) also contains \(A\). The corresponding event inclusion implies \(\operatorname{support}(B)\le\operatorname{support}(A)\), proving the Apriori pruning principle. This anti-monotonicity concerns support, not a universal ordering of confidence or lift across arbitrary rules.
Example 21.5 (From five transactions to the final rule list). Use the five transactions \[\{A,B,C\},\quad\{A,B\},\quad\{A,C\},\quad\{B,C\},\quad\{B\},\] with minimum support \(0.4\) and minimum confidence \(0.6\). Minimum support count is two. Single-item counts are \(A:3,B:4,C:3\), so all three are frequent. The pair candidates \(AB,AC,BC\) each have count two, hence all survive. Their join generates \(ABC\); every pair subset is frequent, so it is counted rather than pruned before counting. Its count is one and it is rejected. There are no larger frequent itemsets.
The six candidate singleton-to-singleton rules from frequent pairs have the following metrics:
| Rule | Support | Confidence | Lift | Qualifies? |
|---|---|---|---|---|
| \(A\Rightarrow B\) | \(2/5\) | \(2/3\) | \(5/6\) | yes |
| \(B\Rightarrow A\) | \(2/5\) | \(1/2\) | \(5/6\) | no |
| \(A\Rightarrow C\) | \(2/5\) | \(2/3\) | \(10/9\) | yes |
| \(C\Rightarrow A\) | \(2/5\) | \(2/3\) | \(10/9\) | yes |
| \(B\Rightarrow C\) | \(2/5\) | \(1/2\) | \(5/6\) | no |
| \(C\Rightarrow B\) | \(2/5\) | \(2/3\) | \(5/6\) | yes |
Thus exactly four rules pass both thresholds. No rule with union \(ABC\) can pass the support threshold, even if its confidence might be high. The rule \(A\Rightarrow B\) has confidence \(2/3\) yet lift below one, because \(B\) occurs in \(4/5\) of all transactions. High confidence alone can reflect a common consequent rather than positive association. Lift is symmetric under reversing this pair, while confidence is not.
A mined association is not a causal effect or a guaranteed recommendation benefit. Searching many itemsets creates many opportunities for unstable findings. Fix support/confidence choices using training or validation transactions, then evaluate frozen rules on independent or later transactions when the aim is future prediction. Repeated customers, sessions, and temporal availability require the same group/time safeguards as supervised learning.
21.4 Applications
Retail: Product placement, cross-selling, promotions
Web usage mining: Page navigation patterns
Bioinformatics: Gene co-occurrence, protein interactions
Healthcare: Symptom associations, drug interactions
21.5 Summary of Part 5
Clustering: Group similar points. K-means for spherical clusters (fast but needs \(K\)). Hierarchical for dendrograms (intuitive but slow). DBSCAN for arbitrary shapes and noise handling.
Cluster Evaluation: Silhouette score, Davies-Bouldin index (intrinsic). ARI when ground truth available.
PCA: Linear dimensionality reduction via eigendecomposition. Maximizes variance, fast, but linear only. Use for preprocessing and visualization.
LDA: Supervised projection maximizing between/within-class scatter; fit it with training labels only and validate downstream benefit.
t-SNE: Fits local-affinity visualizations; standard coordinates do not specify a new-input mapping. Check sensitivity and neighborhood preservation before interpreting a layout.
UMAP: Neighbor-graph embedding that supports transforming new data. Runtime and preservation of local/global structure depend on data, parameters and implementation.
Autoencoders: Neural network-based non-linear reduction. Flexible but requires training.
Association Rules: Find patterns in transaction data. Apriori algorithm with support/confidence/lift metrics. Applications in retail and beyond.
Next Steps: Part 6 develops evaluation and model selection; Part 7 applies those boundaries to complete pipelines and deployment. Representation-learning extensions in Section 30.2 reuse the autoencoder definitions above.
Exercise 21.6.
For K-means with data \(\{(1,1), (1,2), (5,5), (5,6)\}\) and \(K=2\), starting with centroids at \((1,1)\) and \((5,5)\), perform one complete iteration (assignment + update). What are the new centroids?
Show that the K-means objective \(J\) decreases (or stays the same) in both the assignment step and the update step.
For hierarchical clustering with complete linkage, compute the dendrogram for points \(\{(0,0), (1,0), (0,1), (5,5)\}\) using Euclidean distance.
Given covariance matrix \(\boldsymbol{\Sigma} = \begin{bmatrix} 4 & 2 \\ 2 & 2 \end{bmatrix}\), find the principal components (eigenvectors) and explained variance (eigenvalues).
Explain why PCA requires centering the data (subtracting the mean). What happens if you don’t center?
For transactions: \(\{A,B,C\}, \{A,B\}, \{A,C\}, \{B,C\}, \{B\}\), find all rules with minimum support 0.4 and minimum confidence 0.6.
Compare computational complexity: K-means, hierarchical clustering (complete linkage), and DBSCAN. Which is fastest for \(n=100,000\) points?
When would you use t-SNE vs PCA vs UMAP? Give specific scenarios for each.
Part 6: Model Evaluation & Practical Aspects
22 Model Evaluation Metrics
22.1 Classification Metrics
22.1.1 Confusion Matrix
Definition 22.1 (Confusion Matrix). For binary classification with classes {Positive, Negative}:
| Predicted | ||
| Actual | Positive | Negative |
| Positive | TP | FN |
| Negative | FP | TN |
where:
TP (True Positive): Correctly predicted positive
TN (True Negative): Correctly predicted negative
FP (False Positive): Incorrectly predicted positive (Type I error)
FN (False Negative): Incorrectly predicted negative (Type II error)
Example 22.2 (Medical Diagnosis). Disease detection model tested on 100 patients:
| Predicted | ||
| Actual | Disease | Healthy |
| Disease | 40 | 10 |
| Healthy | 5 | 45 |
TP=40 (correct disease detection), TN=45 (correct healthy), FP=5 (false alarm), FN=10 (missed disease).
22.1.2 Basic Metrics
Definition 22.3 (Classification Metrics). 1. Accuracy: \[\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}\] Proportion of correct predictions overall.
Limitation: Misleading for imbalanced datasets (e.g., 95% negative class \(\to\) predicting all negative gives 95% accuracy).
2. Precision (Positive Predictive Value): \[\text{Precision} = \frac{TP}{TP + FP}\] Of all predicted positives, what fraction are actually positive? “How precise are positive predictions?”
3. Recall (Sensitivity, True Positive Rate): \[\text{Recall} = \frac{TP}{TP + FN}\] Of all actual positives, what fraction did we detect? “How many positives did we recall?”
4. Specificity (True Negative Rate): \[\text{Specificity} = \frac{TN}{TN + FP}\] Of all actual negatives, what fraction did we correctly identify?
5. F1-Score (Harmonic Mean of Precision and Recall): \[F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}} = \frac{2TP}{2TP + FP + FN}\] Balances precision and recall. Useful when both are important.
6. F\(_\beta\)-Score (Generalized): \[F_\beta = (1 + \beta^2) \cdot \frac{\text{Precision} \cdot \text{Recall}}{\beta^2 \cdot \text{Precision} + \text{Recall}}\]
\(\beta = 1\): Equal weight (F1)
\(\beta > 1\): More weight on recall
\(\beta < 1\): More weight on precision
Precision vs Recall Trade-off:
High Precision, Low Recall:
Conservative predictions
Few false alarms (FP), but miss many positives (FN)
Example: Spam filter that rarely flags legitimate email as spam but misses some spam
High Recall, Low Precision:
Aggressive predictions
Catch most positives (low FN), but many false alarms (FP)
Example: Cancer screening that detects most cases but has many false positives
When to prioritize:
Precision: When false positives are costly (e.g., predicting customer will buy expensive item, spam detection)
Recall: When false negatives are costly (e.g., disease detection, fraud detection)
F1: When both matter equally
Example 22.4 (Computing Metrics). From medical diagnosis example (TP=40, TN=45, FP=5, FN=10): \[\begin{align} \text{Accuracy} &= \frac{40+45}{100} = 0.85 \\ \text{Precision} &= \frac{40}{40+5} = 0.889 \\ \text{Recall} &= \frac{40}{40+10} = 0.80 \\ \text{Specificity} &= \frac{45}{45+5} = 0.90 \\ F_1 &= 2 \cdot \frac{0.889 \cdot 0.80}{0.889 + 0.80} = 0.842 \end{align}\]
22.1.3 ROC Curve and AUC
Definition 22.5 (ROC Curve). The Receiver Operating Characteristic (ROC) curve plots:
X-axis: False Positive Rate (FPR) = \(\frac{FP}{FP + TN} = 1 - \text{Specificity}\)
Y-axis: True Positive Rate (TPR) = \(\frac{TP}{TP + FN} = \text{Recall}\)
at various classification thresholds.
For a classifier outputting probability \(p\), vary threshold \(t\): predict positive if \(p \geq t\).
Definition 22.6 (AUC (Area Under the Curve)). AUC-ROC is the area under the ROC curve:
AUC = 1.0: All evaluated positives rank above all negatives; this does not establish probability calibration or performance on unseen populations
AUC = 0.5: Chance-level pairwise ranking; a diagonal ROC is one possible curve with this area
AUC < 0.5: Below chance-level ranking; check label/score orientation on validation data before considering reversal
Interpretation: \(\mathrm{AUC}=P(s_+>s_-)+\tfrac12P(s_+=s_-)\) for independent positive and negative score draws; ties receive half credit.
Advantages of ROC-AUC:
Threshold-independent: Evaluates all possible thresholds
Class-proportion comparison: For fixed class-conditional score distributions, ROC-AUC is invariant to prevalence; it can still conceal poor precision when positives are rare
Single number summary: Easy to compare models
Probabilistic interpretation: Ranking quality
When to use ROC vs PR:
ROC: Balanced classes, care about both classes equally
PR: Imbalanced classes, focus on positive class (more informative)
22.1.4 Precision-Recall Curve
Definition 22.7 (PR Curve). Plots Precision vs Recall at various thresholds.
Emphasizes positive-class precision and recall, often useful for rare positives; the appropriate metric still depends on the decision goal.
Definition 22.8 (AP and mAP). Average Precision (AP): A non-interpolated, recall-weighted sum of precision at successive operating points: \[AP = \sum_{k=1}^n (R_k - R_{k-1}) P_k\] Here thresholds are traversed from high to low so \(R_k\) is nondecreasing, with \(R_0=0\); tied scores are processed together. AP is distinct from trapezoidal interpolation of a PR curve.
Mean Average Precision (mAP): Average AP across multiple classes (used in object detection).
22.1.5 A Complete Ranking and Decision Calculation
A score ranks examples; a probability estimates a conditional frequency; a threshold specifies an action. These are three different evaluation questions. Precision is undefined when \(TP+FP=0\), recall when \(TP+FN=0\), and ROC-AUC requires both classes. Declare any software convention for these cases rather than interpreting a substituted zero as a measured failure.
Example 22.9 (Eight scores, including ties). Use the following fixed teaching sample, with positive label 1: \[(y_i)=(1,0,1,0,1,0,0,1),\qquad (s_i)=(.9,.8,.8,.6,.4,.4,.2,.1).\] Predict \(\hat y_i=\mathbb{1}_{\{s_i\ge t\}}\); tied scores enter together.
| \(t\) | TP | FP | FN | TN | Precision | Recall |
|---|---|---|---|---|---|---|
| \(+\infty\) | 0 | 0 | 4 | 4 | undefined | 0 |
| \(.9\) | 1 | 0 | 3 | 4 | 1 | \(.25\) |
| \(.8\) | 2 | 1 | 2 | 3 | \(2/3\) | \(.50\) |
| \(.6\) | 2 | 2 | 2 | 2 | \(1/2\) | \(.50\) |
| \(.4\) | 3 | 3 | 1 | 1 | \(1/2\) | \(.75\) |
| \(.2\) | 3 | 4 | 1 | 0 | \(3/7\) | \(.75\) |
| \(.1\) | 4 | 4 | 0 | 0 | \(1/2\) | 1 |
There are \(4\cdot4=16\) positive–negative pairs. Positives with scores \(.9,.8,.4,.1\) earn respectively \(4,3.5,1.5,0\) wins (ties count half), giving \[\mathrm{AUC}=\frac9{16}=.5625,\qquad \mathrm{AP}=\frac14\left(1+\frac23+\frac12+\frac12\right)=\frac23.\] Only recall increases contribute to AP. Trapezoidal interpolation of the same PR operating points gives approximately \(.699405\), a different quantity. In Figure 61, precision 1 at zero predicted positives is only a plotting endpoint convention, not an observed ratio.
Proposition 22.10 (Cost-based binary decision). Let \(p(x)=P(Y=1\mid X=x)\) be calibrated for the deployment population, with costs \(c_{FP}>0,c_{FN}>0\) and zero cost for correct decisions. The conditional-risk derivation is in Section 3.4.6. Its rule is to predict positive when \[p\ge \frac{c_{FP}}{c_{FP}+c_{FN}}.\] This rule assumes these costs represent the decision and that there are no additional capacity or abstention constraints.
Example 22.11 (Costs and empirical thresholds). For \(c_{FP}=1,c_{FN}=4\), the probability threshold is \(.2\). On the eight rows, the mean empirical cost \((FP+4FN)/8\) is 1 at \(.2\) and \(.5\) at \(.1\). This finite sample need not favor the population-optimal threshold, especially when its scores are uncalibrated. Select an empirical threshold on a decision validation block, then freeze it before final testing. F1 is a harmonic mean of precision and recall; it does not encode a fixed false-positive to false-negative cost ratio. AUC of \(.5\) means chance-level pairwise ranking on the evaluated distribution; it does not prove the score was randomly generated.
22.1.6 Proper Losses, Calibration, and Prevalence
For binary probabilities \(q_i\), use the sample means \[\mathrm{Brier}=\frac1n\sum_i(q_i-y_i)^2,\qquad \mathrm{NLL}=-\frac1n\sum_i[y_i\log q_i+(1-y_i)\log(1-q_i)].\] This NLL has the same mean scaling as earlier cross-entropy objectives. With true conditional probability \(p\), the expected Brier loss is \((q-p)^2+p(1-p)\), uniquely minimized at \(q=p\). Expected NLL is binary entropy \(H(p)\) plus \(D_{KL}(\mathrm{Bern}(p)\Vert\mathrm{Bern}(q))\); nonnegative KL proves the same minimizer. Numerical clipping must be declared; it changes predictions at the boundary, not the theoretical proper-loss result.
Example 22.12 (Brier, reliability bins, and calibration fitting). Treat the eight scores as candidate probabilities. The squared errors sum to \(2.42\), so Brier is \(.3025\); mean NLL is \(.850885\). Two fixed bins, \([0,.5)\) and \([.5,1]\), each contain four rows. Their mean probabilities are \(.275,.775\), while both positive fractions are \(.5\). Consequently \[\mathrm{ECE}=\sum_b\frac{n_b}{n}|\bar q_b-\bar y_b|=.25.\] ECE depends on bin choices and sample size. In a separate two-row case \(q=(.1,.9),y=(1,0)\), one bin gives ECE zero although Brier is \(.81\). A reliability plot should report bin counts and leave empty bins unestimated.
For a separate calibration sample with increasing scores \((.1,.4,.6,.9)\) and labels \((0,1,0,1)\), isotonic least squares pools the violating middle pair: \((0,.5,.5,1)\). The calibration-training Brier decreases from \(.185\) to \(.125\). This is a fit result, not evidence of improved held-out calibration. Alternatively fit \(q=\sigma(as+b)\) (Platt-style) on a declared score \(s\), or \(q=\sigma(z/T)\), \(T>0\), on logits \(z\). Positive temperature preserves ranking but may change both calibration and decisions. On the eight rows, \(T=2\) lowers Brier to \(.262479\) without changing AUC or AP; choosing \(T\) on these evaluated labels would make that an in-sample comparison.
Example 22.13 (Precision changes with prevalence). For prevalence \(\pi=P(Y=1)\) and fixed class-conditional score distributions, \[P(Y=1\mid\hat Y=1)=\frac{\pi\,\mathrm{TPR}} {\pi\,\mathrm{TPR}+(1-\pi)\,\mathrm{FPR}}.\] At TPR \(.8\), FPR \(.1\), precision is \(8/9\) for \(\pi=.5\) but only \(8/107\approx .07477\) for \(\pi=.01\). ROC-AUC can remain unchanged. Neither a high AUC nor a probability calibrated in the old population promises useful precision after a population shift. If only the class prior changes, with \(P(X\mid Y)\) fixed, posterior odds multiply by \(\{\pi_{new}/(1-\pi_{new})\}/\{\pi_{old}/(1-\pi_{old})\}\). Old probability \(.8\) and priors \(.5\to .1\) then give new probability \(4/13\). This correction requires the label-shift assumption.
22.1.7 Multi-Class Metrics
Definition 22.14 (Multi-Class Extension). For \(K\) classes, confusion matrix is \(K \times K\).
Macro-averaging: Compute metric for each class, then average (treats all classes equally). \[\text{Macro-F1} = \frac{1}{K}\sum_{k=1}^K F1_k\]
Micro-averaging: Pool all TP, FP, FN across classes, then compute the metric; this is not a support-weighted average of classwise metrics. \[\text{Micro-Precision} = \frac{\sum_{k=1}^K TP_k}{\sum_{k=1}^K (TP_k + FP_k)}\]
Weighted-averaging: Weight each class metric by its support (number of true instances).
When to use:
Macro: When all classes are equally important (regardless of size)
Micro: Aggregate instance-level errors; for complete single-label classification it equals accuracy
Weighted: Average class metrics using true-class support; it need not lie between macro and micro
For imbalanced datasets, macro-averaging can reveal poor performance on minority classes that micro-averaging might hide.
22.2 Regression Metrics
Definition 22.15 (Regression Metrics). For predictions \(\hat{y}_i\) and true values \(y_i\):
1. Mean Absolute Error (MAE): \[MAE = \frac{1}{n}\sum_{i=1}^n |y_i - \hat{y}_i|\] Average absolute difference, in the units of \(y\); large residuals incur linear rather than quadratic cost.
2. Mean Squared Error (MSE): \[MSE = \frac{1}{n}\sum_{i=1}^n (y_i - \hat{y}_i)^2\] Penalizes large errors heavily. Not in original units.
3. Root Mean Squared Error (RMSE): \[RMSE = \sqrt{MSE} = \sqrt{\frac{1}{n}\sum_{i=1}^n (y_i - \hat{y}_i)^2}\] Same scale as \(y\). More interpretable than MSE.
4. Mean Absolute Percentage Error (MAPE): \[MAPE = \frac{100\%}{n}\sum_{i=1}^n \left|\frac{y_i - \hat{y}_i}{y_i}\right|\] Scale-independent. Undefined when \(y_i = 0\).
5. R2 (Coefficient of Determination): \[R^2 = 1 - \frac{SS_{\text{res}}}{SS_{\text{tot}}} = 1 - \frac{\sum_i(y_i - \hat{y}_i)^2}{\sum_i(y_i - \bar{y})^2}\] where \(\bar{y} = \frac{1}{n}\sum_i y_i\).
\(R^2 = 1\): Perfect predictions
\(R^2 = 0\): Model no better than predicting mean
\(R^2<0\): Worse than predicting the evaluation-set mean; this can occur for linear or nonlinear models on held-out data
Measures proportion of variance explained by the model.
MAE vs MSE/RMSE:
MAE:
Less sensitive to large residuals than squared error, but still unbounded
All errors weighted equally
Easier to interpret
MSE/RMSE:
Sensitive to outliers (large errors penalized heavily)
MSE is differentiable everywhere; RMSE, a scaled residual-vector norm, is not differentiable at the zero residual vector
Common in statistical theory
When a linear residual penalty matches the goal: Consider MAE; investigate measurement errors and the evaluation population separately
When large errors are particularly bad: Use MSE/RMSE
R2 advantages:
Invariant to a common affine rescaling of targets and predictions; different target distributions and baselines still limit comparisons
Intuitive (percentage of variance explained)
R2 limitations:
For nested unregularized OLS fits with an intercept on the same training data, training \(R^2\) cannot decrease as features are added; this guarantee does not extend to test \(R^2\)
Can be negative on held-out data for linear or nonlinear models; it is undefined by this formula when the evaluation targets are constant
Doesn’t indicate if model is appropriate
22.3 Aggregation, Estimation Targets, and Uncertainty
Example 22.16 (Multi-class aggregation calculated completely). Rows are true classes and columns predicted classes in \[C=\begin{pmatrix}8&1&1\\1&1&0\\0&1&1\end{pmatrix}.\] Supports are \((10,2,2)\), predicted counts \((9,3,2)\), and per-class F1 values are \((16/19,2/5,1/2)\). Thus macro-F1 is \(.580702\), support-weighted F1 is \(.730075\), and accuracy is \(10/14=.714286\). In single-label classification over all classes, every incorrect prediction adds one pooled FP and one pooled FN. Hence micro-precision, micro-recall, and micro-F1 all equal accuracy. Weighted F1 need not lie between macro-F1 and micro-F1, as this example shows. Macro-F1 is the average of class F1s, not the harmonic mean of separately macro-averaged precision and recall.
Proposition 22.17 (Why squared and absolute errors estimate different targets). For a constant prediction \(a\) and finite second moment, \(\mathbb{E}(Y-a)^2=\mathrm{Var}(Y)+(a-\mathbb{E}Y)^2\), so squared error is minimized at the mean. For absolute error, a subgradient of \(\mathbb{E}|Y-a|\) includes zero exactly when \(P(Y\le a)\ge1/2\) and \(P(Y\ge a)\ge1/2\): any median minimizes it. These are conditional means and medians when predicting from \(X=x\).
Example 22.18 (A rare large response). Let \(P(Y=0)=.8\), \(P(Y=10)=.2\). The mean is 2 and the median is 0. Predictions 0 and 2 have expected squared losses 20 and 16, but expected absolute losses 2 and 3.2. MAE penalizes large residuals linearly rather than quadratically; it is still unbounded. MAPE is undefined at a zero target and can be dominated by targets near zero. Report its denominator convention. On a separate test set \(y=(0,1,2)\), predicting zero gives SSE 5 and the constant test-mean baseline gives SST 2, hence \(R^2=1-5/2=-1.5\). The test mean defines this evaluation denominator; it is not a predictor that was fitted with test labels.
22.3.1 Intervals Must Match the Sampling Unit
Example 22.19 (Wilson interval and a paired comparison). For \(k\) correct predictions in \(n\) independent Bernoulli trials, invert the score-test inequality \((\hat p-p)^2\le z^2p(1-p)/n\). The Wilson interval is \[\frac{\hat p+z^2/(2n)\ \pm\ z\sqrt{\hat p(1-\hat p)/n+z^2/(4n^2)}} {1+z^2/n}.\] With \(k=85,n=100,z=1.96\), this is \([.76716,.90694]\), an approximate 95% interval under those assumptions. Repeated observations of the same device do not supply 100 independent trials merely because there are 100 rows.
Suppose two classifiers evaluated on the same eight independent cases have 4 and 7 correct predictions: three cases improve and none worsen. The exact two-sided McNemar/binomial test conditional on these three discordant cases has \(p=2(1/2)^3=.25\). A visible accuracy difference can have considerable uncertainty. Paired bootstrap comparisons resample the same case indices for both models; group bootstrap resamples whole independent groups. Neither method justifies treating overlapping CV fold scores as independent replicates.
For unequal validation fold sizes \(n_k\), a pooled mean loss is \(\sum_k n_k\bar\ell_k/\sum_k n_k\), whereas an unweighted fold mean estimates an average over folds. They coincide for equal sizes. For nonlinear metrics, even size weighting need not reproduce the metric of pooled predictions: compute pooled F1 from pooled confusion counts. Repeated searches, dependence, and temporal shifts create additional uncertainty. A bootstrap with a frozen predictor measures evaluation-sample uncertainty conditional on that predictor; it does not include variability from retraining and model selection.
22.3.2 A Finite-Sample Prediction Interval
Example 22.20 (Split conformal, including the small-sample edge case). Fit a regression model on training data and use a separate exchangeable calibration sample of size \(m=5\). Absolute residual scores are \((.1,.2,.2,.4,.8)\). For miscoverage \(\alpha=.2\), use order statistic \(k=\lceil(m+1)(1-\alpha)\rceil=5\), hence \(q=.8\) and prediction interval \([\hat f(x)-q,\hat f(x)+q]\). A prediction 3 gives \([2.2,3.8]\). Exchangeability makes the test score’s rank uniform in the absence of ties; conservative handling of ties yields marginal coverage at least \(1-\alpha\). It is not conditional coverage for every input or group. If \(\alpha=.1\), then \(k=6>m\): the valid general convention is \(q=+\infty\), not clipping the index to 5 and claiming 90% coverage. An arbitrary future time block is not exchangeable with past residuals, so this guarantee does not automatically apply to the device workflow below. See Angelopoulos and Bates’ conformal tutorial.
23 Model Selection and Hyperparameter Tuning
23.1 Cross-Validation
23.1.1 Splitting Units and Fitting the Whole Procedure
The protocol introduced in Section 1.3 evaluates a procedure: every learned transformation, model fit, hyperparameter search, and threshold choice that will be applied to new data. Splitting rows is appropriate only when rows are the independent units relevant to deployment. Use group-disjoint folds for new patients/users/devices, and forward temporal splits for future prediction. A stratified random split preserves class proportions but does not enforce either requirement.
Example 23.1 (A group split and an availability check). Suppose patients A, B, C, D each have five visits. For prediction on new patients, a valid holdout might use A/B/C for training and D for testing, keeping all five D visits outside training. Randomly placing one D visit in the test set and four in training measures a different scenario. For forecasting at time \(t\), a seven-day summary must use data available by \(t\), not days \(t+1\) through \(t+7\). If the target covers the next seven days, adjacent training and validation targets may overlap; choose a gap or purge the overlapping training labels according to their actual end times. A fixed gap is not a substitute for checking these windows.
An executable split–search–refit–test example
from sklearn.datasets import load_iris
from sklearn.model_selection import (
train_test_split, StratifiedKFold, GridSearchCV
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
procedure = Pipeline([
("scale", StandardScaler()),
("model", LogisticRegression(max_iter=1000))
])
folds = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
search = GridSearchCV(
procedure, {"model__C": [0.1, 1.0, 10.0]},
cv=folds, scoring="accuracy", refit=True
)
search.fit(X_train, y_train)
# Each CV fit learns its own scaler. refit=True then fits
# the selected whole pipeline on all 120 non-test examples.
print(search.best_params_)
print(search.score(X_test, y_test)) # one final test evaluationThis demonstration has 9 candidate/fold fits and one final refit. Do not use the printed test score to revise the grid or procedure. Iris rows are treated as independent for this example; replace the splitter and supply group/time information when the application requires it. The numerical value of \(C\) follows the estimator’s documented convention, not the custom ridge \(\lambda\) convention in Part 1.
The scikit-learn leakage guide explains why a pipeline is the safe unit of cross-validation. Its cross-validation documentation describes stratified, group-aware, and temporal alternatives. A splitter encodes the intended evaluation population; a pipeline enforces the fitting boundary after those splits.
23.1.2 K-Fold Cross-Validation
Definition 23.2 (K-Fold Cross-Validation). For \(2\le K\le n\), validation folds form a partition of the current fitting sample, and each fit excludes its validation fold. Ordinary K-fold sizes differ by at most one; the complete fitting algorithm is given below. Choosing \(K\) and reporting aggregate scores must respect the sampling units and metric conventions in Section 22.3.
K-Fold Cross-Validation
Input: Data \(\mathcal{D}\), model/hyperparameters, \(K\)
Split \(\mathcal{D}\) into \(K\) approximately equal-sized folds: \(\{\mathcal{D}_1, \ldots, \mathcal{D}_K\}\)
For \(k = 1\) to \(K\):
\(\mathcal{D}_{\text{train}} = \mathcal{D} \setminus \mathcal{D}_k\)
\(\mathcal{D}_{\text{val}} = \mathcal{D}_k\)
Fit learned preprocessing on \(\mathcal{D}_{\text{train}}\) only; transform both folds with those fitted statistics
Train model on the transformed \(\mathcal{D}_{\text{train}}\)
Evaluate on \(\mathcal{D}_{\text{val}}\), record score \(M_k\)
Compute average score: \(\bar{M} = \frac{1}{K}\sum_{k=1}^K M_k\)
(Optional) Compute standard deviation: \(\sigma_M = \sqrt{\frac{1}{K}\sum_{k=1}^K (M_k - \bar{M})^2}\)
Output: Mean score \(\bar{M}\) and std \(\sigma_M\)
Why Cross-Validation?
Problem with single train/val split:
High variance (depends on random split)
Wastes data (validation set not used for training)
May not be representative
CV advantages:
Lower variance estimate
Uses all data for both training and validation
Fold scores describe split-to-split variation, but their standard deviation is not a confidence interval: training-fold overlap induces dependence
More reliable for model selection
Choosing \(K\):
Small \(K\) (e.g., 3): Fewer fits and less training data per fit; the error estimate may be more pessimistic
Large \(K\) (e.g., 10): More fits and more training data per fit; uncertainty depends on model stability and correlations between folds
\(K=n\) (LOOCV): Trains on \(n-1\) samples per fit; often costly, with highly overlapping training sets. Its variance is not universally larger or smaller than other CV schemes
Common choice: \(K = 5\) or \(10\) (good trade-off)
23.1.3 Stratified K-Fold
Definition 23.3 (Stratified K-Fold). For classification, ensure each fold has approximately the same class distribution as the full dataset.
Particularly important for:
Imbalanced datasets
Small datasets
Multi-class problems
Example 23.4 (Stratified Split). Dataset: 100 examples, 80 class A, 20 class B (80/20 split).
Regular 5-fold: Some folds might have 70/30 or 90/10 (random variation).
Stratified 5-fold: Each fold has exactly 16 class A, 4 class B (80/20 maintained).
23.1.4 Time Series Cross-Validation
Definition 23.5 (Time Series Split). For temporal data, cannot randomly shuffle (violates temporal order).
Forward chaining:
Fold 1: Train on \([1:n_1]\), validate on \([n_1+1:n_2]\)
Fold 2: Train on \([1:n_2]\), validate on \([n_2+1:n_3]\)
Fold 3: Train on \([1:n_3]\), validate on \([n_3+1:n_4]\)
...
Train on the past and validate on future observations. This ordering alone does not prevent leakage: feature windows, preprocessing, label availability and any necessary train-validation gap must also respect the forecast time.
23.2 A Protocol That Includes Calibration and Decisions
The training/validation/test terminology of Part 0 describes information roles. A validation role can require several disjoint blocks when several operations learn from labels. The following conservative example separates four roles:
TRAIN: search hyperparameters with fold-local preprocessing, then refit the selected base pipeline on TRAIN.
CALIBRATION: fit a probability map to the frozen base scores.
POLICY: choose the cost threshold of the frozen calibrated model.
TEST: report the complete frozen procedure and prespecified baselines.
Do not refit the base model after fitting its calibrator and threshold: that changes their score distribution. If refitting on additional non-test data is required, do it before allocating fresh calibration and policy data, or design a suitable cross-fitting protocol. A calibrator is a learned model; a selected threshold is a learned decision rule. Neither belongs on final test labels.
Example 23.6 (Groups, time, and label availability together). The runnable device example uses 260 synthetic devices, three visits each. Device \(g\) has event times \(10g,10g+1,10g+2\) and labels available two time units later. Predeclared blocks contain devices 0–119, 120–159, 160–199, and 200–259: 360, 120, 120, and 180 rows respectively. This evaluates future unseen devices; it is a different target from future visits to known devices. Device identity and times are split metadata, not predictors.
Within TRAIN, three expanding splits each validate on 20 complete devices and exclude a one-device gap. Exact sizes and boundaries are:
| Fold | Train rows | Validation rows | Last training label ready | First validation event |
|---|---|---|---|---|
| 1 | 177 | 60 | 584 | 600 |
| 2 | 237 | 60 | 784 | 800 |
| 3 | 297 | 60 | 984 | 1000 |
All training labels are available before the validation origin and device IDs are disjoint. The gap is measured in devices in this construction; a library row gap is not automatically a duration or a group gap. If a forecast label uses a horizon of two days, require its entire label window to end before the validation origin. At origin day 5, labels ending at day \(t+2\) are available strictly before day 5 only for integer \(t\le2\). Use availability timestamps, not just row ordering. For rolling deployment to known devices, allow their available past histories but never future observations; the split target must match the deployment question.
Example 23.7 (What the nested audit actually estimates). Six \((C,\text{class weight})\) settings and three forward folds cost \(6\cdot3+1=19\) base-model fits including the final TRAIN refit. The calibrator adds one fit; evaluating nine policy thresholds adds no base-model fits. A separate audit confined to TRAIN uses three outer folds and two inner folds: \(3(6\cdot2+1)=39\) base fits. Its held-out outer mean log losses are \(.480678,.476870,.607009\), with mean \(.521519\). Each outer search happens to choose \(C=10\) and no class weighting. The main search selects the same setting and has the same mean score; nesting does not guarantee a numerically worse score on every dataset. This audit estimates base-pipeline hyperparameter selection, not the full calibration-and-policy procedure. Auditing the latter requires fitting all those stages inside each outer training portion. The final 180-row TEST evaluates the full frozen system.
23.3 Hyperparameter Tuning
23.3.1 Grid Search
Definition 23.8 (Grid Search). Exhaustively search over a specified hyperparameter grid.
Example: For SVM with RBF kernel:
\(C \in \{0.1, 1, 10, 100\}\)
\(\gamma \in \{0.001, 0.01, 0.1, 1\}\)
Test all \(4 \times 4 = 16\) combinations.
Grid Search with Cross-Validation
Input: Training data \(\mathcal{D}\), model, hyperparameter grid, \(K\) for CV
Generate all combinations of hyperparameters from grid
For each combination \(\theta\):
Run \(K\)-fold CV with hyperparameters \(\theta\)
Record mean CV score \(\bar{M}(\theta)\)
Select best: \(\theta^* = \mathop{\mathrm{arg\,max}}_\theta \bar{M}(\theta)\)
Refit the selected base procedure on its designated fitting block with \(\theta^*\). If calibration or threshold selection is needed, retain their separate non-test blocks. Freeze every stage before evaluating on the untouched test set
Output: Best hyperparameters \(\theta^*\), trained model
Grid Search Advantages:
Simple, easy to implement
Guaranteed to find best combination in grid
Parallelizable (each combination independent)
Reproducible
Limitations:
Curse of dimensionality: \(n\) parameters with \(k\) values each \(\to\) \(k^n\) combinations
Wastes computation on unpromising regions
Grid may miss optimal values between grid points
Expensive for large grids or slow models
Best practices:
Start with coarse grid, then refine around best values
Use logarithmic spacing for parameters spanning orders of magnitude
Limit grid size (test 3-5 values per parameter max)
23.3.2 Random Search
Definition 23.9 (Random Search). Sample hyperparameter combinations randomly from specified distributions.
Instead of grid, define distributions:
\(C \sim \text{LogUniform}(10^{-3}, 10^3)\)
\(\gamma \sim \text{LogUniform}(10^{-4}, 10^1)\)
Sample \(n\) random combinations, evaluate each.
Intuition 301 (Random Search Coverage). Random search is often more efficient than grid search because:
Some hyperparameters matter more than others
Random search explores more unique values for important parameters
May cover relevant coordinates more finely under a suitable search distribution; no universal performance ordering follows
For \(n\) trials with independent continuous parameter distributions (discrete values can repeat):
Grid search with 2 parameters: \(\sqrt{n} \times \sqrt{n}\) grid
Random search: Almost surely \(n\) distinct sampled values per continuous parameter; no such guarantee holds for discrete parameters
Random Search in Practice:
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import loguniform, randint
# Define distributions
param_distributions = {
'C': loguniform(1e-3, 1e3),
'gamma': loguniform(1e-4, 1e1),
'kernel': ['rbf', 'poly']
}
# Random search with 100 iterations
random_search = RandomizedSearchCV(
estimator=SVC(),
param_distributions=param_distributions,
n_iter=100, # number of random samples
cv=5,
random_state=42,
n_jobs=-1 # parallel
)
random_search.fit(X_train, y_train)
best_params = random_search.best_params_23.3.3 Bayesian Optimization
Definition 23.11 (Bayesian Optimization). Intelligent search that uses past evaluations to guide future trials.
Key idea:
Build probabilistic model (surrogate) of \(f(\theta)\) where \(\theta\) are hyperparameters
Use model to select promising \(\theta\) (acquisition function)
Evaluate \(f(\theta)\), update model
Repeat
Common surrogate: Gaussian Process (GP)
Common acquisition functions:
Expected Improvement (EI): Balance exploration/exploitation
Upper Confidence Bound (UCB): \(\mu(\theta) + \kappa\sigma(\theta)\)
Bayesian Optimization vs Random/Grid:
Advantages:
Can improve sample efficiency when the surrogate and acquisition assumptions suit the objective
Learns from past trials
Handles expensive black-box functions well
Can incorporate prior knowledge
Disadvantages:
More complex to implement
Overhead in building surrogate model
Less parallelizable
Can get stuck in local optima
When to use:
Expensive evaluations (training takes hours)
Limited budget (can only try 10-50 configurations)
Continuous hyperparameters
Black-box optimization
Popular libraries: Optuna, Hyperopt, Scikit-Optimize, Ray Tune
23.4 Nested Cross-Validation
Definition 23.12 (Nested CV). To estimate the performance of the entire hyperparameter-selection procedure using held-out outer folds:
Outer loop (performance estimation):
\(K_{\text{outer}}\)-fold CV
Inner loop (hyperparameter selection):
For each outer fold, run \(K_{\text{inner}}\)-fold CV on training portion
Select best hyperparameters
Refit the selected entire procedure on the outer training portion, then evaluate on the untouched outer fold
This separates tuning from evaluation, reducing the selection optimism caused by reusing validation scores. Each outer model uses less data than the final all-non-test-data fit, so the result is not an exactly unbiased estimate of that final model’s risk. Learned preprocessing must be fitted inside the inner folds and refitted on the outer training portion; outer scores must not guide further tuning without a new evaluation boundary.
23.5 Search Budgets and Acquisition Functions
Example 23.13 (Random-search coverage and minimization EI). If each independent random configuration has probability \(q\) of landing in a prespecified useful region, \(B\) trials hit it with probability \(1-(1-q)^B\). For \(q=.05\), this is \(.6415\) at \(B=20\) and \(.9539\) at \(B=60\). This describes coverage under the chosen search distribution, not guaranteed superiority to a grid or guaranteed held-out performance.
For minimizing validation loss, assume a surrogate predicts \(F(\theta)\sim N(\mu,\sigma^2)\) and the current best loss is \(f_*\). With improvement margin \(\xi\ge0\), integrate the positive part \(I=(f_*-\xi-F)_+\) to obtain \[\mathrm{EI}(\theta)=(f_*-\xi-\mu)\Phi(z)+\sigma\phi(z),\qquad z=\frac{f_*-\xi-\mu}{\sigma}.\] For \(\sigma=0\) use \((f_*-\xi-\mu)_+\). At \(f_*=.2,\xi=0\), assumed predictions \(N(.18,.03^2)\) and \(N(.22,.05^2)\) yield EI approximately \(.024534\) and \(.011522\): a worse predicted mean can still have positive EI. Maximize EI while minimizing the underlying loss. An optimistic confidence bound for minimization is a lower bound \(\mu-\kappa\sigma\); the previous upper-bound form applies to reward maximization. Surrogate quality, noise, and budget determine whether this search is useful.
24 Data Preprocessing
Apply the splitting and fold-local fitting rules in Sections 1.3 and 23.1.1 to every learned preprocessing step below. Fit statistics on the current training fold, transform its validation fold without refitting, and repeat from scratch in the next round.
24.1 Feature Scaling
24.1.1 Standardization (Z-score Normalization)
Definition 24.1 (Standardization). Transform features to have mean 0 and standard deviation 1: \[x_{\text{scaled}} = \frac{x - \mu}{\sigma}\] where \(\mu = \frac{1}{n}\sum_i x_i\) and \(\sigma = \sqrt{\frac{1}{n}\sum_i (x_i - \mu)^2}\).
For a nonconstant training feature, these fitted statistics give training empirical mean zero and population-form empirical variance one. They do not force held-out data to have mean zero or variance one, and do not make a non-Gaussian distribution Gaussian. A truly Gaussian population becomes exactly \(\mathcal N(0,1)\) only when transformed using its true population mean and standard deviation. Constant features need a separate convention.
Definition 24.2 (Min-Max Normalization). Scale features to a fixed range, typically \([0, 1]\): \[x_{\text{scaled}} = \frac{x - x_{\min}}{x_{\max} - x_{\min}}\]
Fit the minimum and maximum on training data only, and require \(x_{\max}>x_{\min}\) (constant features need a separate convention). New observations outside the training range can transform outside \([0,1]\) unless explicitly clipped.
For range \([a,b]\): \[x_{\text{scaled}} = a + (b - a) \cdot \frac{x - x_{\min}}{x_{\max} - x_{\min}}\]
When to use which:
Standardization:
Features have different units/scales
Many ML algorithms (SVM, logistic regression, neural networks)
Mean and standard deviation are meaningful summaries; they are sensitive to outliers, so heavy contamination may call for robust scaling
Preserves outlier information (can go beyond \([0,1]\))
Min-Max:
Need bounded range (e.g., \([0,1]\))
Neural networks (especially with bounded activations like sigmoid)
Image data (pixel values)
Zero is preserved only when it coincides with the chosen lower reference for the transform
When NOT to scale:
Exact threshold-based trees depend on feature order, so strictly monotone feature transformations preserve available partitions; numerical and approximate split procedures can differ
Features already on same scale
Interpretability matters (keep original units)
Critical: Fit on Training, Transform on Test
from sklearn.preprocessing import StandardScaler
# Correct way
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) # Use training statistics
# Wrong way (data leakage!)
# scaler.fit(X_test) # Never fit on test data!Why? Under ordinary inductive evaluation, learned statistics exclude test inputs. A declared descriptive/transductive analysis has a different scope, as discussed in Section 18.1.
24.2 Encoding Categorical Variables
24.2.1 Label Encoding
Definition 24.3 (Label Encoding). Map categories to integers: \[\text{Red} \to 0, \quad \text{Green} \to 1, \quad \text{Blue} \to 2\]
Issue: Introduces artificial ordering (\(\text{Blue} > \text{Green} > \text{Red}\)).
When to use:
Ordinal variables (Low \(<\) Medium \(<\) High)
For feature columns, use an ordinal encoder when an ordering is meaningful. Arbitrary integer codes impose an artificial order on numerical-threshold trees; native categorical split support is implementation-specific
Target variable in classification
24.2.2 One-Hot Encoding
Definition 24.4 (One-Hot Encoding). Create binary column for each category:
| Original | Red | Green | Blue |
|---|---|---|---|
| Red | 1 | 0 | 0 |
| Green | 0 | 1 | 0 |
| Blue | 0 | 0 | 1 |
For \(K\) categories, use \(K\) binary features, or a \(K-1\) reference encoding when needed for identifiability with an unpenalized intercept. Dropping a category is not compulsory for every regularized or tree-based model.
One-Hot Advantages:
No artificial ordering
Works with linear models
Standard approach for neural networks
Limitations:
High cardinality: Many categories \(\to\) many features
Sparse matrices: Most values are 0
Curse of dimensionality: \(K\) categories = \(K\) new dimensions
Alternatives for high cardinality:
Target encoding: Replace a category with a training-estimated target statistic; use out-of-fold or ordered estimates to avoid leaking a row’s own target
Frequency encoding: Replace with category frequency
Embedding layers: Neural network learns dense representations (NLP, RecSys)
Hashing trick: Hash categories to fixed number of buckets
24.3 Handling Missing Data
Definition 24.5 (Types of Missingness). 1. MCAR (Missing Completely At Random):
Missingness independent of observed and unobserved data
Example: Responses lost by a failure independent of response content and participant attributes
2. MAR (Missing At Random):
Conditional on observed data, missingness does not further depend on the missing values
Example: Older people less likely to report income (age is observed)
3. MNAR (Missing Not At Random):
Missingness depends on unobserved data
Example: High earners don’t report income (income itself causes missingness)
Definition 24.6 (Handling Strategies). 1. Deletion:
Listwise: Remove entire row if any feature missing
Pairwise: Use available data for each analysis
Assessment: Complete-case validity depends on the missingness mechanism and analysis; there is no universal 5% safety rule
2. Imputation:
Mean/Median/Mode: Simple, fast, but ignores relationships
Forward/Backward fill: Respect the prediction time. Backward fill uses future observations and is inappropriate when those observations would be unavailable at forecasting time
KNN imputation: Use \(k\) nearest neighbors’ values
Model-based: Regression, EM algorithm, MICE
Indicator variable: Add binary flag for missingness (preserves information)
3. Model-Specific:
Some algorithms handle missing values natively (XGBoost, LightGBM)
Imputation Best Practices:
from sklearn.impute import SimpleImputer, KNNImputer
# Simple imputation
imputer = SimpleImputer(strategy='mean') # or 'median', 'most_frequent'
X_train_imputed = imputer.fit_transform(X_train)
X_test_imputed = imputer.transform(X_test)
# KNN imputation (more sophisticated)
knn_imputer = KNNImputer(n_neighbors=5)
X_train_imputed = knn_imputer.fit_transform(X_train)Remember: Always fit imputer on training data only!
24.4 Outlier Detection and Treatment
Definition 24.7 (Outlier Detection Methods). 1. Statistical:
Z-score: \(|z| > 3\) (assuming Gaussian)
IQR method: Below \(Q_1 - 1.5 \cdot IQR\) or above \(Q_3 + 1.5 \cdot IQR\)
2. Distance-based:
DBSCAN: Points marked as noise
KNN: Points with large distance to \(k\)-th neighbor
3. Model-based:
Isolation Forest: Isolates outliers in random trees
One-Class SVM: Learns boundary around normal data
Local Outlier Factor (LOF): Compares local density
Handling Outliers:
1. Investigate first:
Data error (typo, measurement error)? \(\to\) Correct or remove
Valid extreme value? \(\to\) Keep (important information)
2. Treatment options:
Keep: If valid and informative
Remove: Only under a declared error/eligibility rule defining the target population; do not remove held-out rows after inspecting their labels or prediction errors
Cap/Winsorize: Replace with threshold (e.g., 95th percentile)
Transform: Log, square root to reduce impact
Separate model: Build model specifically for outliers
3. Model robustness:
Robustness depends on the perturbation: Trees are insensitive to strictly monotone feature rescaling, but squared-error leaf means can be sensitive to extreme targets; Huber loss limits large-residual influence
Sensitive models: Linear regression, KNN, SVM (need preprocessing)
25 Feature Engineering
25.1 Feature Extraction vs Selection
Definition 25.1 (Feature Engineering). Feature Extraction: Create new features from existing ones
PCA: Linear combinations
Polynomial features: \(x_1 \cdot x_2\), \(x_1^2\)
Domain-specific transformations
Feature Selection: Choose subset of existing features
Remove irrelevant or redundant features
Improve model performance and interpretability
Reduce overfitting and training time
25.2 Feature Selection Methods
25.2.1 Filter Methods
Definition 25.2 (Filter Methods). Select features based on statistical measures, independent of model.
1. Correlation: Remove features highly correlated with each other (redundant).
2. Mutual Information: \[MI(X, Y) = \sum_{x,y} P(x,y) \log\frac{P(x,y)}{P(x)P(y)}\] This is the discrete-variable formula; continuous variables require the corresponding density integral and an appropriate estimator. It measures dependence, including nonlinear dependence, rather than a causal effect.
3. Chi-Square Test: For categorical features and classification: \[\chi^2 = \sum_{i,j} \frac{(O_{ij} - E_{ij})^2}{E_{ij}}\] Tests independence between feature and target.
4. ANOVA F-test: For continuous features and categorical target. Tests if feature means differ across classes.
Filter Methods:
Advantages:
Fast (no model training)
Model-agnostic
Good for preprocessing
Limitations:
Ignores feature interactions
Doesn’t consider model performance
May select redundant features
25.2.2 Wrapper Methods
Definition 25.3 (Wrapper Methods). Use model performance to guide feature selection.
1. Forward Selection:
Start with no features
Add one feature at a time (choose best improvement)
Stop when no improvement
2. Backward Elimination:
Start with all features
Remove one feature at a time (remove worst)
Stop when removal hurts performance
3. Recursive Feature Elimination (RFE):
Train model on all features
Rank features by importance
Remove least important
Repeat until desired number of features
Recursive Feature Elimination (RFE)
Input: Features \(\boldsymbol{X}\), target \(\boldsymbol{y}\), model, target feature count \(k\)
Initialize: Current feature set \(\mathcal{F} = \{\text{all features}\}\)
While \(|\mathcal{F}| > k\):
Train model on features in \(\mathcal{F}\)
Compute feature importances (e.g., coefficients, Gini importance)
Remove the least important feature from \(\mathcal{F}\); for coefficient-based ranking account for feature scale and use magnitude rather than signed coefficient
Output: Selected features \(\mathcal{F}\). For performance evaluation, repeat feature selection within each training fold; do not select using held-out labels.
Wrapper Methods:
Advantages:
Sequential wrappers can use validation performance; ordinary RFE ranks fitted-model importances, while RFECV uses CV to select the retained count
Can capture feature interactions
Optimizes for specific model
Limitations:
Computationally expensive (many model trainings)
Risk of overfitting (especially with small data)
Model-specific (selected features may not work for other models)
25.2.3 Embedded Methods
Definition 25.4 (Embedded Methods). Feature selection built into model training.
1. L1 Regularization (Lasso): Penalty \(\lambda\sum_j |w_j|\) drives some weights to exactly zero.
2. Tree-based Feature Importance: Random Forest, XGBoost provide importance scores. Select top \(k\) features.
3. ElasticNet: Combines L1 (sparsity) and L2 (grouping) penalties.
Embedded Methods:
Advantages:
Faster than wrapper methods
Less overfitting risk
Integrated with training
Best Practice:
Start with filter methods (fast preprocessing)
Use embedded methods if model supports (L1, tree importance)
Use wrapper methods for critical applications with budget
25.3 Domain-Specific Feature Engineering
Example 25.5 (Common Transformations). 1. Time Features (from datetime):
Hour, day of week, month, year
Is weekend? Is holiday?
Time since event
Cyclic encoding: \(\sin(2\pi \cdot \text{hour}/24)\), \(\cos(2\pi \cdot \text{hour}/24)\)
2. Text Features:
Bag of words, TF-IDF
N-grams
Length, number of words, capitals
Sentiment scores
Word embeddings (Word2Vec, GloVe)
3. Geospatial:
Distance to landmark
Cluster of locations
Urban vs rural classification
4. Interaction Features:
Products: \(x_1 \cdot x_2\)
Ratios: \(x_1 / x_2\)
Differences: \(x_1 - x_2\)
5. Aggregations (for grouped data):
Mean, median, std per group
Count, min, max per group
Time-based: rolling averages, lag features
25.4 Preprocessing and Feature Availability: An Auditable Example
Example 25.6 (Fit statistics on precisely the current training block). For training numeric values \((1,\mathrm{missing},3)\), the fitted median is 2. After imputation the mean is 2 and the population standard deviation used by StandardScaler is \(\sqrt{2/3}\). A held-out value 5 transforms to \(3/\sqrt{2/3}\); it does not change that mean or standard deviation. A held-out missing value transforms to zero after median imputation.
For training categories blue and red, one-hot columns are fixed by training. With handle_unknown=’ignore’, unseen green maps to an all-zero vector. That is a declared fallback, not a learned effect for green. Dropping a reference category can make its representation indistinguishable from an unknown category. Missing categories need their own explicit policy. The runnable example permits missing numerics but requires a nonempty category; it retains all request rows and their order.
Let \(R\) denote an observation indicator. MAR means the conditional law of \(R\) given all data depends only on the observed portion, equivalently an appropriate conditional independence from the missing values given observed values. It does not mean marginal independence from every unobserved variable. An independent random server failure could produce MCAR; a failure associated with device load may not. Neither a low missing fraction nor MAR by itself licenses unbiased complete-case analysis. A missingness mechanism generally cannot be identified from the observed sample alone.
Example 25.7 (Selection and temporal joins can leak before a Pipeline). Suppose an identifier appears in both folds, or a feature table contains “number of failures in the next week.” A perfectly fold-local scaler cannot repair either issue. At prediction time \(t\), a joined record must have both its event time and its availability time no later than \(t\). Use an as-of join against a versioned history, not the latest corrected table.
For a current-outcome task, a within-device rolling average of past outcomes requires sorting, grouping, and a lag before rolling. In pandas, for outcomes that were available by the next visit, one possible expression is
history = history.sort_values(['device_id', 'event_time'])
history['past_mean'] = history.groupby('device_id')['target'].transform(
lambda s: s.shift(1).rolling(3, min_periods=1).mean())With delayed labels, the lag alone is insufficient: filter by label-availability time for each query. In the future-unseen-device protocol, previous training devices’ outcomes cannot be used as the new device’s history. Keep split IDs, feature timestamps, and availability checks outside the model’s public inputs.
Example 25.8 (A univariate selector can discard the whole signal). Let \(X_1,X_2\) be independent fair bits and \(Y=X_1\mathbin{\mathrm{XOR}}X_2\). Each single feature has \(I(X_j;Y)=0\), but the pair determines \(Y\), so \(I((X_1,X_2);Y)=H(Y)=\log2\). An aggressive univariate filter removes both useful features. Feature selection must be tuned inside the training folds; filter methods do not inherently prevent leakage or preserve interactions. The scikit-learn chi-squared selector expects nonnegative feature values (such as counts), not arbitrary standardized negative measurements. Target encoding needs training-row out-of-fold estimates as well as a map fitted on the fold’s training data for held-out transformation. Learn winsorization cutoffs and imputation parameters there too. Do not remove test rows because their outcomes or prediction errors look inconvenient: that changes the evaluation population after seeing results.
25.5 Summary of Part 6
Classification Metrics: Confusion matrix, precision, recall, F1. ROC-AUC measures ranking; PR highlights positive-class performance, especially for rare positives. Neither curve alone specifies the best decision threshold.
Regression Metrics: MAE (linear residual penalty), RMSE (penalizes large errors), R2 (variance explained). Choose based on error characteristics.
Cross-Validation: K-fold for robust evaluation. Stratified for classification. Time series split for temporal data. Nested CV for hyperparameter tuning.
Hyperparameter Tuning: Grid search (exhaustive), random search (efficient), Bayesian optimization (sample-efficient for expensive evaluations).
Feature Scaling: Standardization (most ML algorithms), Min-Max (bounded activations). Always fit on training, transform on test.
Categorical Encoding: Use ordinal encoding for ordered feature categories, one-hot or configured categorical models for nominal features. Target encoding must be fitted within the training/validation scheme.
Missing Data: Understand missingness type (MCAR/MAR/MNAR). Imputation strategies from simple (mean) to complex (KNN, model-based).
Feature Selection: Filter (fast, model-agnostic), wrapper (model-specific, expensive), embedded (integrated). Use based on computational budget and goals.
Next Steps: Part 7 covers practical tools and deployment: WEKA, scikit-learn pipelines, and model serving strategies.
Exercise 25.9.
Given confusion matrix with TP=85, TN=40, FP=10, FN=15, compute accuracy, precision, recall, F1, and specificity.
Explain why accuracy is misleading for a dataset with 95% negative class, 5% positive class. What metrics would you use instead?
For a cancer detection model, would you prioritize precision or recall? Justify your answer and suggest an appropriate threshold strategy.
Implement 5-fold cross-validation by hand for a dataset with 100 examples. Show which examples go in which fold.
Why must we fit the scaler on training data only? What happens if we fit on all data (train + test)?
Design one-hot encoding for categorical variable {Red, Green, Blue, Red, Green}. How many columns? Should you use \(K\) or \(K-1\) columns?
Compare computational complexity: Grid search with 4 parameters (5 values each) vs random search with 100 iterations. Which tries more unique combinations for each parameter?
For time series data, why can’t we use regular k-fold cross-validation? Design a proper time series CV scheme for 120 monthly observations.
Part 7: Tools, Pipelines, and Deployment
26 WEKA: Practical Guide
26.1 Introduction to WEKA
Definition 26.1 (WEKA). WEKA (Waikato Environment for Knowledge Analysis) is a collection of machine learning algorithms for data mining tasks. Developed at University of Waikato, New Zealand.
Key Features:
GUI-based interface (no coding required)
Extensive algorithm library (classification, regression, clustering, etc.)
Built-in visualization tools
Java-based (cross-platform)
Free and open-source
When to use WEKA:
Quick prototyping and experimentation
Teaching and learning ML concepts
Comparing multiple algorithms easily
Small to medium datasets
When GUI is preferred over coding
26.2 WEKA Explorer Interface
WEKA Explorer has 6 main tabs:
1. Preprocess: Load data, view statistics, apply filters
Import ARFF, CSV, JDBC databases
View attribute statistics and distributions
Apply filters (discretization, normalization, attribute selection)
2. Classify: Train classification/regression models
Choose algorithm from tree structure
Configure hyperparameters
Select test options (cross-validation, percentage split, etc.)
View results: accuracy, confusion matrix, ROC
3. Cluster: Perform clustering
K-means, EM, DBSCAN, hierarchical
Evaluate clusters
Visualize assignments
4. Associate: Find association rules
Apriori, FP-Growth
Set minimum support and confidence
5. Select attributes: Feature selection
Various search and evaluation methods
Rank features by importance
6. Visualize: Data exploration
Scatter plots, histograms
Class distributions
Interactive exploration
26.3 Data Format: ARFF
Definition 26.2 (ARFF Format). ARFF (Attribute-Relation File Format) is WEKA’s native format.
Structure:
@relation weather
@attribute outlook {sunny, overcast, rainy}
@attribute temperature numeric
@attribute humidity numeric
@attribute windy {TRUE, FALSE}
@attribute play {yes, no}
@data
sunny,85,85,FALSE,no
sunny,80,90,TRUE,no
overcast,83,86,FALSE,yes
rainy,70,96,FALSE,yes
...
Components:
@relation: Dataset name@attribute: Feature name and type (numeric, nominal, string, date)@data: Actual data rows
26.4 Workflow Example: Classification
WEKA Classification Workflow
Step 1: Load Data
Open Explorer \(\to\) Preprocess tab
Click “Open file...” \(\to\) Select ARFF or CSV
Review attributes in the table
Check class distribution (click on class attribute)
Step 2: Preprocess (Optional)
Configure the desired learned preprocessing, such as
unsupervised.attribute.Normalize.For cross-validation, place the filter inside
meta.FilteredClassifierand choose the base classifier there. Do not fit a learned filter to the full dataset before CV.For a supplied test set, learn the filter only on the training set and apply that fitted filter to test instances.
Step 3: Select Algorithm
Click “Classify” tab
Click “Choose” button
Choose a base model such as
trees.J48; with learned preprocessing, select it as the classifier insidemeta.FilteredClassifierClick on algorithm name to configure parameters
Step 4: Choose Test Method
Cross-validation: Select folds (default 10)
Percentage split: e.g., 66% train, 34% test
Use training set: Evaluate on training (overfitting check)
Supplied test set: Load separate test file
Step 5: Run and Evaluate
Click “Start” button
View results in output area:
Summary statistics
Confusion matrix
Detailed accuracy by class
Right-click on result \(\to\) Visualize for plots
Step 6: Compare Models
Run multiple algorithms (results stack in result list)
Use paired exported evaluations or Experimenter with matched splits for comparisons; menu availability depends on the interface/version
Export results: Right-click \(\to\) Save result buffer
26.5 Common WEKA Algorithms
| Category | Algorithms in WEKA |
|---|---|
| Trees | J48 (C4.5), RandomForest, REPTree |
| Rules | JRip, PART, DecisionTable |
| Functions | Logistic, MultilayerPerceptron, SMO (SVM) |
| Lazy | IBk (KNN), LWL |
| Bayes | NaiveBayes, BayesNet |
| Meta | AdaBoostM1, Bagging, Stacking, Vote |
| Clustering | SimpleKMeans, EM, DBSCAN, HierarchicalClusterer |
26.6 Visualizing Results
WEKA Visualization Tools:
1. ROC Curve:
After classification: Right-click result \(\to\) Visualize threshold curve
Choose class and metric (TPR vs FPR for ROC)
Compare multiple classifiers on same plot
2. Classification Errors:
Right-click result \(\to\) Visualize classifier errors
Shows 2D plot of predictions
Misclassified instances highlighted
Interactive: hover for details
3. Tree Visualization:
For a drawable single-tree classifier such as J48, right-click its result and select “Visualize tree”; a whole forest is not one such tree
Shows decision rules graphically
Can save as PNG/PDF
4. Cost/Benefit Analysis:
Define cost matrix for different types of errors
WEKA computes expected cost
Useful for imbalanced datasets
26.7 Advantages and Limitations
WEKA Advantages:
Easy to use: GUI-based, no programming required
Comprehensive: 100+ algorithms built-in
Educational: Excellent for learning ML
Visualization: Good built-in plots
Reproducible: Can save configurations
WEKA Limitations:
Integration requirements: WEKA also has Java APIs and command-line interfaces; production suitability depends on the application and integration, not on GUI availability
Scalability: Limited to datasets that fit in memory
Packages: Available methods depend on installed packages and Java dependencies; verify the exact estimator rather than assuming every extension is bundled
Automation: Reproducible automation uses its command-line or Java interfaces rather than manual GUI steps
Customization: Limited compared to programming libraries
Best Use Cases:
Academic research and teaching
Quick baseline comparisons
Data exploration
Proof of concept
When to move beyond WEKA:
Datasets whose feature representation or computation exceeds available memory/time; row count alone is insufficient
Production deployment
Need for latest algorithms
Complex preprocessing pipelines
Integration with other systems
26.8 Reproducible WEKA Evaluation with the Same Split Boundaries
The repository workflow exports complete ARFF files, not excerpts containing ellipsis. Predictors are two numeric signals and nominal device type; the last attribute is the nominal class \(\{0,1\}\). Numeric missing values use ?. The allowed category schema \(\{alpha,beta,gamma\}\) is specified in advance; gamma is permitted even if absent from training. IDs, times, and split names are excluded from model attributes.
Example 26.3 (A supplied validation fold with a training-only filter). After running scripts/batch4_workflow.py, use WEKA 3.8.6 and its runtime dependencies on the Java classpath. The following command, with weka-lib/* pointing to those JARs, was tested with Java 21:
java -Djava.awt.headless=true -cp 'weka-lib/*' \
weka.classifiers.meta.FilteredClassifier \
-t output/batch4-demo/fold-1-train.arff \
-T output/batch4-demo/fold-1-valid.arff -c last \
-F weka.filters.unsupervised.attribute.Standardize \
-W weka.classifiers.functions.Logistic -- -R 1.0E-8 -M 200
-T supplies the already separated validation file. Do not add -no-cv to this command: this WEKA version rejects that combination. The filter learns on the 177 training rows, not on all 360 TRAIN rows. The 60 validation rows produce the confusion matrix \[\begin{array}{c|rr}
&\hat y=0&\hat y=1\\\hline
y=0&35&9\\y=1&6&10
\end{array},\qquad \mathrm{accuracy}=45/60=.75.\] Repeat with fold-2 and fold-3 files for the same forward boundaries, preserving all candidates’ paired folds. WEKA’s built-in randomized CV does not enforce this grouped temporal protocol. This is a separate WEKA logistic baseline, with its own regularization, preprocessing, and uncalibrated \(.5\) decision. It is not the frozen calibrated Python system: do not attach the Python calibrator or threshold to a different classifier’s scores. Any WEKA model chosen for deployment needs its own calibration and policy stages.
27 ML Pipelines in Python
27.1 Introduction to Scikit-learn
Definition 27.1 (Scikit-learn). Scikit-learn is Python’s premier machine learning library, offering:
Consistent API across algorithms
Comprehensive algorithm coverage
Excellent documentation
Integration with NumPy, Pandas, Matplotlib
Production-ready code
Core API: All estimators follow the same pattern:
model = Estimator() # Initialize
model.fit(X_train, y_train) # Train
predictions = model.predict(X_test) # Predict
score = model.score(X_test, y_test) # Evaluate27.2 The Pipeline Concept
Definition 27.2 (Pipeline). A Pipeline chains multiple processing steps into a single estimator: \[\text{Data} \xrightarrow{\text{Transform 1}} \xrightarrow{\text{Transform 2}} \xrightarrow{\cdots} \xrightarrow{\text{Model}}\]
Benefits:
Convenience: Single
fit()/predict()callEnforces fitting boundaries: When the whole Pipeline is fitted within valid splits, its transformers learn only from that training block; upstream feature/time/group leakage still needs separate checks
Hyperparameter tuning: Tune entire pipeline with GridSearchCV
Reproducibility: Easy to save and load entire workflow
Code cleanliness: Organized preprocessing + modeling
27.3 Building Pipelines
The short snippets below are independent API illustrations: each assumes its own previously split data with the displayed numeric or named-column schema. They are not one script that changes the meaning of X_train midway. The generated-data implementation in Section 27.9 is the complete executable workflow. A short fragment’s external data or metric variables must be supplied consistently for that fragment.
Basic Pipeline Example:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
# X_train/X_test: numeric matrices with at least two features;
# training sample size is at least two. Splits are already fixed.
# Create pipeline
pipeline = Pipeline([
('scaler', StandardScaler()), # Step 1: Scale
('pca', PCA(n_components=2)), # Step 2: Reduce dim
('classifier', LogisticRegression(max_iter=1000)) # Step 3: Classify
])
# Use like any other estimator
pipeline.fit(X_train, y_train)
predictions = pipeline.predict(X_test)
accuracy = pipeline.score(X_test, y_test)
print(f"Accuracy: {accuracy:.3f}")Key Points:
Each step is a tuple:
(’name’, transformer)Intermediate steps must implement
fit()andtransform(); a separatefit_transform()can be inherited or optionally implementedLast step must implement
fit(); prediction pipelines needpredict(), while a transformation-only pipeline may end in a transformerAccess steps:
pipeline.named_steps[’scaler’]
27.4 Column Transformer
Definition 27.3 (ColumnTransformer). Apply different transformations to different columns:
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler, OneHotEncoder
# Define transformations for different column types
preprocessor = ColumnTransformer([
('num', StandardScaler(), ['age', 'income']),
('cat', OneHotEncoder(handle_unknown='ignore'), ['gender', 'city'])
])
# Use in pipeline
pipeline = Pipeline([
('preprocessor', preprocessor),
('classifier', RandomForestClassifier(random_state=42))
])Benefits:
Handle mixed data types (numerical + categorical)
Apply appropriate transformation to each feature type
Cleaner than manual column splitting
27.5 Pipeline with GridSearchCV
Hyperparameter Tuning with Pipeline:
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
# Create pipeline
pipeline = Pipeline([
('scaler', StandardScaler()),
('classifier', SVC())
])
# Define parameter grid (use double underscore)
param_grid = [
{'classifier__kernel': ['rbf'],
'classifier__C': [0.1, 1, 10],
'classifier__gamma': [0.001, 0.01, 0.1]},
{'classifier__kernel': ['linear'],
'classifier__C': [0.1, 1, 10]}
]
# Grid search on entire pipeline
grid_search = GridSearchCV(
pipeline,
param_grid,
cv=5,
scoring='accuracy',
n_jobs=1
)
grid_search.fit(X_train, y_train)
print(f"Best params: {grid_search.best_params_}")
print(f"Best CV score: {grid_search.best_score_:.3f}")
# Use best model
best_model = grid_search.best_estimator_
test_score = best_model.score(X_test, y_test)Naming convention: Use step_name__parameter_name to reference pipeline parameters.
27.6 Custom Transformers
Definition 27.4 (Custom Transformer). Create your own transformer by inheriting from BaseEstimator and TransformerMixin:
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
class LogTransformer(TransformerMixin, BaseEstimator):
def __init__(self, features):
self.features = features
def fit(self, X, y=None):
return self # Nothing to learn
def transform(self, X):
X_copy = X.copy()
values = X_copy.loc[:, self.features].to_numpy(dtype=float)
if not np.isfinite(values).all() or np.any(values <= -1):
raise ValueError('log1p requires finite values greater than -1')
X_copy[self.features] = np.log1p(values)
return X_copy
# Use in pipeline
pipeline = Pipeline([
('log', LogTransformer(['income', 'age'])),
('scaler', StandardScaler()),
('model', RandomForestRegressor(random_state=42))
])Requirements:
Implement
fit()(even if it just returnsself)Implement
transform()Optionally implement
fit_transform()(inherited from mixin)
27.7 Model Persistence
27.7.1 Saving and Loading Models
Method 1: Joblib (Recommended):
import joblib
# Save model
joblib.dump(pipeline, 'model_pipeline.joblib')
# Load model
loaded_pipeline = joblib.load('model_pipeline.joblib')
# Use loaded model
predictions = loaded_pipeline.predict(X_new)Method 2: Pickle:
import pickle
# Save
with open('model.pkl', 'wb') as f:
pickle.dump(pipeline, f)
# Load
with open('model.pkl', 'rb') as f:
loaded_model = pickle.load(f)Joblib vs Pickle:
Joblib: Array-oriented persistence with optional compression; performance depends on data and settings
Pickle: Supports many Python objects; referenced definitions and compatible dependencies must be available when loading
Cross-version scikit-learn estimator loading is unsupported; recreate the recorded environment. Both formats can execute code when loading, so use only trusted artifacts
27.7.2 Versioning and Reproducibility
Best Practices for Model Persistence:
1. Save Metadata:
import json
import sklearn
from datetime import datetime
# Schema example: metrics refer to this same frozen selected procedure.
selected = grid_search.best_estimator_
metadata = {
'model_type': type(selected.steps[-1][1]).__name__,
'sklearn_version': sklearn.__version__,
'training_date': datetime.now().isoformat(),
'features': list(X_train.columns),
'performance': {
'train_accuracy': train_acc,
'test_accuracy': test_acc,
'cv_score': cv_score
},
'hyperparameters': grid_search.best_params_
}
with open('model_metadata.json', 'w') as f:
json.dump(metadata, f, indent=2)2. Version Control:
Use Git for code
Use DVC (Data Version Control) for models and data
Tag model versions:
v1.0.0,v1.1.0
3. Environment Management:
# Save environment
pip freeze > requirements.txt
# Or use conda
conda env export > environment.yml4. Directory Structure:
27.8 Complete Pipeline Example
End-to-End Pipeline with All Features:
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
import pandas as pd
import joblib
# Define column types
numeric_features = ['age', 'income', 'credit_score']
categorical_features = ['gender', 'education', 'employment']
# Numeric pipeline
numeric_transformer = Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())
])
# Categorical pipeline
categorical_transformer = Pipeline([
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# Combine with ColumnTransformer
preprocessor = ColumnTransformer([
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
])
# Full pipeline
pipeline = Pipeline([
('preprocessor', preprocessor),
('classifier', RandomForestClassifier(random_state=42))
])
# Cross-validation
cv_scores = cross_val_score(
pipeline, X_train, y_train,
cv=5, scoring='accuracy'
)
print(f"CV Accuracy: {cv_scores.mean():.3f} (fold SD {cv_scores.std():.3f})")
# Train final model
pipeline.fit(X_train, y_train)
# Evaluate
test_score = pipeline.score(X_test, y_test)
print(f"Test Accuracy: {test_score:.3f}")
# Save
joblib.dump(pipeline, 'credit_model_pipeline.joblib')
# Later: Load and predict
loaded_pipeline = joblib.load('credit_model_pipeline.joblib')
new_predictions = loaded_pipeline.predict(X_new)27.9 One Complete, Executed Device-Alert Workflow
The preceding credit example illustrates a conventional pipeline. This section provides a complete additional implementation with generated data, declared partitions, calibration, a decision rule, persistence, serving, and export. All reported values below come from the synthetic run with seed 20261119; they are not a claim about a real device population.
Example 27.5 (Training through the final frozen report). Use Python 3.12 with the direct dependency pins in scripts/requirements-batch4.txt. For example, create a virtual environment and install those packages before running from the repository root:
python3.12 -m venv .venv
.venv/bin/python -m pip install -r scripts/requirements-batch4.txt
Activate that environment, then run:
python scripts/batch4_workflow.py --output output/batch4-demo
python scripts/batch4_export.py
uvicorn --app-dir scripts batch4_serving:app --host 127.0.0.1 --port 8000
The last line starts a local demonstration service; validation uses an in-process client, so no network listener is necessary. The first script generates 780 rows, applies Section 23.2, and saves the complete bundle. Its actual selection sequence is:
from batch4_workflow import (
make_data, partition, fit_before_test, evaluate_frozen)
data = make_data() # deterministic synthetic records
parts = partition(data)
bundle, selection = fit_before_test(data)
# fit_before_test uses TRAIN, CALIBRATION and POLICY labels only.
metrics, probability, prediction = evaluate_frozen(bundle, parts['test'])Here the module lives in scripts; use PYTHONPATH=scripts when executing this excerpt from the root. The complete script, rather than this excerpt, writes all artifacts and audit tables.
Numeric preprocessing is median imputation followed by standardization; nominal preprocessing is one-hot encoding with unknown categories ignored. Every search clone fits these statistics inside its current training fold. Six logistic settings select \(C=10\) with no class weighting using mean validation NLL \(.521519\). Logistic regularization follows the estimator’s own \(C\) convention; \(C\) is not silently equated with an earlier mean-loss \(\lambda\). If transferring a regularization setting between sum and mean objectives, convert the loss/penalty scaling explicitly.
The base pipeline is refitted on TRAIN only. For base probability \(p_0\) define \(s=\log\{\tilde p_0/(1-\tilde p_0)\}\) with \(\tilde p_0=\mathrm{clip}(p_0,10^{-7},1-10^{-7})\). A one-feature logistic calibrator fitted on 120 CALIBRATION rows gives \[q=\sigma(.7864064865\,s+.1497350775).\] On 120 POLICY rows, search the predeclared grid \(.1,.2,\ldots,.9\) for mean cost \((FP+4FN)/120\), breaking ties toward the higher threshold. Threshold \(.2\) wins with FP 54, FN 1, cost \(58/120=.483333\). Thresholds \(.1\) and \(.3\) give costs \(65/120\) and \(60/120\). No model, calibrator, or threshold is fitted after this selection.
The frozen TEST result on 180 rows from 60 devices is:
| TN / FP | 22 / 93 | FN / TP | 2 / 63 |
| Accuracy | \(.472222\) | ROC-AUC | \(.698997\) |
| Average precision | \(.536225\) | Brier | \(.213298\) |
| Mean NLL | \(.611886\) | Mean cost | \(.561111\) |
The low accuracy is retained in the report. With these declared costs the fixed always-negative and always-positive baselines cost \(260/180=1.444444\) and \(115/180=.638889\). The chosen decision prioritizes recall at a substantial false-positive burden; these synthetic results do not establish deployment readiness. No threshold is changed in response to TEST.
A 500-draw percentile bootstrap samples whole test devices with all three visits retained. Conditional on this frozen predictor, the AUC interval is \([.618689,.785074]\) and the mean-cost interval is \([.477778,.661111]\). All draws contain both classes. This excludes training/search uncertainty and does not resolve future population shift.
27.9.1 Artifacts and Reproducibility
output/batch4-demo contains the base pipeline, calibrator, class order, clipping constant, threshold, and schema version in device_alert.joblib; metadata records source/data hashes and dependency versions. Complete split CSVs, ARFF files, forward-fold exports, test predictions, and a JSON report accompany it. Test rows do not enter the model identifier or decision-data hash. Changing only test labels must not change a fitted parameter, threshold, or model ID. A saved file hash detects accidental file changes relative to a trusted manifest; it does not authenticate an artifact obtained from an untrusted source. Both pickle and joblib can execute code while loading: load only trusted, operator-selected artifacts. Record and recreate the training environment; cross-version estimator loading is not supported merely because deserialization happens to succeed. See the official persistence guide.
27.9.2 An Input Contract Shared by Offline and Online Prediction
The complete service is scripts/batch4_serving.py. Its contract is:
Exactly
signal_a,signal_b, anddevice_typeper row. Both numeric keys are required but may be null; non-null values must be finite numbers. Strings masquerading as numbers, booleans, infinities, extra keys, missing keys, and blank categories are rejected.Unknown nonempty category strings are permitted by the trained all-zero one-hot fallback. This differs from silently inventing a new fitted category.
A request has 1–256 rows. Responses preserve row order and identify model version, schema version, threshold, positive label 1, probabilities, and decisions. No request can cause a fitting operation or choose an artifact path.
A valid request includes a null and an unseen category:
{"rows":[{"signal_a":0.2,"signal_b":null,"device_type":"gamma"}]}
The app factory verifies the artifact’s feature list, class ordering, and estimator runtime version before exposing readiness. Separate liveness and readiness endpoints distinguish a running process from a loaded model. The provided service logs model ID, batch size, and latency rather than raw feature values. Before a broader deployment, specify authentication, resource limits, concurrency, and service-level requirements for that environment. The earlier Flask/FastAPI excerpts illustrate smaller credit-model interfaces; they are separate schemas, not interchangeable endpoints for this artifact.
27.9.3 Export Is a Whole-System Parity Question
Example 27.6 (ONNX graph plus explicit postprocessing). scripts/batch4_export.py converts the full base pipeline, including imputation, scaling, category encoding, and logistic head, at opset 21. Numeric inputs are float32 tensors of shape \((B,1)\); the category is a string tensor of that shape. The probability output’s column 1 corresponds to class 1. The graph’s raw label is not the calibrated system’s decision.
onnx_postprocess.json stores clipping, calibration coefficients, class index, threshold, and model ID. The adapter applies the same clipped-logit calibration formula and \(q\ge .2\) rule as Python. On all 180 fixed test rows plus three null/unseen-category/saturated-score cases, maximum calibrated probability difference is \(4.08\times10^{-7}\) (rounded upward); all decisions match, using absolute and relative tolerances \(2\times10^{-6}\). This finite parity check is not a proof for all possible inputs. A different converter, dtype, or quantized graph needs its own parity assessment, especially near the threshold. Exporting a classifier alone would omit the policy.
A local ASGI container recipe can copy the frozen artifact and use an explicit startup command:
FROM python:3.12-slim
WORKDIR /app
COPY output/batch4-demo/requirements-runtime.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY scripts/batch4_workflow.py scripts/batch4_serving.py /app/scripts/
COPY output/batch4-demo/device_alert.joblib /app/model.joblib
ENV MODEL_PATH=/app/model.joblib
EXPOSE 8000
CMD ["uvicorn", "--app-dir", "scripts", "batch4_serving:app", "--host", "0.0.0.0", "--port", "8000"]
The generated requirements pin direct runtime packages; a deployment release should additionally lock transitive dependencies and the base image digest. This recipe has been reviewed but not built here because Docker is unavailable. The TensorFlow export excerpt is an optional framework-specific example and was not executed in this environment. The executed export evidence is ONNX.
28 Model Deployment
28.1 Deployment Considerations
Key Questions Before Deployment:
1. Latency Requirements:
Real-time (\(<\) 100ms): Lightweight models, caching
Near real-time (seconds): Benchmark the complete preprocessing and inference path under expected load
Batch processing (hours): Choose a model whose memory and compute fit the processing window
2. Scale:
Queries per second (QPS)?
Peak vs average load?
Need for horizontal scaling?
3. Infrastructure:
Cloud (AWS, GCP, Azure) vs on-premise?
Serverless (Lambda) vs containers (Docker) vs VMs?
GPU required?
4. Monitoring:
Performance metrics (latency, throughput)
Model metrics (accuracy, drift detection)
System metrics (CPU, memory, errors)
5. Updates:
How often to retrain?
Blue-green deployment vs canary?
Rollback strategy?
28.2 Model Export Formats
28.2.1 ONNX (Open Neural Network Exchange)
Definition 28.1 (ONNX). ONNX is an open format for representing ML models, enabling interoperability across frameworks.
Benefits:
Train in one framework (PyTorch, scikit-learn), deploy in another
Optimized inference engines (ONNX Runtime)
Hardware acceleration support
Language-agnostic (use from Python, C++, Java, etc.)
# This separate excerpt assumes a supported, already fitted
# all-numeric sklearn_model and matching numeric X_test.
import numpy as np
# Convert scikit-learn to ONNX
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
# Define input type
initial_type = [('float_input', FloatTensorType([None, n_features]))]
# Convert
onnx_model = convert_sklearn(
sklearn_model,
initial_types=initial_type, target_opset=21
)
# Save
with open("model.onnx", "wb") as f:
f.write(onnx_model.SerializeToString())
# Load and inference with ONNX Runtime
import onnxruntime as rt
sess = rt.InferenceSession("model.onnx")
input_name = sess.get_inputs()[0].name
pred = sess.run(None, {input_name: X_test.astype(np.float32)})The returned list contains the graph’s named outputs; inspect their names, shapes, and class ordering rather than assuming every entry is a label array. For the mixed-column pipeline and calibrated decision rule, use the executed adapter in Section 27.9 and its explicit postprocessing.
28.2.2 TensorFlow SavedModel
Definition 28.2 (TensorFlow SavedModel). TensorFlow SavedModel is an inference/export format. In Keras 3, use the native .keras format with save() and load_model(). Use model.export() for SavedModel. A SavedModel is loaded using TensorFlow APIs or wrapped with TFSMLayer, not passed to Keras 3 load_model(). See the Keras 3 migration guide.
import tensorflow as tf
# Keras 3: save a reloadable Keras model
model.save('model.keras')
loaded_model = tf.keras.models.load_model('model.keras')
predictions = loaded_model.predict(X_test)
# Export an inference artifact in TensorFlow SavedModel format
model.export('saved_model/my_model', format='tf_saved_model')
serving_model = tf.saved_model.load('saved_model/my_model')
served_predictions = serving_model.serve(tf.convert_to_tensor(X_test))Benefits:
SavedModel preserves exported computation and weights for inference; the native Keras format also preserves Keras configuration and optimizer state when saved
TensorFlow Serving integration
TensorFlow Lite for mobile/edge
28.2.3 Format Comparison
| Format | Framework | Use Case | Pros |
|---|---|---|---|
| Pickle/Joblib | Any Python | Python-only | Simple, native |
| ONNX | Cross-framework | Production | Optimized, portable |
| SavedModel | TensorFlow | TF ecosystem | Complete, TF Serving |
| PMML | Traditional ML | Enterprise | Standardized, legacy |
28.3 Serving Models via REST API
28.3.1 Flask API
Simple Flask API for Model Serving:
from flask import Flask, request, jsonify
import joblib
import os
import pandas as pd
app = Flask(__name__)
# Same artifact and named-column contract as the complete pipeline example.
model = joblib.load(os.environ.get(
'MODEL_PATH', 'credit_model_pipeline.joblib'))
def prepare_rows(rows):
if not isinstance(rows, list) or not rows:
raise ValueError('rows must be a nonempty list of objects')
expected = list(model.feature_names_in_)
if any(not isinstance(row, dict) or set(row) != set(expected)
for row in rows):
raise ValueError(f'each row must have exactly these keys: {expected}')
return pd.DataFrame(rows).loc[:, expected]
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
if not isinstance(data, dict):
return jsonify({'error': 'expected a JSON object'}), 400
try:
features = prepare_rows(data.get('rows'))
return jsonify({
'predictions': model.predict(features).tolist(),
'probabilities': model.predict_proba(features).tolist(),
'classes': model.classes_.tolist()
})
except (ValueError, TypeError) as exc:
return jsonify({'error': str(exc)}), 400
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'healthy'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) # Local development serverTest with curl:
curl -X POST http://localhost:5000/predict \
-H 'Content-Type: application/json' \
-d '{"rows": [{"age": 25, "income": 50000, "credit_score": 700,
"gender": "female", "education": "college",
"employment": "employed"}]}'28.3.2 FastAPI (Modern Alternative)
FastAPI for High-Performance Serving:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
import joblib
import os
import pandas as pd
class PredictionRequest(BaseModel):
rows: list[dict[str, float | str | None]] = Field(min_length=1)
app = FastAPI(title='ML Model API')
model = joblib.load(os.environ.get(
'MODEL_PATH', 'credit_model_pipeline.joblib'))
@app.post('/predict')
def predict(request: PredictionRequest):
# A regular def lets FastAPI run blocking model work in a thread pool.
expected = list(model.feature_names_in_)
if any(set(row) != set(expected) for row in request.rows):
raise HTTPException(400, f'each row must have these keys: {expected}')
try:
features = pd.DataFrame(request.rows).loc[:, expected]
return {
'predictions': model.predict(features).tolist(),
'probabilities': model.predict_proba(features).tolist(),
'classes': model.classes_.tolist()
}
except (ValueError, TypeError) as exc:
raise HTTPException(400, detail=str(exc)) from exc
@app.get('/health')
def health():
return {'status': 'healthy'}
# Development: uvicorn app:app --reloadFastAPI Advantages:
Automatic API documentation (Swagger UI at
/docs)Type validation with Pydantic
Supports asynchronous I/O; synchronous model computation must not block an async event loop
Throughput depends on the server, workers and model cost; framework choice alone does not determine it
28.4 Containerization with Docker
Dockerfile for ML API:
FROM python:3.12-slim
WORKDIR /app
# Copy requirements and install
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy model and code
COPY credit_model_pipeline.joblib .
COPY app.py .
# Expose port
EXPOSE 5000
# Run app
CMD ["python", "app.py"]
Build and Run:
# Build image
docker build -t ml-model-api .
# Run container
docker run -p 5000:5000 ml-model-api
# Test
curl http://localhost:5000/healthDocker Compose for the Flask Example: Place the saved artifact in ./models/. Redis is an optional additional service; the API below does not use it until caching code is added.
services:
api:
build: .
ports:
- "5000:5000"
environment:
- MODEL_PATH=/models/credit_model_pipeline.joblib
volumes:
- ./models:/models
redis:
image: redis:alpine
ports:
- "6379:6379"
28.5 Cloud Deployment
Cloud Deployment Options:
1. Serverless (AWS Lambda, Google Cloud Functions):
Pros: No server management, auto-scaling, pay per use
Cons: Cold starts, limited execution time, limited memory
Best for: Low to medium traffic, event-driven, cost-sensitive
2. Containers (AWS ECS, GKE, Azure Container Instances):
Pros: Consistent environments, easy scaling, orchestration
Cons: More complex setup, need to manage infrastructure
Best for: Medium to high traffic, microservices
3. Managed ML Services:
Managed training/serving platforms; verify the provider’s current interfaces, supported runtimes, and service configuration
Pros: Built-in monitoring, auto-scaling, A/B testing, versioning
Cons: Vendor lock-in, can be expensive
Best for: Enterprise ML, need full MLOps
4. Kubernetes:
Pros: Highly scalable, flexible, cloud-agnostic
Cons: Steep learning curve, operational overhead
Best for: Large scale, multi-model serving, complex workflows
28.6 Model Monitoring
Definition 28.3 (Model Monitoring). Continuous tracking of model performance and data quality in production.
Key Metrics to Monitor:
1. Performance Metrics:
Prediction accuracy/error
Latency (p50, p95, p99)
Throughput (requests per second)
2. Data Quality:
Missing values
Out-of-range values
Data type mismatches
3. Data Drift:
Feature distribution changes
Target distribution changes
KL divergence, KS test
4. Concept Drift:
\(P(y|X)\) changes over time
Predictive performance may change; outcome measurements are needed to assess it
Investigate the cause and validate an appropriate response before retraining or changing the policy
5. System Metrics:
CPU/memory usage
Error rates
Uptime
Simple Logging for Monitoring:
import logging
import time
from datetime import datetime, timezone
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Replace the Flask /predict handler above; do not register both handlers.
# Reuse app, model, prepare_rows, request and jsonify from that example.
@app.route('/predict', methods=['POST'])
def predict():
start = time.perf_counter()
data = request.get_json()
if not isinstance(data, dict):
return jsonify({'error': 'expected a JSON object'}), 400
try:
features = prepare_rows(data.get('rows'))
predictions = model.predict(features).tolist()
probabilities = model.predict_proba(features).tolist()
logger.info({
'timestamp': datetime.now(timezone.utc).isoformat(),
'batch_size': len(features),
'latency_ms': (time.perf_counter() - start) * 1000
})
return jsonify({'predictions': predictions,
'probabilities': probabilities,
'classes': model.classes_.tolist()})
except (ValueError, TypeError) as exc:
return jsonify({'error': str(exc)}), 400Advanced: Use dedicated tools like Prometheus, Grafana, ELK stack, or cloud-native solutions (CloudWatch, Stackdriver).
28.7 Best Practices Summary
Versioning: Tag models, save metadata, track lineage
Testing: Unit tests, integration tests, load tests before production
Monitoring: Log predictions, track performance, detect drift
Gradual Rollout: Canary deployment (5% \(\to\) 50% \(\to\) 100%)
Rollback Plan: Keep previous model version, quick rollback capability
Security:
API authentication (API keys, OAuth)
Rate limiting
Input validation
HTTPS only
Documentation: API docs, model cards, usage examples
Automation: CI/CD pipeline for model updates
Cost Optimization: Right-size resources, use caching, batch predictions when possible
Feedback Loop: Collect ground truth labels, retrain periodically
28.8 Monitoring, Delayed Labels, and a Reversible Release
Example 28.4 (An input alarm is not a performance measurement). For fixed categorical bins, reference frequencies are \(p=(.5,.5)\) and current frequencies \(q=(.8,.2)\). Then \[\begin{aligned} D_{KL}(q\Vert p)&=.8\log1.6+.2\log.4=.192745,\\ \mathrm{PSI}&=\sum_j(q_j-p_j)\log(q_j/p_j)=.3\log4=.415888. \end{aligned}\] The direction of KL is declared. With empty bins, define a fixed smoothing rule and normalize before computing these quantities; a plug-in zero is not an innocuous finite value. Thresholds for alerts need baseline variability, sample sizes, and investigation procedures, not universal PSI cutoffs.
Input drift concerns \(P(X)\). Performance can remain unchanged after it; conversely, changing \(Y=X\) to \(Y=1-X\) for a fair binary \(X\) leaves \(P(X)\) unchanged while reversing a formerly perfect classifier. Thus input tests alone cannot detect all changes in \(P(Y\mid X)\). Delayed outcome metrics join each prediction’s ID, model ID, prediction time, threshold, and feature snapshot to a label available by the monitoring cutoff. Report unresolved-label counts; if resolved labels are selective, their metric is for the observed subset. Never treat missing labels as negatives or overwrite old predictions with a new model before computing historical performance.
Example 28.5 (Stable assignment and a prespecified canary decision). Assign traffic consistently at the independent entity level using SHA256(salt:entity) mapped to buckets 0–9999. Buckets below 1000 form an approximately 10% canary; finite realized fractions need not be exactly 10%. Python’s process-randomized hash() is unsuitable for persistent assignment. Version the salt and retain assignment IDs. Repeated visits by one device stay in one arm.
For a separate illustrative experiment with 1000 independent entities in each arm, old and new error counts 120 and 90 give difference \(\hat p_{new}-\hat p_{old}=-.03\), standard error \(\sqrt{.12\cdot.88/1000+.09\cdot.91/1000}=.013693\), and approximate 95% interval \([-.05684,-.00316]\). These are invented release numbers, not measurements of the device example. Predeclare the horizon, minimum sample size, primary metric, and latency/error/fairness guardrails. Repeated optional peeking invalidates a fixed-horizon interval; dependent observations need an appropriate cluster or sequential analysis.
A release version contains the preprocessing, base predictor, calibrator, threshold, input schema, and runtime together. Rollback restores this entire version. An input alarm initiates investigation; retraining uses a newly versioned training window and a fresh evaluation boundary. Repeatedly choosing new versions on the old final test turns that test into validation data.
28.9 Summary of Part 7
WEKA: Offers a GUI, command-line tools and Java APIs. Useful for learning and baseline comparisons; put learned filters inside cross-validation.
Scikit-learn Pipelines: Chain preprocessing and modeling. Fit the complete pipeline inside correctly constructed folds to enforce preprocessing boundaries; audit upstream feature availability separately. Use ColumnTransformer for mixed data types.
Model Persistence: Use joblib for scikit-learn models. Save metadata (version, hyperparameters, performance). Version control models.
Export Formats: ONNX for cross-framework compatibility, SavedModel for TensorFlow ecosystem, pickle/joblib for Python-only.
API Serving: Flask for simple APIs, FastAPI for high performance. Include health checks and error handling.
Containerization: Docker ensures consistent environments. Docker Compose for multi-service setups.
Cloud Deployment: Choose based on scale (serverless \(\to\) containers \(\to\) Kubernetes). Managed services for full MLOps.
Monitoring: Track performance, data drift, system metrics. Log predictions for debugging and retraining.
Next Steps: Part 8 covers advanced topics: reinforcement learning, representation learning, ethics in ML, and modern trends like foundation models and AutoML.
Exercise 28.6.
Design a WEKA workflow to compare Decision Tree (J48), Random Forest, and SVM on the Iris dataset. What test method would you use and why?
Create a scikit-learn pipeline that handles both numeric (scaling) and categorical (one-hot encoding) features, then trains a Random Forest. Include proper error handling.
Explain why we must fit transformers only on training data. Give an example of what goes wrong if we fit on test data.
Design a Flask API that serves a sentiment analysis model. Include endpoints for single prediction and batch prediction. Add appropriate error handling.
Write a Dockerfile for deploying a scikit-learn model as a Flask API. What base image would you use? Why?
Compare serverless (AWS Lambda) vs container (Docker on ECS) deployment for: (a) Low-traffic app (100 requests/day), (b) High-traffic app (10,000 requests/second).
Design a monitoring system for a production model. What metrics would you track? How would you detect when the model needs retraining?
Implement a simple A/B test framework where 10% of traffic goes to a new model version, 90% to the old version. How would you decide when to fully switch?
Part 8: Advanced Topics and Modern Directions
The advanced objectives below reuse the notation and loss conventions of Section 1.4. They change the learning problem, not the need for a valid evaluation boundary: policy training uses fresh evaluation episodes, representation fitting respects source-level splits, and federated or retrieved data need their own client/time/availability rules. Part 5 holds the core autoencoder derivation; this part develops its uses and extensions.
29 Reinforcement Learning
29.1 Introduction to Reinforcement Learning
Definition 29.1 (Reinforcement Learning). Reinforcement Learning (RL) is learning by interacting with an environment to maximize cumulative reward.
Key difference from supervised learning:
No labeled examples—agent must discover good actions through trial and error
Delayed rewards—actions may have long-term consequences
Sequential decision-making—current action affects future states
29.2 Core Components
Definition 29.2 (RL Framework). An RL system consists of:
1. Agent: The learner/decision maker
2. Environment: Everything the agent interacts with
3. State (\(s_t\)): Current situation of the agent
4. Action (\(a_t\)): Choice made by the agent
5. Reward (\(r_t\)): Immediate feedback from environment
6. Policy (\(\pi\)): Agent’s strategy for selecting actions \[\pi(a|s) = P(\text{action } a | \text{state } s)\]
7. Value Function (\(V^\pi(s)\)): Expected cumulative reward from state \(s\) under policy \(\pi\) \[V^\pi(s) = \mathbb{E}_\pi\left[\sum_{t=0}^\infty \gamma^t r_t \mid s_0 = s\right]\] For bounded rewards in a continuing task, take \(0\leq\gamma<1\) so this sum is finite. The episodic case can use \(\gamma=1\) when the return has finite expectation.
8. Q-Function (\(Q^\pi(s,a)\)): Expected cumulative reward from taking action \(a\) in state \(s\) \[Q^\pi(s,a) = \mathbb{E}_\pi\left[\sum_{t=0}^\infty \gamma^t r_t \mid s_0 = s, a_0 = a\right]\]
Intuition 338. Think of learning to play a video game:
State: Current game screen
Action: Button presses (up, down, left, right, jump)
Reward: Points gained, lives lost
Policy: Strategy for playing (e.g., “when enemy approaches, jump”)
Goal: Maximize total score (cumulative reward)
The agent explores different actions, observes rewards, and learns which actions lead to high scores.
29.3 The Exploration-Exploitation Dilemma
Definition 29.4 (Exploration vs Exploitation). Exploitation: Choose the action with the largest estimated long-term return, not necessarily the largest immediate reward
Exploration: Try new actions to discover potentially better options
Dilemma: How to balance?
Pure exploitation: May miss better strategies
Pure exploration: Wastes time on known bad actions
\(\epsilon\)-Greedy Strategy: \[a_t = \begin{cases} \mathop{\mathrm{arg\,max}}_a Q(s_t, a) & \text{with probability } 1-\epsilon \text{ (exploit)} \\ \text{random action} & \text{with probability } \epsilon \text{ (explore)} \end{cases}\] Common: Start with high \(\epsilon\) (e.g., 1.0), decay over time to 0.01.
29.4 Q-Learning
Definition 29.5 (Q-Learning). Model-free algorithm to learn optimal Q-function (and thus optimal policy).
Bellman Optimality Equation: \[Q^*(s,a) = \mathbb{E}_{s' \sim P(\cdot|s,a)}\left[r(s,a) + \gamma \max_{a'} Q^*(s', a')\right]\] The optimal Q-value equals expected immediate reward plus discounted max future Q-value. In deterministic environments, this simplifies to \(Q^*(s,a) = r + \gamma \max_{a'} Q^*(s', a')\).
For a terminal next state, use a future-value term of zero.
Q-Learning Update Rule: \[Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\left[r_t + \gamma \max_{a} Q(s_{t+1}, a) - Q(s_t, a_t)\right]\] where \(\alpha\) is the learning rate. Set \(Q(s_{\rm terminal},a)=0\) for every action; the terminal state is not used for another action selection.
Intuition: Adjust Q-value toward a sampled, bootstrapped TD target; the TD error is target minus current estimate.
Q-Learning Algorithm
Initialize: Q-table \(Q(s,a) = 0\) for all states \(s\) and actions \(a\)
For each episode:
Initialize state \(s\)
While not terminal:
Choose action \(a\) using \(\epsilon\)-greedy policy based on \(Q(s, \cdot)\)
Take action \(a\), observe reward \(r\) and next state \(s'\)
Update: \[Q(s,a) \leftarrow Q(s,a) + \alpha\left[r + \gamma \max_{a'} Q(s',a') - Q(s,a)\right]\]
\(s \leftarrow s'\)
Output: Learned Q-table and its greedy policy. Convergence to \(Q^*\) requires assumptions including sufficient exploration and suitable diminishing learning rates; a finite run is not guaranteed optimal.
Example 29.6 (GridWorld Navigation). Agent in \(4 \times 4\) grid, goal at top-right corner.
States: Grid positions Actions: \(\{\text{up, down, left, right}\}\) Rewards: \(-1\) per step, \(+10\) at goal, \(-10\) for obstacles
With suitable exploration and learning rates, Q-learning can learn a policy maximizing the stated discounted rewards. A finite run need not find a shortest path, and shortest length is not equivalent to every reward objective.
29.5 Deep Q-Networks (DQN)
Definition 29.7 (DQN). Extend Q-learning to high-dimensional state spaces (e.g., images) using neural networks.
Instead of Q-table, use neural network \(Q(s, a; \theta)\) parameterized by \(\theta\).
Key innovations:
1. Experience Replay:
Store transitions \((s_t,a_t,r_t,s_{t+1},d_t)\), where \(d_t=1\) denotes an actual terminal state. A time-limit truncation is handled according to the task definition, not automatically as termination
Sample random mini-batches for training
Reduces the influence of consecutive-sample correlation; replay samples can remain dependent
2. Target Network:
Use separate network \(Q(s, a; \theta^-)\) for target computation
Update \(\theta^-\) periodically (copy from \(\theta\))
Stabilizes training (target doesn’t move every update)
Loss Function: \[\mathcal{L}(\theta)=\mathbb{E}_{(s,a,r,s',d)\sim\text{Buffer}} \left[\left(r+\gamma(1-d)\max_{a'}Q(s',a';\theta^-)-Q(s,a;\theta)\right)^2\right]\]
DQN Breakthroughs:
Success: DQN (2013-2015) achieved human-level performance on Atari games using only pixel input.
Why important:
First deep RL success on complex tasks
Showed RL can work with raw sensory input
Sparked modern deep RL research
Extensions:
Double DQN: Addresses overestimation bias
Dueling DQN: Separate value and advantage streams
Prioritized Experience Replay: Sample important transitions more
Rainbow: Combines multiple improvements
Limitations:
Sample inefficient (needs millions of frames)
Discrete actions only
Can be unstable
29.6 Policy Gradient Methods
Definition 29.8 (Policy Gradient). Instead of learning Q-function, directly learn policy \(\pi(a|s; \theta)\).
Objective: Maximize expected cumulative reward \[J(\theta)=\mathbb{E}_{\tau\sim\pi_\theta}\left[\sum_{t=0}^{T-1}\gamma^t r_t\right]\]
Policy Gradient Theorem: \[\nabla_\theta J(\theta)=\mathbb{E}_{\tau\sim\pi_\theta}\left[\sum_{t=0}^{T-1}\gamma^t\nabla_\theta\log\pi_\theta(a_t\mid s_t)G_t\right]\] Here \(G_t=\sum_{k=t}^{T-1}\gamma^{k-t}r_k\) is reward-to-go for a finite horizon \(T\). Assume differentiability, parameter-independent environment dynamics, and conditions permitting differentiation under the expectation. The outer \(\gamma^t\) is required for this start-state discounted objective; for \(\gamma=1\) both expressions reduce to the undiscounted episodic case.
Intuition: Increase probability of actions that led to high returns.
Modern Algorithms:
REINFORCE: Basic policy gradient
Actor-Critic: Combines policy gradient with value function
A3C: Asynchronous actor-critic
PPO (Proximal Policy Optimization): Uses a constrained or clipped surrogate update; stability and performance depend on implementation and tuning
SAC (Soft Actor-Critic): Maximum entropy RL
29.7 Bellman Equations, Targets, and a Complete Small MDP
For bounded rewards and \(0\le\gamma<1\), define \((TV)(s)=\max_a\mathbb{E}[r+\gamma V(s')\mid s,a]\), with terminal value zero. The inequality \(|\max_a u_a-\max_a v_a|\le\max_a|u_a-v_a|\) gives \(\|TV-TW\|_\infty\le\gamma\|V-W\|_\infty\). The contraction has a unique fixed point \(V^*\) and exact value iteration obeys \(\|V_k-V^*\|_\infty\le\gamma^k\|V_0-V^*\|_\infty\). This statement concerns exact expectations on a fixed MDP, not automatic convergence of an arbitrary neural approximation.
Example 29.9 (Two states and an absorbing terminal state). In state A, stop terminates with reward 1; go moves to B with reward 0. In B, stop terminates with reward 2; loop stays in B with reward \(.5\). With \(\gamma=.9\), looping forever in B has value \(.5/(1-.9)=5>2\), so \(V^*(B)=5\), \(V^*(A)=.9\cdot5=4.5\). Action values are \[\begin{array}{c|rr} &\text{stop}&\text{go/loop}\\\hline A&1&4.5\\B&2&5\end{array}.\] Starting from \(V_0=(0,0)\), simultaneous updates give \(V_1=(1,2)\), \(V_2=(1.8,2.3)\), \(V_3=(2.07,2.57)\), converging to \((4.5,5)\). The finite initial preference for stopping at B eventually changes as future loop rewards propagate through the backups.
For sampled Q-learning, start every Q-value at zero and use \(\alpha=.5\). A sequence of observed transitions gives these updated entries:
| Transition | TD target | Updated Q entry |
|---|---|---|
| B loop to B | \(.5\) | \(Q(B,loop)=.25\) |
| B stop | \(2\) | \(Q(B,stop)=1\) |
| A go to B | \(.9\max(.25,1)=.9\) | \(Q(A,go)=.45\) |
| B loop to B | \(.5+.9\max(.25,1)=1.4\) | \(Q(B,loop)=.825\) |
| A stop | \(1\) | \(Q(A,stop)=.5\) |
These are bootstrap targets, not complete observed Monte Carlo returns. This short trace is not a convergence proof. In the finite tabular discounted setting, standard sufficient conditions include infinite visits to each state–action pair and per-pair step sizes satisfying \(\sum_t\alpha_t=\infty\), \(\sum_t\alpha_t^2<\infty\), with bounded noise. A fixed \(.5\) step size used for demonstration does not meet the second condition.
Example 29.10 (A DQN batch with terminal masking and mean-loss scaling). For two replay transitions, let rewards be \((2,.5)\), terminal indicators \((1,0)\), and target-network next-state maxima \((100,3)\). With \(\gamma=.9\) the detached TD targets are \((2,3.2)\), not \((92,3.2)\). If current selected-action outputs are \((1,4)\), the mean squared loss is \[L=\tfrac12[(1-2)^2+(4-3.2)^2]=.82,\quad \nabla_{(Q_1,Q_2)}L=(-1,.8).\] Here \(1/2\) is \(1/B\) for batch size two, not the extra half convention for squared loss. In general \(\partial L/\partial Q_i=2(Q_i-y_i)/B\). Targets are held constant during the online update. A target-network copy and random replay reduce some feedback and serial correlation; they do not make samples independent or guarantee stable nonlinear learning.
For a separate Double-DQN next state, online action scores \((5,4)\) choose the first action and target-network values \((1,3)\) evaluate it. At reward zero, Double-DQN target is \(.9\cdot1=.9\), versus ordinary target \(.9\cdot3=2.7\). Selection and evaluation are separated; this does not promise lower error for every transition. A true termination masks bootstrap value. A time-limit truncation may require bootstrapping from the final observation when the underlying task continues; using the observation after an automatic reset is incorrect. Follow the task semantics and Gymnasium’s time-limit guidance.
29.7.1 Deriving the Policy Gradient and Its Baseline
Write a trajectory likelihood as its initial-state density times policy terms and environment transition densities. If the environment does not depend on \(\theta\), then \(\nabla\log P_\theta(\tau)=\sum_t\nabla\log\pi_\theta(a_t\mid s_t)\). Differentiating the expected discounted return gives the score-function estimator. Rewards before action \(a_t\) have zero expected product with its score conditional on the past; removing them yields the reward-to-go formula above, including its outer \(\gamma^t\). Similarly, \[\mathbb{E}_{a\sim\pi_\theta(\cdot\mid s)} [b(s)\nabla\log\pi_\theta(a\mid s)] =b(s)\nabla\sum_a\pi_\theta(a\mid s)=0.\] A state-dependent baseline therefore preserves the expected gradient. Treat a fitted critic’s advantage as constant in the actor loss; the critic has a separate fitting objective. An arbitrary action-dependent baseline does not satisfy this argument without an appropriate correction.
Example 29.11 (A bandit gradient and variance reduction). Choose action 1 with \(p=\sigma(\theta)\); rewards are 2 for action 1 and 0 otherwise. Then \(J=2p\) and \(J'=2p(1-p)\). At \(\theta=0\), \(J'=1/2\). The unbiased sample estimator \(r(a)(a-p)\) equals 1 or 0 with equal probability, so variance is \(.25\). With baseline 1 it becomes \((r(a)-1)(a-p)=.5\) for either action, giving zero variance in this special case. One exact gradient ascent step with \(\eta=.1\) gives \(\theta=.05\) and \(J=1.024995\).
To check discount placement, let two independent Bernoulli actions have this same probability, rewards \(r_0=a_0\), \(r_1=2a_0+a_1\), and \(\gamma=.7\). Then \(J=(1+3\gamma)p\), with derivative \(.775\) at \(\theta=0\). The correct score terms have expectations \(.6\) and \(.175\); omitting the outer \(\gamma\) from the second gives \(.6+.25=.85\), the wrong gradient. For evaluation, freeze the policy and use fresh episodes, initial conditions, and multiple seeds. Replay transitions used for training are not an independent policy-evaluation set; multiple steps within one episode are not independent experimental replicates.
29.8 Applications of RL
Game Playing: AlphaGo, OpenAI Five (Dota 2), AlphaStar (StarCraft)
Robotics: Manipulation, locomotion, drone control
Autonomous Vehicles: Path planning, decision making
Recommendation Systems: Sequential recommendations
Resource Management: Data center cooling, traffic light control
Finance: Trading, portfolio management
Healthcare: Treatment optimization, drug dosing
30 Representation Learning
30.1 Introduction to Representation Learning
Definition 30.1 (Representation Learning). Learning good representations (features) of data automatically, rather than hand-crafting them.
Goal: Discover abstractions that make it easier to extract useful information for downstream tasks.
Good representations:
Capture relevant factors of variation
Disentangle underlying causes
Robust to noise
Transfer across tasks
30.2 Using Autoencoders as Learned Representations
The encoder/decoder definition, architecture diagram, reconstruction objective, linear-PCA equivalence, and VAE derivation are collected in Sections 20.4.5–20.4.7. Here the question is how the learned code is used and constrained. A denoising target remains the clean training input; generating new data requires a specified generative model, such as the VAE, rather than only a small deterministic bottleneck.
30.2.1 Sparse and Contractive Extensions
Let \(z_i=f_{enc}(x_i)\) and \(\hat x_i=f_{dec}(z_i)\). An activation-sparse objective with the same example-mean convention is \[\mathcal{L}_{sparse}=\frac1n\sum_i\left[\|x_i-\hat x_i\|_2^2 +\lambda\|z_i\|_1\right].\] This penalizes latent activations, unlike Lasso’s penalty on model weights. A contractive extension instead adds sensitivity of the encoder: \[\mathcal{L}_{contractive}=\frac1n\sum_i\left[\|x_i-\hat x_i\|_2^2 +\lambda\|J_{enc}(x_i)\|_F^2\right], \quad J_{enc}\in\mathbb{R}^{k\times d}.\] The Jacobian uses the output-by-input convention of Part 0. Both losses sum coordinates and average observations. Decoder capacity and constraints matter: for a freely rescalable linear encoder/decoder, shrinking the code and inversely scaling the decoder can reduce an activation penalty while leaving reconstruction unchanged. A sparsity term alone does not identify a unique representation or its semantics.
30.2.2 Downstream Use and Anomaly Decisions
For a linear probe, freeze the fitted encoder and its inference state, fit only the head with training labels, and select settings on validation data. Fine-tuning is a different procedure that updates the encoder as well. A low reconstruction loss need not imply useful class separation; the PCA/LDA comparison in Section 20.3.1 illustrates this objective mismatch.
For reconstruction-based anomaly detection, declare the reference population, score, and threshold-selection block. High reconstruction error means poor reconstruction under this model; it does not establish a harmful or causal anomaly. An overcomplete model can reconstruct unusual inputs well. Fit preprocessing and the encoder on permitted training records, select any threshold using appropriate validation data, and evaluate the frozen decision using the splitting units and costs in Sections 23.1.1 and 3.4.6. The device workflow in Section 27.9 shows how to separate fitting and decision selection, though its score is a class probability rather than reconstruction error.
30.3 Word Embeddings
30.3.1 Motivation
Definition 30.2 (Word Representation Problem). How to represent words for machine learning?
One-hot encoding: \[\text{``cat''} = [0, 0, 1, 0, \ldots, 0], \quad \text{``dog''} = [0, 0, 0, 1, \ldots, 0]\]
Problems:
High-dimensional (\(|V|\) for vocabulary size)
Sparse (only one 1)
No semantic similarity (all words equally distant)
Solution: Dense, low-dimensional embeddings that capture semantics.
30.3.2 Word2Vec
Definition 30.3 (Word2Vec). Learn word embeddings by predicting context words.
Two architectures:
1. CBOW (Continuous Bag of Words):
Input: Context words
Output: Target (center) word
Predict word from its context
2. Skip-gram:
Input: Target word
Output: Context words
Predict context from word
Training objective (Skip-gram): \[\min\ -\frac{1}{|\mathcal P|}\sum_{(t,u)\in\mathcal P}\log P(w_u\mid w_t),\quad \mathcal P=\{(t,u):1\le t,u\le T,\ 0<|u-t|\le c\}\] where \(c\) is the context window size and only valid in-document pairs enter the mean; no out-of-range boundary tokens are included.
Probability: Use separate input vectors \(\boldsymbol{v}_w\) and output/context vectors \(\boldsymbol{u}_w\): \[P(w_O\mid w_I)=\frac{\exp(\boldsymbol{u}_{w_O}^\top\boldsymbol{v}_{w_I})}{\sum_{w\in V}\exp(\boldsymbol{u}_w^\top\boldsymbol{v}_{w_I})}\]
Word2Vec Properties:
Semantic similarity:
Distributional training can place words with similar contexts nearby; this is an empirical tendency
\(\text{similarity}(\text{``cat''}, \text{``dog''}) > \text{similarity}(\text{``cat''}, \text{``car''})\)
Analogies: \[\boldsymbol{v}_{\text{king}} - \boldsymbol{v}_{\text{man}} + \boldsymbol{v}_{\text{woman}} \approx \boldsymbol{v}_{\text{queen}}\] Such analogy relations can occur empirically; their quality depends on the learned corpus representation.
Composition:
Adding word vectors is a simple composition heuristic; it need not represent a non-compositional phrase such as “New York” accurately
Training efficiency:
Negative sampling: Instead of full softmax over \(|V|\), sample few negative examples
Hierarchical softmax: Use tree structure for faster computation
30.3.3 GloVe
Definition 30.4 (GloVe (Global Vectors)). Learn embeddings by factorizing word co-occurrence matrix.
Objective: \[J = \sum_{\substack{1\le i,j\le |V|\\X_{ij}>0}} f(X_{ij})(\boldsymbol{w}_i^\top \tilde{\boldsymbol{w}}_j + b_i + \tilde{b}_j - \log X_{ij})^2\] where:
\(X_{ij}\): Number of times word \(j\) appears in context of word \(i\)
\(f(X_{ij})\): Weighting function (down-weight rare co-occurrences)
Advantage: Uses global corpus statistics (Word2Vec uses local context).
30.4 Contrastive Learning
Definition 30.5 (Contrastive Learning). Learn representations by contrasting similar and dissimilar examples.
Core idea: Pull similar examples together, push dissimilar ones apart in embedding space.
SimCLR (Simple Framework for Contrastive Learning):
Data augmentation: Create two views of each image (crop, color jitter, etc.)
Encode: Pass through neural network \(f(\cdot)\) to get embeddings
Project: Apply projection head \(g(\cdot)\) to get \(\boldsymbol{z}\)
Contrastive loss: \[\ell_{i,j} = -\log \frac{\exp(\text{sim}(\boldsymbol{z}_i, \boldsymbol{z}_j)/\tau)}{\sum_{k=1}^{2N} \mathbb{1}_{k \neq i} \exp(\text{sim}(\boldsymbol{z}_i, \boldsymbol{z}_k)/\tau)}\] where \(\text{sim}(\boldsymbol{u}, \boldsymbol{v}) = \boldsymbol{u}^\top\boldsymbol{v} / (\left\lVert\boldsymbol{u}\right\rVert\left\lVert\boldsymbol{v}\right\rVert)\) (cosine similarity).
Why Contrastive Learning is Powerful:
Self-supervised: No labels needed! Use data augmentation to create positive pairs.
State-of-the-art results:
SimCLR: Competitive with supervised learning on ImageNet
MoCo (Momentum Contrast): Efficient contrastive learning
CLIP: Contrastive learning of aligned image and text representations; some image-generation systems use such representations, but architectures differ
Applications:
Image classification (pretrain on unlabeled data)
Few-shot learning (good representations with few labels)
Transfer learning (transfer to downstream tasks)
Multi-modal learning (vision + language)
Recent methods:
BYOL (Bootstrap Your Own Latent): No negative pairs needed
SimSiam: Even simpler, still effective
SwAV: Clustering-based contrastive learning
30.5 Embedding Objectives and Their Gradients
The autoencoder and VAE derivations in Part 5 continue to apply here; a representation is evaluated by a declared downstream protocol. A linear probe freezes the fitted encoder, learns a linear head on training labels, and uses validation for selection. Frozen weights also require a declared inference mode for dropout and batch-normalization buffers. Fit vocabularies, whitening, and normalization on permitted training data. Augmented views of one source example must stay in the same split. Using test inputs for representation training is a transductive protocol and must be declared; it is different from a test set withheld from all fitting.
Example 30.6 (A complete skip-gram softmax step). Use input vector \(v=(1,0)^\top\) and context matrix \[U=\begin{pmatrix}0&0\\\log2&1\\\log3&-1\end{pmatrix}.\] For target context 3, \(p=\mathrm{softmax}(Uv)=(1/6,1/3,1/2)^\top\) and \(\ell=-\log p_3=\log2\). With \(e_3=(0,0,1)^\top\), \[\nabla_v\ell=U^\top(p-e_3)=(-.318257,.833333)^\top,\qquad \nabla_U\ell=(p-e_3)v^\top.\] The three rows of the latter are \((1/6,0),(1/3,0),(-1/2,0)\). Simultaneously updating both parameter sets with \(\eta=.1\), using gradients at the old parameters, gives \[v'=(1.031826,-.083333)^\top,\quad U'=\begin{pmatrix}-.016667&0\\.659814&1\\1.148612&-1\end{pmatrix},\] and loss \(.580898\). These coordinates are constructed teaching parameters, not pretrained word meanings. A minibatch loss averages over its valid center–context pairs; each pair contributes once to the gradient before that mean scaling.
Example 30.7 (Negative sampling is a different objective). For one positive score \(u_+^\top v\) and \(K\) sampled negatives, minimize \[\ell_{NS}=-\log\sigma(u_+^\top v) -\sum_{k=1}^K\log\sigma(-u_k^\top v).\] The negative terms are summed within a pair; average pairs over the minibatch. The positive score derivative is \(\sigma(z_+)-1\) and each negative score derivative is \(\sigma(z_k)\). With scalar \(v=1,u_+=\log3,u_-=0,K=1\), loss is \(\log(8/3)=.980829\) and derivatives are \(\partial_{u_+}\ell=-.25\), \(\partial_{u_-}\ell=.5\), \(\partial_v\ell=-(\log3)/4\). Negative sampling depends on its sampling distribution and \(K\); it is not an unbiased estimator of the full-softmax loss or gradient.
For GloVe, include only \(X_{ij}>0\) in the log-count objective and commonly use \(f(x)=\min\{(x/x_{max})^\alpha,1\}\). For one toy term with \(X_{ij}=2,x_{max}=4,\alpha=1\) and predicted log-count \(s=0\), its contribution is \(.5(0-\log2)^2=.240227\), with derivative \(-\log2\) with respect to \(s\). These toy weighting parameters are not claimed as paper defaults. Word-vector analogies and similarity patterns depend on corpus, preprocessing, and training; they are empirical patterns rather than algebraic semantic laws.
30.6 A Fully Specified Contrastive Batch
Example 30.8 (Four views, self masking, and temperature). Take \(N=2\) original examples, two views each, and normalized embeddings \(z_1=z_2=(1,0)\), \(z_3=z_4=(0,1)\). Positive pairs are \((1,2)\) and \((3,4)\). With \(\tau=1\), every anchor’s denominator is \(e+2\), since its self term is excluded but its positive is included. Each positive probability is \(e/(e+2)=.576117\), and \[L=\frac1{2N}\sum_{i=1}^{2N}\ell_{i,j(i)} =\log(e+2)-1=.551445.\] If all four embeddings collapse to the same unit vector, each probability is \(1/3\) and loss is \(\log3=1.098612\). This comparison shows why this objective disfavors collapse on this batch; it is not a global optimization or downstream-generalization guarantee.
For row logits \(a_{ik}=z_i^\top z_k/\tau\), the derivative is \((p_{ik}-\mathbb{1}_{\{k=j(i)\}})/(2N)\) for \(k\ne i\). Backpropagation through dot products adds a factor \(1/\tau\) and includes both anchor and key roles, because each embedding occurs in other rows. For unnormalized network output \(h\), \(z=h/\|h\|\) contributes Jacobian \((I-zz^\top)/\|h\|\); ignoring this changes the gradient. A separate two-image/two-text CLIP-style batch with matched logits 1 and mismatched logits 0 has row and column cross-entropies \(\log(1+e^{-1})=.313262\). Its symmetric loss is the average of the two mean cross-entropies, not their unscaled sum.
31 Ethics and Fairness in Machine Learning
31.1 Bias and Discrimination
Definition 31.1 (Types of Bias in ML). 1. Data Bias:
Historical bias: Data reflects past discrimination
Sampling bias: Training data not representative of population
Measurement bias: Features measured differently for different groups
2. Algorithmic Bias:
Model amplifies existing biases
Optimization objective doesn’t account for fairness
3. Interaction Bias:
Feedback loops: Biased predictions reinforce themselves
Example: Predictive policing \(\to\) more arrests in certain areas \(\to\) model predicts more crime there
Example 31.2 (Audit mechanisms before assigning a fairness conclusion). A hiring model trained on historical selections may reproduce a selective label process; an outcome available only for hired people is not an unbiased label for all applicants. A credit feature can proxy group membership even if a group column is removed. In any such application, specify the measured outcome, affected population, subgroup denominators, error rates, and uncertainty. The historical Gender Shades study audited commercial gender classification by skin type and gender; its scope should not be silently generalized to every facial identification system. The rate calculation below uses synthetic counts so its claims can be checked without relying on a disputed universal description of a deployed product.
31.2 Fairness Definitions
Definition 31.3 (Fairness Metrics). 1. Demographic Parity (Statistical Parity): \[P(\hat{Y} = 1 | A = 0) = P(\hat{Y} = 1 | A = 1)\] Equal positive prediction rates across groups \(A\) (e.g., race, gender).
2. Equalized Odds: \[P(\hat{Y} = 1 | Y = y, A = 0) = P(\hat{Y} = 1 | Y = y, A = 1) \quad \text{for } y \in \{0, 1\}\] Equal TPR and FPR across groups.
3. Equal Opportunity: \[P(\hat{Y} = 1 | Y = 1, A = 0) = P(\hat{Y} = 1 | Y = 1, A = 1)\] Equal TPR (recall) across groups. This is a weaker condition implied by equalized odds, since it does not also constrain FPR.
4. Predictive Parity: \[P(Y = 1 | \hat{Y} = 1, A = 0) = P(Y = 1 | \hat{Y} = 1, A = 1)\] Equal precision across groups.
5. Individual Fairness: Similar individuals should receive similar predictions (harder to formalize).
Fairness Trade-offs:
Compatibility depends on conditions: For groups with different base rates, calibration/predictive parity and equalized error rates are generally incompatible for imperfect, nondegenerate predictors. State the exact fairness definitions and assumptions; there is no unconditional claim that every collection of fairness criteria conflicts.
Accuracy vs Fairness: Often a trade-off
Adding constraints restricts a fixed empirical optimization problem; it cannot improve that problem’s optimum objective under exact optimization
Held-out accuracy and held-out constraint satisfaction remain empirical questions; an empirical constraint does not guarantee population fairness
Which fairness metric to use?
Depends on context and stakeholders
Consider the actual decision, harms, outcome validity, and affected groups
No single rate criterion is automatically appropriate for every application in a domain
Mitigation strategies:
Pre-processing: Transform data to remove bias
In-processing: Add fairness constraints to training
Post-processing: Adjust predictions to satisfy fairness
31.3 Fairness Rates, Base Rates, and Their Compatibility
Example 31.4 (Equalized odds does not imply equal selection or precision). Use two synthetic groups of 100 people each:
| Group | TP | FN | FP | TN | Prevalence | Selection rate |
|---|---|---|---|---|---|---|
| 0 | 16 | 4 | 8 | 72 | \(.2\) | \(.24\) |
| 1 | 40 | 10 | 5 | 45 | \(.5\) | \(.45\) |
Both groups have TPR \(.8\) and FPR \(.1\), so equalized odds and equal opportunity hold on this sample. Group precisions are \(16/24=2/3\) and \(40/45=8/9\); demographic parity and predictive parity do not hold. The second group’s counts coincide with the earlier binary-metric teaching example, now used as one group in a distinct comparison.
For group prevalence \(\pi_g\), common TPR \(t\) and FPR \(f\) imply \[P(\hat Y=1\mid g)=f+\pi_g(t-f),\qquad P(Y=1\mid\hat Y=1,g)=\frac{\pi_g t}{\pi_g t+(1-\pi_g)f}.\] When prevalences differ, the first rates agree only if \(t=f\). For \(t>0,f>0\) the precision expression is strictly increasing in prevalence, so predictive parity cannot also hold. Degenerate cases, such as \(f=0\) with nonzero positive predictions, are exceptions. This is a precise conditional incompatibility, not a statement that all fairness definitions always conflict.
Treat the outcome definition and observation process as part of the audit. An outcome recorded only for selected applicants can make apparent error rates unrepresentative of all applicants. Report group denominators, unavailable outcomes, uncertainty, and relevant intersections; a rate based on two cases is not as precise as the same rate based on thousands. Choose criteria with the people affected and the decision context. Fit any thresholds or constraints on training/validation data and report the frozen policy on held-out groups; repeatedly adjusting it on test-group disparities is another selection loop.
31.4 Explainable AI (XAI)
Definition 31.5 (Explainability). The ability to explain or present ML predictions in understandable terms to humans.
Why important?:
Trust: Users need to trust model decisions
Debugging: Understand why model fails
Governance: Document the applicable decision-review and transparency requirements; mathematical attribution alone does not establish compliance
Fairness: Detect and fix bias
Safety: Critical applications (healthcare, autonomous vehicles)
31.4.1 LIME (Local Interpretable Model-agnostic Explanations)
Definition 31.6 (LIME). Explain individual predictions by approximating the model locally with an interpretable model.
Algorithm:
Select instance \(\boldsymbol{x}\) to explain
Perturb \(\boldsymbol{x}\) to create neighborhood samples
Get predictions from black-box model on perturbed samples
Fit simple interpretable model (e.g., linear regression) weighted by proximity to \(\boldsymbol{x}\)
Explain prediction using interpretable model’s coefficients
Intuition: Fit a simple model locally around the prediction to understand what features matter.
Example 31.7 (LIME for Image Classification). Model predicts “husky” for an image.
LIME highlights image regions:
Green regions: Support prediction (dog’s face, fur)
Red regions: Against prediction (background)
Reveals: Model uses dog features (good) or background snow (bad—spurious correlation)?
31.4.2 SHAP (SHapley Additive exPlanations)
Definition 31.8 (SHAP). Uses Shapley values from cooperative game theory to assign each feature an importance value for a prediction.
Shapley value: Fair distribution of “payout” (prediction) among “players” (features).
Properties:
Local accuracy: Explanation matches prediction
Consistency: If feature contributes more, importance increases
Missingness: A feature absent from the simplified explanation representation has zero attribution
Computation: \[\phi_i = \sum_{S \subseteq F \setminus \{i\}} \frac{|S|!(|F|-|S|-1)!}{|F|!}[v_{\boldsymbol{x}}(S\cup\{i\})-v_{\boldsymbol{x}}(S)]\] Here \(v_{\boldsymbol{x}}(S)\) is the expected model output when features in \(S\) are fixed to the instance and other features are integrated over a declared background distribution. Conditional and interventional definitions differ for dependent features. The baseline is \(v_{\boldsymbol{x}}(\emptyset)\); a model-unused feature need not receive zero under a conditional game with correlated features.
Advantages over LIME:
Theoretical foundation (game theory)
Consistent across models
Can aggregate for global explanations
Using SHAP in Python:
import shap
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# Independent example: X_train and X_test contain numeric model features.
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)
# Declare a tree-path-dependent background and use the Explanation API.
explainer = shap.TreeExplainer(
model, feature_perturbation='tree_path_dependent')
explanations = explainer(X_test)
# Forest classifiers have an output axis for classes; select one explicitly.
class_index = 1 if len(model.classes_) > 1 else 0
if explanations.values.ndim == 3:
explanations = explanations[:, :, class_index]
# Verify the selected baseline and attributions reconstruct its probability.
np.testing.assert_allclose(
explanations.base_values + explanations.values.sum(axis=1),
model.predict_proba(X_test)[:, class_index], atol=1e-6)
shap.plots.beeswarm(explanations) # Global, selected class
shap.plots.waterfall(explanations[0]) # First instance, same classThis example defines its reference distribution using training tree-path counts. Multi-output models require an explicit output selection; see the TreeExplainer documentation. Do not mix one class’s attribution values with another class’s baseline. An interventional explanation with an explicit background dataset defines a different reference game.
31.4.3 Other Interpretability Methods
Attention visualization: Displays attention weights; these weights alone are not a validated explanation of a token’s causal contribution to the prediction
Saliency Maps: Gradient-based methods for images (highlight important pixels)
Partial Dependence Plots (PDP): Show relationship between feature and prediction
Counterfactual Explanations: “What would need to change for different prediction?”
Anchors: Find sufficient conditions for prediction (“If age > 50 AND income > 100K, then approve”)
31.5 Local Explanations with an Explicit Reference Game
Example 31.9 (A weighted local surrogate need not interpolate the query). For perturbed scalar inputs \(z=(0,1,2)\) around query 1, take weights \((1,2,1)\) and black-box output \(f(z)=z^2\). A LIME-style linear surrogate \(g(z)=\beta_0+\beta z\) minimizes \[\frac1S\sum_iw_i[f(z_i)-\beta_0-\beta z_i]^2+\lambda\beta^2, \qquad S=\sum_iw_i=4.\] With design matrix \(Z\) containing an intercept, \(W=\mathrm{diag}(w_i)\) and \(P=\mathrm{diag}(0,1)\), the normal equations give \(\theta=(Z^\top WZ+S\lambda P)^{-1}Z^\top Wf\) when invertible. For \(\lambda=0\), weighted means are \(\bar z=1,\bar f=1.5\), weighted variance numerator 2 and covariance numerator 4, so \(\beta=2,\beta_0=-.5\). Weighted mean squared residual is \(.25\) and \(g(1)=1.5\ne f(1)=1\). For \(\lambda=.5\), the solution is \(\beta=1,\beta_0=.5\), objective \(1.25\); using the unregularized slope in that penalized objective would give \(2.25\). The weight normalization changes the effective regularization, just as mean/sum loss scaling does elsewhere. Results depend on perturbations, locality weights, and output scale.
Example 31.10 (Compute all coalitions and both Shapley contributions). For \(f(x_1,x_2)=x_1+2x_2+3x_1x_2\), query \((1,1)\), and a fixed-zero replacement reference, coalition values are \(v(\varnothing)=0,v(\{1\})=1,v(\{2\})=2,v(\{1,2\})=6\). Averaging the two feature orderings yields \[\phi_1=\tfrac12[(1-0)+(6-2)]=2.5,\quad \phi_2=\tfrac12[(2-0)+(6-1)]=3.5.\] They sum to \(f(1,1)-v(\varnothing)=6\). If the explained output is instead \(\sigma(f)\), use coalition values \(.5,\sigma(1),\sigma(2),\sigma(6)\); contributions become \(.173894\) and \(.323633\), summing to \(\sigma(6)-.5\). Applying a sigmoid separately to raw-output contributions is incorrect.
Example 31.11 (Conditional versus interventional reference distributions). Let \(X_1=X_2\) be a fair Bernoulli variable and the model be \(f(x)=x_1\). At query \((1,1)\), the conditional game \(v(S)=\mathbb{E}[f(X)\mid X_S=x_S]\) has baseline \(.5\), both singleton values 1, and full value 1. It assigns \((\phi_1,\phi_2)=(.25,.25)\) even though the model does not use feature 2. In an interventional replacement game, missing features are drawn from their marginal background law: singleton values are 1 and \(.5\), so contributions are \((.5,0)\). This game evaluates off-support combinations \((0,1)\) and \((1,0)\), making the specified reference important. Neither allocation establishes a causal effect or certifies fairness. Document background data, coalition semantics, explained class, and output scale. Using held-out explanations to redesign a model also consumes the held-out data as selection information.
31.6 Responsible AI Practices
Diverse Teams: Include diverse perspectives in development
Data Auditing: Check training data for bias, representativeness
Fairness Testing: Evaluate model across demographic groups
Transparency: Document data sources, model architecture, limitations
Human Oversight: Keep humans in the loop for critical decisions
Regular Audits: Monitor model performance and fairness in production
Right to Appeal: Allow users to contest automated decisions
Privacy: Control data access and retention; distinguish data locality in federated learning from a formally accounted differential-privacy guarantee
Impact Assessment: Consider societal impact before deployment
Continuous Learning: Stay updated on fairness research and regulations
32 Modern Trends
32.1 Transfer Learning and Fine-Tuning
Definition 32.1 (Transfer Learning). Use knowledge learned from one task (source) to improve learning on a different but related task (target).
Why transfer?
Limited labeled data for target task
Training from scratch is expensive
Pretrained models capture general features
Typical workflow:
Pretrain: Train model on large dataset (e.g., ImageNet)
Transfer: Use pretrained weights as initialization
Fine-tune: Train on target task with small learning rate
Transfer Learning Strategies:
1. Feature Extraction (Frozen Pretrained Model):
Freeze all pretrained layers
Add new layers on top
Train only new layers
Fast, works when target data is small and similar to source
2. Fine-Tuning All Layers:
Unfreeze all layers
Train entire network with small learning rate
Can improve or degrade target performance; validate the chosen strategy and regularization
3. Fine-Tuning Top Layers Only:
Freeze early layers (general features)
Unfreeze later layers (task-specific features)
Balance between feature extraction and full fine-tuning
Success stories:
Computer Vision: ResNet, EfficientNet pretrained on ImageNet
NLP: BERT, GPT pretrained on massive text corpora
Speech: Wav2Vec2 pretrained on unlabeled audio
32.2 Low-Rank Adaptation with Dimensions and Gradients
For a frozen linear map \(W_0\in\mathbb{R}^{d_{out}\times d_{in}}\), LoRA parameterizes \[Wx=W_0x+\frac\alpha r BAx,\qquad A\in\mathbb{R}^{r\times d_{in}},\quad B\in\mathbb{R}^{d_{out}\times r}.\] Only \(A,B\) are trained in this map. Rank of \(BA\) is at most \(r\); the original map need not itself be low rank. The trainable count is \(r(d_{in}+d_{out})\) instead of \(d_{in}d_{out}\), excluding biases and other trained components. For output loss gradient \(g=\nabla_{Wx}\ell\), \[\nabla_B\ell=\frac\alpha r g(Ax)^\top,\qquad \nabla_A\ell=\frac\alpha r B^\top g x^\top.\] Minibatch gradients average these expressions with the same loss normalization as the base task. See the original LoRA paper for the parameterization.
Example 32.2 (A rank-one update calculated end to end). Take \(r=1,\alpha=2\) and \[W_0=\begin{pmatrix}1&0&-1\\0&1&1\end{pmatrix},\quad A=\begin{pmatrix}1&2&0\end{pmatrix},\quad B=\begin{pmatrix}.1\\-.2\end{pmatrix}.\] Then \(\Delta W=\begin{pmatrix}.2&.4&0\\-.4&-.8&0\end{pmatrix}\). At \(x=(1,1,1)^\top\), base output is \((0,2)^\top\) and adapted output is \((.6,.8)^\top\). Five adapter parameters replace six full-map trainable parameters in this deliberately small case. At dimension \(4096\times4096\) and rank 8, counts become 65,536 versus 16,777,216, a factor of 256 for this map’s weights only. It is not a factor-256 reduction in total training memory, which includes activations and optimizer state for other components.
Initializing \(B=0\) and \(A\ne0\) preserves the original map while allowing a nonzero first gradient for \(B\); the first gradient for \(A\) is zero. Initializing both to zero makes both gradients zero for this isolated map. Choose rank, learning rate, and which layers to adapt using validation only. Record pretrained weight provenance, tokenizer, normalization, batch-normalization buffer behavior, and train/evaluation modes. Freezing gradients does not by itself freeze mutable normalization statistics. Transfer can hurt when source and target differ; full fine-tuning has no universal performance advantage.
32.3 Foundation Models
Definition 32.3 (Foundation Models). Large-scale models trained on broad data that can be adapted to a wide range of downstream tasks.
Characteristics:
Trained on massive diverse datasets (web-scale)
Often large, but no fixed parameter-count threshold defines a foundation model
Capabilities beyond any one downstream training task, requiring task-specific evaluation
General-purpose (adapt to many tasks)
Paradigm shift: \[\text{Traditional: Task-specific data} \to \text{Task-specific model}\] \[\text{Foundation: General data} \to \text{Foundation model} \to \text{Many tasks}\]
32.3.1 BERT (Bidirectional Encoder Representations from Transformers)
Definition 32.4 (BERT). Pretrained Transformer encoder (2018, Google).
Pretraining tasks:
Masked Language Modeling (MLM): Select 15% of positions and predict their originals; original BERT uses an 80/10/10 corruption mixture within that selection \[\text{Input: } \text{The [MASK] is on the table}\] \[\text{Predict: } \text{cat}\]
Next Sentence Prediction (NSP): Predict if sentence B follows sentence A
Impact:
State-of-the-art on many NLP tasks
Spawned many variants (RoBERTa, ALBERT, DistilBERT)
Showed power of bidirectional context
32.3.2 GPT (Generative Pre-trained Transformer)
Definition 32.5 (GPT Family). Autoregressive Transformer decoders (OpenAI).
GPT-1 (2018): 117M parameters GPT-2 (2019): 1.5B parameters GPT-3 (2020): 175B parameters GPT-4 (2023): Multimodal; parameter count is not disclosed in the official technical report. Do not treat an external estimate as a verified specification.
Training: Predict next token given previous tokens \[P(w_t | w_1, \ldots, w_{t-1})\]
Historical observation: Larger next-token models have demonstrated varied task capabilities; scaling and this objective alone do not guarantee a particular ability
Few-shot learning: Learn from few examples in prompt
In-context learning: Adapt to task from prompt alone
Chain-of-thought reasoning: Generate step-by-step solutions
GPT-3 Capabilities:
Zero-shot: No examples, just task description
Translate to French: Hello, how are you?
Output: Bonjour, comment allez-vous?
Few-shot: Provide examples in prompt
Q: What is 2+2? A: 4
Q: What is 5+3? A: 8
Q: What is 7+9? A: 16
Illustrative capabilities to evaluate explicitly (performance depends on model, prompting, and scoring):
Arithmetic
Code generation
Common sense reasoning
Instruction following
Limitations:
Hallucinations (generates plausible but false information)
Bias from training data
No grounding in real world
Expensive to run
32.4 Language Objectives, Token Averaging, and Retrieval Boundaries
For a causal language model with a declared start context, \(P_\theta(w_{1:T})=\prod_{t=1}^T P_\theta(w_t\mid w_{<t})\). Its token-mean loss on a masked/padded batch is \[L_{AR}=-\frac{\sum_{b,t}m_{bt}\log P_\theta(w_{bt}\mid w_{b,<t})} {\sum_{b,t}m_{bt}},\] where \(m\) selects valid prediction targets, not padding. The causal attention mask prevents seeing future tokens. This token mean differs from averaging each sequence’s mean equally when sequence lengths differ. For masked language modeling, sum NLL only over the selected positions and divide by their count. Bidirectional context is permitted for this separate objective. In original BERT, 15% of positions were selected; of those, 80% used a mask token, 10% a random token, and 10% the unchanged token. This is not “replace every selected position by MASK.” See Devlin et al. (2019).
Example 32.6 (Likelihood, mean NLL, and perplexity). For three causal targets with true-token probabilities \(.8,.5,.25\), sequence likelihood is \(.1\), total NLL is \(\log10\), mean NLL is \(\log10/3=.767528\), and token perplexity is \(\exp(L)=10^{1/3}=2.154435\). A separate selected MLM target with true-token probability \(.6\) contributes \(-\log.6=.510826\). It does not define a normalized autoregressive likelihood for the whole uncorrupted sentence. Compare perplexities only under compatible tokenization, target masking, context, and evaluation data.
Split by source document, entity, and time before constructing windows. Overlapping train/test windows from the same document can leak near-identical continuations. Fix tokenizer fitting, deduplication, normalization, prompt templates, and model selection before final evaluation. If the pretrained corpus is unknown, explicitly record that benchmark contamination cannot be excluded; a held-out downstream split alone cannot prove its absence.
Example 32.7 (Retrieval-augmented prediction and an index snapshot). For a simplified latent-document model, \[P(y\mid x)=\sum_{d\in\mathcal D}P(d\mid x)P(y\mid x,d).\] With two documents, retrieval weights \(.6,.4\) and answer likelihoods \(.8,.3\), the mixture likelihood is \(.6\), giving NLL \(.510826\). A real top-\(k\) retrieval approximation must declare whether weights are renormalized over the retrieved set; omitted mass changes this formula. Retrieval quality, generated-answer correctness, and support by retrieved evidence are distinct evaluation targets.
Version the index and permit only documents available and authorized at the prediction time. Keep benchmark answer keys and evaluation feedback out of training and prompt selection. Task-authorized evidence documents can contain the facts needed to answer a query: this is intended retrieval, not automatically leakage. The boundary concerns unauthorized or unavailable information and feedback used for selection. Freeze chunking, embeddings, retrieval settings, and prompt choices before final testing. Log which index/model versions and retrieved sources produced the answer so failures can be reproduced.
32.5 Federated Learning
Definition 32.8 (Federated Learning). Train models across decentralized devices without sharing raw data.
Workflow:
Server sends global model to clients
Each client trains on local data
Clients send model updates (not data) to server
Server aggregates updates into global model
Repeat
Aggregation (FedAvg): \[\boldsymbol{w}_{t+1}=\sum_{k\in S_t}\frac{n_k}{\sum_{j\in S_t}n_j}\boldsymbol{w}_{k,t}^{\rm local}\] Here \(S_t\) is the set of participating clients and \(\boldsymbol{w}_{k,t}^{\rm local}\) is client \(k\)’s model after local training initialized from \(\boldsymbol{w}_t\). The weights normalize over participating clients.
Benefits of Federated Learning:
Data locality: Raw training data stays local in the standard protocol; shared updates can still leak information and do not by themselves provide a formal privacy guarantee
Reduced latency: On-device inference
Data governance: Local training can support data-residency requirements, but does not by itself establish regulatory compliance
Communication trade-off: Exchange model updates instead of raw records; large models and many rounds can still be costly
Challenges:
Non-IID data: Each client has different distribution
Communication cost: Many rounds needed
Heterogeneous devices: Different compute power
Privacy attacks: Model updates can leak information
Applications:
Mobile keyboards (Gboard)
Healthcare (multiple hospitals, can’t share patient data)
Finance (banks collaborate without sharing data)
IoT devices
Enhanced privacy:
Differential privacy: Bound contributions and calibrate noise under a declared adjacency and composition accountant
Secure aggregation: Conceal individual updates from the aggregator under its protocol assumptions; this is distinct from differential privacy
Homomorphic encryption: Compute on encrypted data
32.6 FedAvg, Client Drift, and a Concrete Privacy Guarantee
If client \(k\) minimizes a local mean loss \(F_k(w)\) and \(n_k\) is its sample count, the population-weighted empirical objective is \(F(w)=\sum_k(n_k/\sum_jn_j)F_k(w)\). With all clients participating and one full local gradient step from the same \(w\), averaging gives \(\sum_kp_k[w-\eta\nabla F_k(w)]=w-\eta\nabla F(w)\). Multiple local steps generally break this equality. Sample weighting must not multiply an already summed local loss a second time. See the original FedAvg paper.
Example 32.9 (Two clients with different curvatures). Client 1 has \(n_1=2,F_1=(w-1)^2\); client 2 has \(n_2=3,F_2=2(w+1)^2\). These are mean squared losses: the second can arise from identical examples \(x=\sqrt2,y=-\sqrt2\). Global loss is \(F=.4F_1+.6F_2\), with \(F'(w)=3.2w+1.6\) and optimum \(w^*=-.5\). At \(w_0=0,\eta=.1\), one local step gives \(.2,-.4\), averaging to \(-.16\), the same as one centralized step. Two local steps give \(.36,-.64\), averaging to \(-.24\). Two centralized steps instead give \(-.2688\).
The two-local-step round map is \(w_{t+1}=.472w_t-.24\), whose fixed point is \(-5/11\approx-.454545\), not \(-.5\). Objective excess is \(F(w)-F(w^*)=1.6(w+.5)^2\). This simple deterministic example exhibits persistent client drift at a fixed step size. If only client 1 participates, its first update is \(.2\); normalizing over participating counts does not make this an unbiased global step \(-.16\). Sampling probabilities and the targeted client population matter. Evaluate on held-out clients or future periods according to the desired deployment target, rather than on local training loss.
Definition 32.10 (Differential privacy with an explicit adjacency unit). A randomized mechanism \(M\) is \((\epsilon,\delta)\)-differentially private when, for all adjacent datasets \(D,D'\) and measurable events \(S\), \[P(M(D)\in S)\le e^\epsilon P(M(D')\in S)+\delta.\] State whether adjacency replaces one record, adds/removes one record, or changes one entire client’s data. These are different privacy promises. Raw-data locality and secure aggregation alone do not establish this inequality.
Example 32.11 (Sensitivity, Laplace noise, and composition). For \(n=100\) fixed records bounded in \([0,1]\) under replacement adjacency, the mean has sensitivity \(\Delta=1/100=.01\). Release \(M(D)=\bar x+Z\), \(Z\sim\mathrm{Laplace}(0,b)\) with \(b=\Delta/\epsilon\). For \(\epsilon=1\), \(b=.01\) and noise standard deviation is \(\sqrt2b=.014142\). The reverse triangle inequality bounds the ratio of densities by \(\exp(|\bar x-\bar x'|/b)\le e^\epsilon\), proving pure DP (\(\delta=0\)). The bound requires the declared clipping/boundedness; an arbitrary unbounded mean has no such finite global sensitivity.
Publishing \(T\) such mechanisms with budgets \(\epsilon_t\) has the basic pure-DP composition budget at most \(\sum_t\epsilon_t\), including adaptive releases under the corresponding per-step conditions. Releasing the noisy mean and then revealing the original mean defeats the mechanism’s privacy claim. Client-level sensitivity for a federated model requires a different derivation, usually involving bounded client updates and a declared participation process. For scalar squared loss \((w-y)^2\), sharing gradient \(g=2(w-y)\) at known \(w\) reveals \(y=w-g/2\) exactly: keeping raw labels local is insufficient by itself.
32.7 AutoML (Automated Machine Learning)
Definition 32.12 (AutoML). Automate the end-to-end process of applying ML to real-world problems.
Components:
Data preprocessing
Feature engineering
Model selection
Hyperparameter optimization
Architecture search (for neural networks)
Ensemble construction
32.7.1 Neural Architecture Search (NAS)
Definition 32.13 (NAS). Automatically design neural network architectures.
Search space: Define possible architectures (layers, connections, operations)
Search strategy:
Random search
Reinforcement learning
Evolutionary algorithms
Gradient-based (DARTS)
Performance estimation:
Train from scratch (expensive)
Early stopping
Weight sharing (ENAS)
Performance prediction
Assessment: Search-discovered architectures can perform well under stated datasets and budgets; compare against tuned baselines with matched training/search resources rather than assuming universal superiority.
32.7.2 AutoML Tools
Auto-sklearn: Automated scikit-learn pipeline
TPOT: Genetic programming for pipeline optimization
H2O AutoML: Automated model selection and ensembling
Google Cloud AutoML: Managed AutoML service
AutoKeras: NAS for Keras
PyCaret: Low-code ML library
AutoML: Democratization or Threat?
Pros:
Lowers barrier to entry (non-experts can use ML)
Frees experts to focus on problem formulation
Often finds better models than manual search
Reproducible workflows
Cons:
Can be slow (lots of trials)
Black box (hard to understand choices)
May not consider domain constraints
Expensive (compute cost)
Reality: AutoML is a tool, not a replacement. ML expertise still needed for:
Problem formulation
Data quality assessment
Interpreting results
Debugging failures
Ethical considerations
32.8 Automated Search Still Needs an Evaluation Boundary
Example 32.14 (Selection optimism without any biased single-model score). Two candidate models both have true risk \(.2\). Suppose each validation estimate independently equals \(.15\) or \(.25\) with equal probability. Each estimate is unbiased. Selecting the smaller gives \(.15\) with probability \(3/4\) and \(.25\) with probability \(1/4\), so the reported selected validation risk has expectation \(.175\), below \(.2\). A new independent test estimate remains centered on \(.2\). Automating the search over preprocessing, features, architectures, prompts, and thresholds does not remove this minimum-selection effect. Include the whole adaptive procedure inside the outer evaluation boundary, record trial budgets and random seeds, and compare with fixed-budget baselines. A larger search budget is an additional experimental resource, not a free improvement.
32.9 A Quantization Error Calculation and Its Deployment Consequences
Example 32.15 (Symmetric signed 8-bit weights). Let \(s=\max_j|w_j|/127\) and \(q_j=\mathrm{clip}(\mathrm{round}(w_j/s),-127,127)\), \(\tilde w_j=sq_j\). Define a harmless positive scale, such as 1, for an all-zero weight tensor. Without clipping overflow, \(|\tilde w_j-w_j|\le s/2\). For \(w=(-1,-.1,.3,1)\), \(s=1/127\), codes are \((-127,-13,38,127)\) and reconstructed weights are \((-1,-.102362,.299213,1)\). For \(x=(1,2,-1,1)\), original dot product is \(-.5\) and reconstructed value is \(-64/127=-.503937\). Its absolute error \(1/254\) obeys \[|x^\top(\tilde w-w)|\le\|x\|_1\|\tilde w-w\|_\infty \le 5/254.\] Weight-only 32-bit to 8-bit storage has an ideal factor of four before scales, metadata, and other tensors. It does not imply a fourfold latency improvement: kernels, hardware, activation precision, and memory traffic determine speed. Activation clipping ranges are learned on an allowed calibration dataset, not final test data. This quantizer-calibration role is distinct from probability calibration. If quantization changes the base scores, revalidate probability calibration and decisions with appropriate non-test blocks before freezing the new complete artifact. Include threshold-near inputs in parity checks.
32.10 Reading and Reproducing Parts 6–8
The numerical figures are generated by scripts/build_batch4_figures.py, with explicit fixtures in scripts/batch4_examples.py. Their manifest records versions, seed, figure names, and the fixed workflow report. Validation checks analytic calculations against independent enumeration, finite differences, library metrics, and saved-artifact predictions. The workflow, service, export adapter, and validation report distinguish executed paths from optional framework recipes. The source-specific links in these sections point to primary papers or official documentation; historical model examples are dated illustrations, not an inventory of current products.
For the original formulations, see negative sampling, SimCLR, LIME, SHAP, and retrieval-augmented generation. For privacy definitions, the Laplace mechanism, and basic composition, see Dwork and Roth’s monograph. The small numerical fixtures above are constructed here to expose the calculations.
The whole-book audit runs the retained P0 checks, all three expansion-batch validators, and the final consistency checks. From the repository root, in the Python environment described in Part 7, use:
python -m pip install -r scripts/requirements-final-review.txt
python scripts/validate_final.py
latexmk -pdf main.texOn macOS, the XGBoost wheel also needs a compatible OpenMP runtime; this audit used Homebrew’s libomp. Python package pins do not install that system library. Inspect rendered figures and changed pages after compilation; numerical checks do not replace layout review.
32.11 Future Directions
Emerging Trends and Open Problems:
1. Multimodal Learning:
Models that understand multiple modalities (text, image, audio, video)
CLIP, DALL-E, Flamingo, GPT-4
2. Continual Learning:
Learn new tasks without forgetting old ones
Overcome catastrophic forgetting
3. Few-Shot and Zero-Shot Learning:
Learn from very few examples
Generalize to unseen classes
4. Causal Machine Learning:
Go beyond correlation to causation
Study transport across environments under explicit causal identification and invariance assumptions
Counterfactual reasoning
5. Energy-Efficient ML:
Measure training/inference energy and report hardware, utilization, runtime, and carbon-intensity assumptions
Model compression, pruning, quantization
Efficient architectures
6. Trustworthy AI:
Robustness to adversarial attacks
Uncertainty quantification
Certified defenses
7. Human-AI Collaboration:
AI as assistant, not replacement
Interactive ML
Human-in-the-loop systems
8. Quantum Machine Learning:
Leverage quantum computers for ML
Quantum neural networks
Any speedup claim needs explicit data-access, hardware, noise, and classical-baseline assumptions
32.12 Conclusion
Machine Learning is a rapidly evolving field with profound impact on society. As practitioners, we must:
Master fundamentals: Strong foundation enables understanding new methods
Stay curious: New papers, techniques, applications emerge daily
Think critically: Not every problem needs ML; not every solution is ethical
Embrace uncertainty: Models are tools, not truth
Prioritize ethics: Consider impact on individuals and society
Collaborate: ML is interdisciplinary—work with domain experts
Keep learning: The field evolves faster than any textbook
The journey from mathematical foundations to modern foundation models is remarkable. Yet the most exciting developments are still ahead. Whether through scientific breakthroughs, ethical frameworks, or novel applications, the future of ML will be shaped by thoughtful practitioners who combine technical skill with wisdom.
Your role: Build systems that are not just intelligent, but beneficial.
Exercise 32.16.
Design a Q-learning agent for a simple grid world. Define states, actions, rewards, and write the Q-update rule.
Explain why experience replay and target networks are crucial for DQN stability. What problems do they solve?
Compare PCA (from Part 5) and autoencoders for dimensionality reduction. When would you prefer autoencoders?
Using a specified embedding corpus, test whether the king/man/woman/queen analogy holds. Explain how corpus statistics, retrieval metric, and exclusions affect the result rather than assuming the identity always works.
A facial recognition system has 99% accuracy but 5% false positive rate for one demographic group vs 1% for another. Which fairness definition is violated? Propose a mitigation strategy.
You have 100 labeled examples and 10,000 unlabeled examples for image classification. Design a strategy using transfer learning and/or contrastive learning.
Compare fine-tuning BERT for sentiment analysis vs training a CNN from scratch. What are the trade-offs?
Design a federated learning system for predicting disease from hospital data. Address: communication efficiency, privacy, and non-IID data distributions.
End of Machine Learning Notes
“The best way to predict the future is to invent it.” — Alan Kay