Reference sheet

Machine Learning reference sheet

The main definitions, formulas, metrics and algorithms of the machine learning course on one page, unit by unit, with links to the lessons that explain each topic in full.

For Machine Learning

This sheet follows the fifteen units of the course in order. Each unit starts with the big idea in a few sentences, then gives the definitions, formulas, metrics and algorithms you will look up most often, with the assumptions they need. When you want the full explanation, a derivation or more examples, follow the lesson links under each topic. The numerical examples use small constructed data, chosen so that every number can be checked by hand.

A data set has nn examples and pp features. The feature vector of example ii is the column xi∈Rp\mathbf{x}_i \in \mathbb{R}^p, the design matrix XX has the rows xi⊤\mathbf{x}_i^{\top} and size n×pn \times p, the targets form the vector y\mathbf{y}, and a prediction is y^\hat{y}. Vectors are bold lowercase, matrices are capitals and scalars are italic. A linear model has weights w\mathbf{w} and an intercept bb, and a general parameter vector is θ\boldsymbol{\theta}. A hat marks an estimate or a fitted value, so θ^\hat{\theta} estimates the parameter θ\theta. The transpose is X⊤X^{\top}, and ∥v∥2\lVert \mathbf{v} \rVert_2 and ∥v∥1\lVert \mathbf{v} \rVert_1 are the Euclidean norm and the sum of the absolute entries.

A loss L(y,y^)L(y, \hat{y}) scores one prediction y^\hat{y} of the target yy. The empirical risk of a predictor ff is its average loss on the nn training examples, and its population risk is its expected loss on a new example (x,y)(\mathbf{x}, y) drawn from the data distribution PP,

R^n(f)=1n∑i=1nL(yi,f(xi)),R(f)=E(x,y)∼P[L(y,f(x))].\begin{gathered} \hat{R}_n(f) = \frac{1}{n}\sum_{i=1}^{n} L(y_i, f(\mathbf{x}_i)), \\[0.4em] R(f) = E_{(\mathbf{x}, y) \sim P}\big[L(y, f(\mathbf{x}))\big]. \end{gathered}

Probabilities are written P(⋅)P(\cdot) and P(Y=1∣x)P(Y = 1 \mid \mathbf{x}), expectations E[⋅]E[\cdot] and variances Var⁡(⋅)\operatorname{Var}(\cdot). The letter σ\sigma is a standard deviation, except that σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}) applied to a score zz is the logistic sigmoid and σ1≥σ2≥⋯\sigma_1 \ge \sigma_2 \ge \cdots are the singular values of a matrix. The learning rate is η\eta, and log⁡\log is the natural logarithm unless a base is written. Training data fit a model, validation data choose among models and settings, and test data are used once at the end to estimate performance on new cases. A feature that predicts the target well is a predictive association, not evidence that changing the feature would change the outcome.

Learning Problems, Data, and a First Model

A learning task names what is predicted, from which information, at what time and for which decision. The data are split by role before any model-driven choice, every preprocessing rule is learned from the training data alone, and a first model is judged against a simple baseline on data it has not seen.

Learning tasks, features and targets

Machine learning fits a prediction rule, or a description of structure, from examples instead of writing the rule by hand.

SettingDataGoalExample
Regressionfeatures with a numerical targetpredict the numberdelivery time in minutes
Classificationfeatures with a categorical targetpredict the class or its probabilitylate or on time
Unsupervised learningfeatures onlyfind groups, directions or unusual casesgroups of similar customers
Reinforcement learningstates, actions and rewards that depend on the learner’s own choiceschoose actions with a large long-run rewardchoosing delivery routes

Regression and classification are supervised learning, since every training example has a recorded target. The unit of observation is what one row describes, such as one parcel or one customer on one day, and rows that share a customer or a time period need not be independent. A feature is a value available when the prediction is made, the target is the quantity to predict, and the label is the recorded target of one example. Prediction time is the moment the prediction is made, and the prediction horizon is how far ahead of it the target lies. A data schema lists every column with its meaning, type, units and the time at which it becomes known.

Target leakage is a feature that carries information about the target but is not available at prediction time, such as the actual arrival time used to predict whether a parcel will be late. A baseline is a simple rule that any proposed model has to beat, such as the training mean of the target or the most frequent training class. A model that predicts well can still be useless for deciding what to change, because prediction and causation are different questions.

Lessons What Is Machine Learning?, Features, Targets, and Prediction Time

Arrays and tables in Python

A NumPy array has a shape, the tuple of its sizes along each axis. A design matrix is a two-dimensional array of shape (n, p), a target vector has shape (n,), and a pandas DataFrame is a table with named columns of possibly different types that converts to such arrays.

OperationCodeResult for X of shape (n, p)
Select rowsX[0:3]the first three rows, shape (3, p)
Column meansX.mean(axis=0)one mean per feature, shape (p,)
Row sumsX.sum(axis=1)one value per example, shape (n,)
Elementwise productA * Bentry by entry, for arrays of the same shape
Matrix productX @ wone prediction per row, shape (n,), for w of shape (p,)
BroadcastingX - X.mean(axis=0)every column minus its own mean

Broadcasting stretches an axis of length 1, or a missing leading axis, to match the other array. It never stretches an axis of any other length, so arrays of shapes (3, 2) and (2,) combine, while (3, 2) and (3,) do not. The product A * B multiplies matching entries and is not the matrix product A @ B. A notebook runs code in cells, and the order in which cells were run can differ from their order on the page, so rerun a notebook from the top before trusting its results.

Lessons Python Arrays and Tables for Machine Learning

Training, validation and test sets

SetJobUsed
Training setfits the model parameters, the values learned from data such as weightsfor every fit
Validation setcompares models and chooses hyperparameters, the settings fixed before fitting such as kk in nearest neighborsduring development
Test setestimates performance after every choice is frozenonce, at the end

Generalization is good performance on new cases from the deployment population, the cases the model will meet in use. A test score estimates performance only for data drawn the way the test data were drawn. Choosing anything because of a test score makes the test set part of development, and its score is then optimistic.

A constant baseline predicts one value for every case. On the training data the best constant is the mean of the targets for squared error, a median for absolute error and the most frequent class for accuracy. A model that does not beat this baseline on validation data shows no useful gain from its features.

Lessons Training, Validation, and Test Sets

Data leakage and honest splitting

Data leakage is any route by which information that will not be available at prediction time, or information from the evaluation data, reaches model fitting or model selection. The information boundary separates what the model may use from what it may not.

LeakageHow it happensPrevention
Target leakagea feature recorded after the outcome or computed from itkeep only features known at prediction time
Duplicate leakagethe same or a nearly identical record on both sides of a splitremove duplicates before splitting
Group leakagerows of one customer, patient or device on both sidessplit by group
Temporal leakagelater data used to predict earlier outcomessplit by time
Preprocessing leakagescaling, imputation, encoding or feature selection fitted on all the datafit every step on the training part only

A random row split suits rows that are independent and exchangeable. A group split keeps all rows of one group on the same side and estimates performance for new groups. A temporal split trains on earlier data and evaluates on later data, which matches forecasting and any use in which the model predicts the future. The split has to match the intended use, so the right choice depends on the question as well as on the data.

Lessons Data Leakage and Honest Splitting

Exploratory analysis and missing data

Exploratory data analysis checks units, types, ranges, duplicates, missing values and distributions before modeling. Exploration that looks at the target belongs on the training data, so that the evaluation data stay unseen. The empirical distribution of a sample puts mass 1/n1/n on each observed value. Its mean is the average, its median the middle ordered value or the average of the two middle values, and a qq quantile has a fraction of about qq of the data at or below it under a stated rule. A histogram shows counts in bins. An outlier lies far from the bulk of the data, which is a reason to check the record, and a valid extreme value stays in the data.

MechanismThe probability that a value is missingConsequence
Missing completely at randomdoes not depend on any data, observed or notthe complete cases are a random subset of the rows
Missing at randomdepends only on observed valuesmethods that use those observed values can correct for it under this assumption
Missing not at randomdepends on the unobserved value itself, even given the observed onesthe observed data cannot correct it without further assumptions

These mechanisms are assumptions, and observed data alone generally cannot tell the last two apart. Imputation fills a missing value with a modeling input, such as a training mean, a training median or a prediction from other features, and it does not recover the true value. A missingness indicator is a feature equal to 1 when the value was missing and 0 otherwise, which lets a model use the fact of missingness. Complete-case analysis drops every row with a missing value. Under missing completely at random this only loses data, while under the other mechanisms the complete cases can differ systematically from the rest. A row with a missing target is left out of fitting and scoring, since an imputed label is not an observation. Every imputation rule is fitted on the training data alone.

Lessons Exploratory Data Analysis and Data Quality, Missing Data and Reliable Imputation

Feature scaling and categorical encoding

Standardization uses the mean and standard deviation of each feature on the nn training rows,

xˉj=1n∑i=1nxij,sj=1n∑i=1n(xij−xˉj)2,zij=xij−xˉjsj,\begin{gathered} \bar{x}_j = \frac{1}{n}\sum_{i=1}^{n} x_{ij}, \\[0.4em] s_j = \sqrt{\frac{1}{n}\sum_{i=1}^{n}(x_{ij} - \bar{x}_j)^2}, \\[0.4em] z_{ij} = \frac{x_{ij} - \bar{x}_j}{s_j}, \end{gathered}

and applies the same xˉj\bar{x}_j and sjs_j unchanged to validation, test and future rows. The course divides by nn here, and dividing by n−1n - 1 is another convention, so record which one a fitted scaler used. A column with sj=0s_j = 0 is constant on the training data and the division is undefined, so a stated convention is needed, such as dividing by 1 after centering, which turns the column into zeros, or dropping it. Standardized training columns with sj>0s_j > 0 have mean 0 and standard deviation 1, and standardizing does not make a distribution normal. Min-max scaling maps xx to (x−mj)/(Mj−mj)(x - m_j)/(M_j - m_j) with the training minimum mjm_j and maximum Mj>mjM_j > m_j, and new values can fall outside [0,1][0, 1].

For example, training weights of 2, 4, 6 and 8 kilograms have mean 5 and standard deviation 5≈2.236\sqrt{5} \approx 2.236, so a new parcel of 9 kilograms gets z=4/5≈1.789z = 4/\sqrt{5} \approx 1.789. Scaling matters for distances. With weight in kilograms and distance in kilometers, the query (2,5)(2, 5) has squared distances 5 to (3,7)(3, 7) and 9.019.01 to (5,5.1)(5, 5.1), while with distance in meters the squared distances become 4,000,001 and 10,009, and (5,5.1)(5, 5.1) becomes the nearer point.

One-hot encoding turns a categorical feature with categories c1,…,cKc_1, \dots, c_K into KK indicator columns, where column kk is 1 for an example of category ckc_k and 0 otherwise. It imposes no order on the categories. Next to an intercept the KK columns add up to the column of ones, so one category is dropped as the reference level or a penalty is used. An ordinal category with a meaningful order, such as small, medium and large, can be coded as ordered integers when equal steps between levels are acceptable. The list of categories is learned from the training data, and an unknown category at prediction time needs a stated rule, such as a row of zeros or an explicit column for other categories.

Lessons Feature Scaling and Categorical Encoding

K-nearest neighbors

For a query x\mathbf{x}, k-nearest neighbors finds the kk training examples with the smallest Euclidean distance

d(x,xi)=∑j=1p(xj−xij)2.d(\mathbf{x}, \mathbf{x}_i) = \sqrt{\sum_{j=1}^{p}(x_j - x_{ij})^2} .

Classification predicts the majority class among those kk neighbors, and k-nearest neighbor regression predicts the mean of their targets. A tie-breaking rule has to be stated, both for equal distances at the kkth place and for a tied vote, for example the class of the single nearest neighbor or the smallest class index. The number of neighbors kk is chosen on validation data, and the features are scaled with training statistics first, because the distance adds squared differences in whatever units the features have. A small kk gives a flexible and noisy rule, k=1k = 1 returns the stored label of any training input that is not repeated, and k=nk = n predicts the training majority class or the training mean everywhere.

For the query (1,0)(1, 0) and the training points (0,0)(0, 0) labeled red, (2,0)(2, 0) labeled blue and (0,2)(0, 2) labeled blue, the distances are 1, 1 and 5≈2.236\sqrt{5} \approx 2.236. With k=1k = 1 two points of different classes tie, so the answer depends on the tie rule, while k=3k = 3 predicts blue by a vote of 2 to 1.

Lessons K-Nearest Neighbors

Overfitting, underfitting and model complexity

Training error is the average loss on the data used for fitting, and validation error is the average loss on held-out data. Model complexity is the flexibility of the fitted rule, such as a small kk in nearest neighbors, a high polynomial degree or a deep tree.

PatternTraining errorValidation errorTypical cause
Underfittinghighhigh, close to trainingthe model is too simple for the pattern
Good fitlowlow, a little above trainingflexibility matches the signal
Overfittingvery lowclearly higher than trainingthe model follows noise in the training data

As complexity grows, training error usually falls, while validation error often falls and then rises. That shape is common but not a theorem, and a gap between the two errors can also come from noise in a small validation set or from a difference between the two sets. A memorizing predictor stores the training rows and returns the stored label, which gives zero training error whenever no input appears twice with different labels, and it says nothing about new inputs.

Lessons Overfitting, Underfitting, and Model Complexity

Linear Algebra and Calculus for Learning

A data table becomes a design matrix, and a linear model turns it into one prediction per row. Span, rank and projection decide which predictions a linear model can produce and when its coefficients are unique. Derivatives show how a loss changes with each parameter, and gradient descent uses them to move downhill with a step size small enough for the curvature.

Feature vectors, design matrices and linear predictions

The dot product of w\mathbf{w} and x\mathbf{x} in Rp\mathbb{R}^p is w⊤x=w1x1+⋯+wpxp\mathbf{w}^{\top}\mathbf{x} = w_1x_1 + \cdots + w_px_p. A linear prediction for one example and for all nn examples at once is

y^=w⊤x+b,y^=Xw+b1,\begin{gathered} \hat{y} = \mathbf{w}^{\top}\mathbf{x} + b, \\[0.4em] \hat{\mathbf{y}} = X\mathbf{w} + b\mathbf{1}, \end{gathered}

where XX is n×pn \times p, w\mathbf{w} has pp entries, 1\mathbf{1} is the column of nn ones and y^\hat{\mathbf{y}} has nn entries. Entry ii of the matrix-vector product XwX\mathbf{w} is xi⊤w\mathbf{x}_i^{\top}\mathbf{w}, and the product needs exactly as many entries in w\mathbf{w} as XX has columns. Adding an intercept column of ones gives the augmented design matrix X~=[1  X]\tilde{X} = [\mathbf{1} \; X] of size n×(p+1)n \times (p + 1) and the parameter vector θ=(b,w)\boldsymbol{\theta} = (b, \mathbf{w}), so that y^=X~θ\hat{\mathbf{y}} = \tilde{X}\boldsymbol{\theta} is a single product. The intercept column is a modeling device, not a feature.

For example, with weights of 2 minutes per kilometer and 0.50.5 minutes per package and an intercept of 10 minutes, a delivery of 12 kilometers with 4 packages gets y^=10+2⋅12+0.5⋅4=36\hat{y} = 10 + 2 \cdot 12 + 0.5 \cdot 4 = 36 minutes.

Lessons Vectors, Matrices, and Linear Predictions

Norms, rank and orthogonal projection

The Euclidean norm is ∥v∥2=v⊤v\lVert \mathbf{v} \rVert_2 = \sqrt{\mathbf{v}^{\top}\mathbf{v}}, and two vectors are orthogonal when their dot product is 0. The span of some vectors is the set of their linear combinations, and the column space of XX is the span of its columns, the set of all possible XwX\mathbf{w}. The columns are linearly independent when Xw=0X\mathbf{w} = \mathbf{0} only for w=0\mathbf{w} = \mathbf{0}, and the rank of XX is the largest number of linearly independent columns, the dimension of the column space.

The orthogonal projection of y\mathbf{y} onto a subspace is the unique vector y^\hat{\mathbf{y}} of the subspace with y−y^\mathbf{y} - \hat{\mathbf{y}} orthogonal to the whole subspace, and it is the point of the subspace closest to y\mathbf{y}. Onto the span of one nonzero vector a\mathbf{a},

y^=a⊤ya⊤a a.\hat{\mathbf{y}} = \frac{\mathbf{a}^{\top}\mathbf{y}}{\mathbf{a}^{\top}\mathbf{a}}\,\mathbf{a} .

For a=(1,2)\mathbf{a} = (1, 2) and y=(3,1)\mathbf{y} = (3, 1), both a⊤y\mathbf{a}^{\top}\mathbf{y} and a⊤a\mathbf{a}^{\top}\mathbf{a} equal 5, so y^=(1,2)\hat{\mathbf{y}} = (1, 2), and the difference y−y^=(2,−1)\mathbf{y} - \hat{\mathbf{y}} = (2, -1) is orthogonal to a\mathbf{a}. The projection is unique even when the coefficients are not. If the column is duplicated, X=[a  a]X = [\mathbf{a} \; \mathbf{a}], every w\mathbf{w} with w1+w2=1w_1 + w_2 = 1 gives the same y^\hat{\mathbf{y}}.

A square matrix is singular when it has no inverse, which happens exactly when its columns are linearly dependent, and X⊤XX^{\top}X is invertible exactly when XX has full column rank. Conditioning describes near dependence. For XX with full column rank, the condition number κ(X)=σmax⁡/σmin⁡\kappa(X) = \sigma_{\max}/\sigma_{\min} is the ratio of its largest and smallest singular values, and a large value means that small changes in the data can move the solution a lot, even though the matrix is not exactly singular.

Lessons Vector Geometry, Rank, and Projection

Derivatives, gradients and the chain rule

The derivative of ff at tt is

f′(t)=lim⁡h→0f(t+h)−f(t)hf'(t) = \lim_{h \to 0}\frac{f(t + h) - f(t)}{h}

when this limit exists, and ff is differentiable at tt when it does. The partial derivative ∂f/∂θj\partial f/\partial \theta_j differentiates in θj\theta_j with the other coordinates held fixed. The gradient ∇f(θ)\nabla f(\boldsymbol{\theta}) is the column of partial derivatives in the order of the parameter vector, so it has the same shape as θ\boldsymbol{\theta}. For differentiable ff, the directional derivative along a unit vector u\mathbf{u} is ∇f(θ)⊤u\nabla f(\boldsymbol{\theta})^{\top}\mathbf{u}, a nonzero gradient points in the direction of steepest increase, and f(θ+Δ)≈f(θ)+∇f(θ)⊤Δf(\boldsymbol{\theta} + \boldsymbol{\Delta}) \approx f(\boldsymbol{\theta}) + \nabla f(\boldsymbol{\theta})^{\top}\boldsymbol{\Delta} for small Δ\boldsymbol{\Delta}.

The chain rule says that if L=g(u)L = g(u) and u=h(θ)u = h(\theta), then dL/dθ=g′(u) h′(θ)dL/d\theta = g'(u)\,h'(\theta), and when θ\theta affects LL through several paths the contributions of the paths add. For one example with feature xx and target yy, the squared error L(w,b)=(wx+b−y)2L(w, b) = (wx + b - y)^2 has

∂L∂w=2(wx+b−y) x,∂L∂b=2(wx+b−y).\begin{gathered} \frac{\partial L}{\partial w} = 2(wx + b - y)\,x, \\[0.4em] \frac{\partial L}{\partial b} = 2(wx + b - y). \end{gathered}

With x=2x = 2, y=5y = 5, w=1w = 1 and b=0b = 0 the prediction misses by −3-3, so the partial derivatives are −12-12 and −6-6. The central difference (f(t+h)−f(t−h))/(2h)(f(t + h) - f(t - h))/(2h) approximates f′(t)f'(t) with an error of order h2h^2 for smooth ff. Agreement between it and a coded derivative is a numerical check, not a proof. Where ff is not differentiable, as ∣u∣\lvert u \rvert at 0, a stated convention or a subgradient is needed.

Lessons Derivatives, Partial Derivatives, and the Chain Rule

Gradient descent and convexity

An objective function is the quantity a training method minimizes. Gradient descent repeats

θt+1=θt−η ∇J(θt)\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta\,\nabla J(\boldsymbol{\theta}_t)

with a learning rate η>0\eta > 0. At a differentiable point with nonzero gradient the negative gradient is a descent direction, so a small enough step lowers JJ, but a large step can raise it. A stationary point has ∇J=0\nabla J = \mathbf{0}. A local minimum is lowest within a neighborhood and a global minimum is lowest overall.

For J(w)=(w−3)2J(w) = (w - 3)^2 the gradient at w=0w = 0 is −6-6, and one step with η=0.1\eta = 0.1 gives w=0.6w = 0.6. Each step multiplies the error w−3w - 3 by 1−2η1 - 2\eta, so the iterates converge to 3 exactly when 0<η<10 < \eta < 1. At η=1\eta = 1 they jump between 0 and 6 forever, and at η=1.1\eta = 1.1 they move farther away at every step. In general, if the gradient is β\beta-Lipschitz, which means ∥∇J(u)−∇J(v)∥2≤β∥u−v∥2\lVert \nabla J(\mathbf{u}) - \nabla J(\mathbf{v}) \rVert_2 \le \beta\lVert \mathbf{u} - \mathbf{v} \rVert_2 for all u\mathbf{u} and v\mathbf{v}, a constant step η≤1/β\eta \le 1/\beta never increases JJ, and for a convex JJ that attains its minimum the values J(θt)J(\boldsymbol{\theta}_t) converge to that minimum.

A function JJ is convex when, for all u\mathbf{u} and v\mathbf{v} and every c∈[0,1]c \in [0, 1],

J(cu+(1−c)v)≤cJ(u)+(1−c)J(v).\begin{aligned} &J(c\mathbf{u} + (1 - c)\mathbf{v}) \\[0.4em] &\quad \le cJ(\mathbf{u}) + (1 - c)J(\mathbf{v}). \end{aligned}

Every local minimum of a convex function is a global minimum, though it need not be unique. The Hessian is the matrix of second partial derivatives. A twice differentiable function on Rp\mathbb{R}^p is convex exactly when its Hessian is positive semidefinite everywhere, and at a stationary point a positive definite Hessian gives a strict local minimum, while a Hessian with both positive and negative eigenvalues gives a saddle point. Squared error and logistic loss are convex in the weights of a linear model, and the training loss of a neural network is generally not convex. A global minimum of the training loss still says nothing about performance on new data.

Lessons Gradient Descent and Optimization

Probability and Statistical Reasoning

Predictions are made under uncertainty. Conditional probability keeps track of the reference group, Bayes’ rule combines a base rate with new evidence, and distributions, expectations and variances describe what a random quantity tends to do. Estimates computed from a sample vary from sample to sample, and standard errors and confidence intervals describe that variation under stated assumptions.

Conditional probability and Bayes’ rule

An event is a set of outcomes, and P(A∩B)P(A \cap B) is the joint probability that AA and BB both occur. For P(B)>0P(B) > 0, the conditional probability and Bayes’ rule are

P(A∣B)=P(A∩B)P(B),P(A∣B)=P(B∣A) P(A)P(B),\begin{gathered} P(A \mid B) = \frac{P(A \cap B)}{P(B)}, \\[0.4em] P(A \mid B) = \frac{P(B \mid A)\,P(A)}{P(B)}, \end{gathered}

with P(B)=P(B∣A)P(A)+P(B∣Ac)P(Ac)P(B) = P(B \mid A)P(A) + P(B \mid A^c)P(A^c). Here P(A)P(A) is the prior probability or base rate, P(B∣A)P(B \mid A) is the likelihood of the evidence and P(A∣B)P(A \mid B) is the posterior probability. Events are independent when P(A∩B)=P(A)P(B)P(A \cap B) = P(A)P(B), and conditionally independent given CC, with P(C)>0P(C) > 0, when P(A∩B∣C)=P(A∣C)P(B∣C)P(A \cap B \mid C) = P(A \mid C)P(B \mid C). Neither kind of independence implies the other.

For example, suppose 2 percent of items are defective, and an inspection flags 90 percent of defective items and 5 percent of good ones. A flagged item is defective with probability

P(D∣+)=0.0180.018+0.049≈0.269,\begin{aligned} P(D \mid +) &= \frac{0.018}{0.018 + 0.049} \\[0.4em] &\approx 0.269, \end{aligned}

where 0.018=0.9⋅0.020.018 = 0.9 \cdot 0.02 and 0.049=0.05⋅0.980.049 = 0.05 \cdot 0.98. The probability P(+∣D)=0.9P(+ \mid D) = 0.9 answers a different question, and confusing the two ignores the base rate.

Lessons Conditional Probability and Bayes’ Rule

Random variables and probability distributions

A random variable assigns a number to each outcome. Its cumulative distribution function F(x)=P(X≤x)F(x) = P(X \le x) is nondecreasing, with limits 0 and 1. A discrete variable has a probability mass function p(x)=P(X=x)p(x) = P(X = x) whose values add to 1, written with summation notation as ∑xp(x)=1\sum_x p(x) = 1. A continuous variable has a probability density function f(x)≥0f(x) \ge 0 with

P(a≤X≤b)=∫abf(x) dx,∫−∞∞f(x) dx=1.\begin{gathered} P(a \le X \le b) = \int_a^b f(x)\,dx, \\[0.4em] \int_{-\infty}^{\infty} f(x)\,dx = 1 . \end{gathered}

The integral is the area under the density between aa and bb. Every single value has probability 0, and a density can exceed 1, as the uniform density on [0,0.5][0, 0.5], which equals 2 there.

DistributionProbabilitiesMeanVarianceConditions
BernoulliP(X=1)=qP(X = 1) = q, P(X=0)=1−qP(X = 0) = 1 - qqqq(1−q)q(1 - q)0≤q≤10 \le q \le 1
BinomialP(X=k)=(mk)qk(1−q)m−kP(X = k) = \binom{m}{k}q^k(1 - q)^{m - k} for k=0,…,mk = 0, \dots, mmqmqmq(1−q)mq(1 - q)successes in mm independent Bernoulli trials with the same qq
Normal N(μ,σ2)N(\mu, \sigma^2)density 1σ2πe−(x−μ)2/(2σ2)\dfrac{1}{\sigma\sqrt{2\pi}}e^{-(x - \mu)^2/(2\sigma^2)}μ\muσ2\sigma^2σ>0\sigma > 0

With m=10m = 10 independent trials and q=0.1q = 0.1, the probability of no success is 0.910≈0.3490.9^{10} \approx 0.349. About 95 percent of a normal distribution lies within 1.961.96 standard deviations of its mean.

Lessons Random Variables and Probability Distributions

Expectation, variance and covariance

The expected value is E[X]=∑xx p(x)E[X] = \sum_x x\,p(x) for a discrete variable and E[X]=∫xf(x) dxE[X] = \int x f(x)\,dx for a continuous one, when the sum or integral converges absolutely. Expectation is linear, E[aX+bY+c]=aE[X]+bE[Y]+cE[aX + bY + c] = aE[X] + bE[Y] + c, whether or not XX and YY are independent. With μX=E[X]\mu_X = E[X] and μY=E[Y]\mu_Y = E[Y], and finite second moments, the variance σX2=Var⁡(X)\sigma_X^2 = \operatorname{Var}(X) and the covariance σXY=Cov⁡(X,Y)\sigma_{XY} = \operatorname{Cov}(X, Y) are

σX2=E[(X−μX)2],σXY=E[XY]−μXμY.\begin{gathered} \sigma_X^2 = E[(X - \mu_X)^2], \\[0.4em] \sigma_{XY} = E[XY] - \mu_X\mu_Y . \end{gathered}

Variance is in squared units and Var⁡(aX+c)=a2Var⁡(X)\operatorname{Var}(aX + c) = a^2\operatorname{Var}(X). Covariance depends on the units, while the correlation Cov⁡(X,Y)/Var⁡(X)Var⁡(Y)\operatorname{Cov}(X, Y)/\sqrt{\operatorname{Var}(X)\operatorname{Var}(Y)}, defined when both variances are positive, has no units and lies in [−1,1][-1, 1]. Zero covariance does not imply independence. If XX is −1-1, 0 or 1 with equal probabilities and Y=X2Y = X^2, then Cov⁡(X,Y)=E[X3]−E[X]E[X2]=0\operatorname{Cov}(X, Y) = E[X^3] - E[X]E[X^2] = 0, although YY is a function of XX.

The covariance matrix of a random vector x\mathbf{x} with mean μ\boldsymbol{\mu} is Σ=E[(x−μ)(x−μ)⊤]\Sigma = E[(\mathbf{x} - \boldsymbol{\mu})(\mathbf{x} - \boldsymbol{\mu})^{\top}]. It is symmetric and positive semidefinite, with the variances on its diagonal. The conditional expectation E[Y∣X=x]E[Y \mid X = x] is the mean of YY among cases with X=xX = x, and the law of total expectation says E[E[Y∣X]]=E[Y]E\big[E[Y \mid X]\big] = E[Y]. When E[Y2]E[Y^2] is finite, the function of xx with the smallest expected squared error for predicting YY is E[Y∣X=x]E[Y \mid X = x]. Expectations belong to a distribution, while averages over a sample estimate them.

Lessons Expectation, Variance, and Covariance

Sampling, estimation and uncertainty

An estimator is a rule that turns a sample into an estimate of a parameter, and its sampling distribution describes how the estimate varies over repeated samples. Observations are independent and identically distributed, or iid, when they are independent draws from one distribution, and independence and identical distribution are separate conditions. For iid observations with mean μ\mu and finite variance σ2\sigma^2, the sample mean satisfies

E[Xˉ]=μ,SE⁡(Xˉ)=σn,\begin{gathered} E[\bar{X}] = \mu, \\[0.4em] \operatorname{SE}(\bar{X}) = \frac{\sigma}{\sqrt{n}}, \end{gathered}

and the standard error is estimated by s/ns/\sqrt{n}, where s2=1n−1∑i(xi−xˉ)2s^2 = \frac{1}{n - 1}\sum_{i}(x_i - \bar{x})^2. The law of large numbers says that Xˉ\bar{X} converges to μ\mu as nn grows, for iid observations with a finite mean, and it gives no guarantee for a particular finite nn.

An approximate 95 percent confidence interval for μ\mu is xˉ±1.96 s/n\bar{x} \pm 1.96\,s/\sqrt{n}, justified for large nn by the central limit theorem. It is only approximate in general, and for independent normal observations the interval with the Student tt quantile for n−1n - 1 degrees of freedom in place of 1.961.96 is exact. With s=12s = 12 and n=36n = 36 the estimated standard error is 2 and the interval is xˉ±3.92\bar{x} \pm 3.92. Coverage describes the procedure, so about 95 percent of the intervals from repeated samples contain μ\mu, while one computed interval either contains μ\mu or does not. Selection bias arises when the sampled units differ systematically from the target population, and a larger sample from the same process does not remove it.

Lessons Sampling, Estimation, and Statistical Uncertainty

Regression, Loss, and Regularization

Regression predicts a number. A loss measures one error, the empirical risk averages it over the training data, and the population risk is the quantity that matters for new cases. Least squares fits linear models, features and penalties change what they can express, and regression metrics compare models on the same held-out cases against simple baselines.

Loss functions and empirical risk

A loss function L(y,y^)L(y, \hat{y}) scores a single prediction. The common regression losses are the squared error (y−y^)2(y - \hat{y})^2 and the absolute error ∣y−y^∣\lvert y - \hat{y} \rvert. Training minimizes a training objective, the empirical risk plus any penalty, possibly with sample weights, while the evaluation metric reported on held-out data can be a different quantity.

The choice of loss decides what is being predicted. Among constant predictions cc, the expected squared error E[(Y−c)2]E[(Y - c)^2] is smallest at c=E[Y]c = E[Y] when E[Y2]E[Y^2] is finite, and the expected absolute error E∣Y−c∣E\lvert Y - c \rvert is smallest at any median of YY when E∣Y∣E\lvert Y \rvert is finite. Given the features, squared loss therefore targets the conditional mean E[Y∣x]E[Y \mid \mathbf{x}] and absolute loss a conditional median. For residuals 1, −1-1 and 4, the mean squared error is 6 and the mean absolute error is 2, and under squared error the residual 4 contributes 16 of the total 18. Neither loss is better in general, since they answer different questions.

Lessons Loss Functions and Empirical Risk

Simple linear regression

For pairs (xi,yi)(x_i, y_i) with at least two distinct xx values, least squares minimizes ∑i(yi−b−wxi)2\sum_i (y_i - b - wx_i)^2 and gives

w=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,b=yˉ−wxˉ.\begin{gathered} w = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sum_i (x_i - \bar{x})^2}, \\[0.4em] b = \bar{y} - w\bar{x}. \end{gathered}

The fitted value is y^i=b+wxi\hat{y}_i = b + wx_i, and the residual is ri=y^i−yir_i = \hat{y}_i - y_i, prediction minus target in the course convention, while some texts use the opposite sign. The residuals satisfy ∑iri=0\sum_i r_i = 0 and ∑ixiri=0\sum_i x_ir_i = 0, and the line passes through (xˉ,yˉ)(\bar{x}, \bar{y}). The slope is the difference in fitted value per unit of xx, in target units per feature unit. Computing the fit needs no assumption of normal errors, which matter only for classical intervals and tests.

The points (0,1)(0, 1), (1,2)(1, 2) and (2,2)(2, 2) give xˉ=1\bar{x} = 1, yˉ=5/3\bar{y} = 5/3, w=1/2w = 1/2 and b=7/6b = 7/6, with residuals 1/61/6, −1/3-1/3 and 1/61/6. Extrapolation beyond the observed range of xx assumes that the line continues there, which the data cannot check, and the slope describes an association in the data, not the effect of changing xx.

Lessons Simple Linear Regression

Multiple linear regression and least squares

With the augmented design matrix X~=[1  X]\tilde{X} = [\mathbf{1} \; X] of size n×(p+1)n \times (p + 1) and θ=(b,w)\boldsymbol{\theta} = (b, \mathbf{w}), least squares minimizes ∥y−X~θ∥22\lVert \mathbf{y} - \tilde{X}\boldsymbol{\theta} \rVert_2^2, and every minimizer solves the normal equations

X~⊤X~ θ=X~⊤y.\tilde{X}^{\top}\tilde{X}\,\boldsymbol{\theta} = \tilde{X}^{\top}\mathbf{y}.

When X~\tilde{X} has full column rank, which needs n≥p+1n \ge p + 1, the matrix X~⊤X~\tilde{X}^{\top}\tilde{X} is invertible and the solution θ^=(X~⊤X~)−1X~⊤y\hat{\boldsymbol{\theta}} = (\tilde{X}^{\top}\tilde{X})^{-1}\tilde{X}^{\top}\mathbf{y} is unique. Without full column rank infinitely many coefficient vectors fit equally well, yet they all give the same fitted vector y^=X~θ^\hat{\mathbf{y}} = \tilde{X}\hat{\boldsymbol{\theta}}, the orthogonal projection of y\mathbf{y} onto the column space of X~\tilde{X}. The residual vector y^−y\hat{\mathbf{y}} - \mathbf{y} is orthogonal to every column of X~\tilde{X}.

A coefficient wjw_j is a partial effect, the difference in prediction for a one-unit difference in xjx_j with the other features held fixed. It is an association within this model and can change, even in sign, when features are added or removed. For computation, a QR decomposition X~=QR\tilde{X} = QR, with orthonormal columns in QQ and an upper triangular RR, turns the problem into Rθ=Q⊤yR\boldsymbol{\theta} = Q^{\top}\mathbf{y}, solved by back substitution when X~\tilde{X} has full column rank. The SVD also handles the rank-deficient case. Forming (X~⊤X~)−1(\tilde{X}^{\top}\tilde{X})^{-1} explicitly squares the condition number and loses accuracy.

Lessons Multiple Linear Regression and Least Squares

Stochastic gradient descent and mini-batches

Full-batch gradient descent uses the gradient of the empirical risk over all nn examples at every step. Stochastic gradient descent replaces it with the average gradient over a mini-batch BB of examples,

θ←θ−η∣B∣∑i∈B∇Li(θ),\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \frac{\eta}{\lvert B \rvert}\sum_{i \in B}\nabla L_i(\boldsymbol{\theta}),

where LiL_i is the loss on example ii. When the batch is drawn uniformly at random, this stochastic gradient is an unbiased estimate of the full gradient. An epoch is one pass through the training data, about n/∣B∣n/\lvert B \rvert updates. A learning-rate schedule lowers η\eta over time. With a fixed η\eta the iterates keep fluctuating near a minimum, and the classical convergence results for convex objectives use steps with ∑tηt=∞\sum_t \eta_t = \infty and ∑tηt2<∞\sum_t \eta_t^2 < \infty.

Standardize the features with training statistics first, since very different feature scales make one fixed step too large in some directions and too small in others, and handle any feature with zero training variance by a stated convention. A fixed random seed makes a run repeatable on one setup. The run-to-run variation of the optimizer belongs to the training procedure and is a different thing from statistical uncertainty about the predictions.

Lessons Stochastic Gradient Descent and Mini-Batches

Polynomial features, interactions and splines

Feature engineering builds new columns from the raw inputs. A model is linear in parameters when its prediction is a weighted sum of fixed basis functions ϕk\phi_k,

y^=b+∑k=1Kwk ϕk(x),\hat{y} = b + \sum_{k=1}^{K} w_k\,\phi_k(\mathbf{x}),

so least squares and the penalized methods still apply, even when y^\hat{y} is a curved function of x\mathbf{x}. Polynomial features x,x2,…,xdx, x^2, \dots, x^d give curves, an interaction term x1x2x_1x_2 lets the effect of one feature depend on another, and indicator variables code categories, with K−1K - 1 indicators for KK levels next to an intercept. A spline is a piecewise polynomial joined smoothly at chosen knots, built from local basis functions such as max⁡(0,x−κ)\max(0, x - \kappa) for a knot κ\kappa.

In y^=10+2x1+3x2−x1x2\hat{y} = 10 + 2x_1 + 3x_2 - x_1x_2, a one-unit step in x1x_1 changes y^\hat{y} by 2−x22 - x_2, so the effect of x1x_1 is positive for x2<2x_2 < 2 and negative for x2>2x_2 > 2. High-degree polynomials swing wildly outside the training range, so scale the input, choose the degree on validation data and do not extrapolate. Every learned expansion, such as the category list or the knot positions, is fitted on the training data.

Lessons Polynomial Features and Interactions

Ridge, lasso and elastic net

With features standardized on the training data, residuals ri=b+w⊤xi−yir_i = b + \mathbf{w}^{\top}\mathbf{x}_i - y_i and an unpenalized intercept bb, the course writes the penalized least-squares objectives as

J0=12n∑i=1nri2,Jridge=J0+λ2∥w∥22,Jlasso=J0+λ∥w∥1,Jnet=J0+λα∥w∥1+λ(1−α)2∥w∥22,\begin{aligned} J_0 &= \frac{1}{2n}\sum_{i=1}^{n} r_i^2, \\[0.4em] J_{\text{ridge}} &= J_0 + \tfrac{\lambda}{2}\lVert \mathbf{w} \rVert_2^2, \\[0.4em] J_{\text{lasso}} &= J_0 + \lambda\lVert \mathbf{w} \rVert_1, \\[0.4em] J_{\text{net}} &= J_0 + \lambda\alpha\lVert \mathbf{w} \rVert_1 \\ &\quad + \tfrac{\lambda(1 - \alpha)}{2}\lVert \mathbf{w} \rVert_2^2, \end{aligned}

with regularization strength λ≥0\lambda \ge 0 and mixing weight α∈[0,1]\alpha \in [0, 1]. At λ=0\lambda = 0 all three are least squares. Ridge shrinks the coefficients smoothly toward zero and has a unique solution for every λ>0\lambda > 0. With the centered and standardized matrix ZZ and the centered target yc\mathbf{y}_c, it is

w^=(Z⊤Z+nλI)−1Z⊤yc,\hat{\mathbf{w}} = (Z^{\top}Z + n\lambda I)^{-1}Z^{\top}\mathbf{y}_c,

and bb is the training mean of the target. Lasso can set coefficients exactly to zero and so also selects features. Its penalty is not differentiable at zero, so it is solved by coordinate descent with soft thresholding, or another method that handles the corner, rather than by plain gradient descent.

For a single standardized feature whose average square is 1, let cc be its average product with the centered target. The three solutions are

wridge=c1+λ,wlasso=Sλ(c),wnet=Sλα(c)1+λ(1−α),\begin{gathered} w_{\text{ridge}} = \frac{c}{1 + \lambda}, \\[0.4em] w_{\text{lasso}} = S_{\lambda}(c), \\[0.4em] w_{\text{net}} = \frac{S_{\lambda\alpha}(c)}{1 + \lambda(1 - \alpha)}, \end{gathered}

where the soft-thresholding function is St(c)=sign⁡(c)max⁡(∣c∣−t,0)S_t(c) = \operatorname{sign}(c)\max(\lvert c \rvert - t, 0). For c=0.7c = 0.7 and λ=0.5\lambda = 0.5 they are about 0.4670.467, 0.20.2 and, with α=0.5\alpha = 0.5, 0.360.36. The regularization path plots the fitted coefficients against λ\lambda. Choose λ\lambda and α\alpha on validation data or by cross-validation, never on the test set. With strongly correlated features lasso may keep one and drop another almost arbitrarily, so a zero coefficient is not evidence that a feature is unrelated to the target. Software packages scale these objectives differently, so the same printed λ\lambda can mean different fits.

Lessons Ridge, Lasso, and Elastic Net

Regression metrics and baselines

For mm evaluated predictions with errors ei=y^i−yie_i = \hat{y}_i - y_i, prediction minus target,

MAE⁡=1m∑i=1m∣ei∣,MSE⁡=1m∑i=1mei2,RMSE⁡=MSE⁡,R2=1−∑iei2∑i(yi−yˉ)2,\begin{gathered} \operatorname{MAE} = \frac{1}{m}\sum_{i=1}^{m}\lvert e_i \rvert, \\[0.4em] \operatorname{MSE} = \frac{1}{m}\sum_{i=1}^{m} e_i^2, \\[0.4em] \operatorname{RMSE} = \sqrt{\operatorname{MSE}}, \\[0.4em] R^2 = 1 - \frac{\sum_i e_i^2}{\sum_i (y_i - \bar{y})^2}, \end{gathered}

where yˉ\bar{y} is the mean of the evaluation targets. The MAE and RMSE are in target units and the MSE in squared units. The value R2R^2 is undefined when all evaluation targets are equal. Otherwise it is 1 for perfect predictions, 0 when every prediction equals yˉ\bar{y}, and negative for predictions worse than that, which can happen on held-out data. The mean absolute percentage error, MAPE⁡=100m∑i∣ei∣/∣yi∣\operatorname{MAPE} = \frac{100}{m}\sum_i \lvert e_i \rvert/\lvert y_i \rvert in percent, needs every yi≠0y_i \ne 0 and becomes huge near zero targets.

Targets 2, 4, 6 and 8 with predictions 3, 4, 5 and 12 have errors 1, 0, −1-1 and 4, so the MAE is 1.51.5, the MSE is 4.54.5, the RMSE is about 2.1212.121, R2=1−18/20=0.1R^2 = 1 - 18/20 = 0.1 and the MAPE is about 29.229.2 percent. Compare models on the same held-out cases. The mean baseline predicts the training mean of the target, the best constant for squared error on the training data, and the median baseline predicts the training median, the best constant for absolute error. Any constant prediction has R2≤0R^2 \le 0 on the evaluation data, with equality only when the constant equals yˉ\bar{y}, so a mean baseline fitted on training data usually has a negative R2R^2 on test data.

Lessons Regression Metrics and Baseline Comparisons

Huber loss and quantile prediction

Robust regression limits the pull of large errors. With u=y−y^u = y - \hat{y}, the target minus the prediction,

LossFormulaBest constant prediction
Squaredu2u^2the mean
Absolute∣u∣\lvert u \rverta median
Huber with δ>0\delta > 012u2\tfrac{1}{2}u^2 for ∣u∣≤δ\lvert u \rvert \le \delta, δ(∣u∣−12δ)\delta(\lvert u \rvert - \tfrac{1}{2}\delta) otherwisethe mean when δ\delta is large enough, tending to a median as δ→0\delta \to 0
Pinball at level τ∈(0,1)\tau \in (0, 1)τu\tau u for u≥0u \ge 0, (τ−1)u(\tau - 1)u for u<0u < 0a τ\tau quantile

Huber loss is quadratic near zero and linear in the tails, with its slope capped at ±δ\pm\delta, so one large error pulls with bounded force. The threshold δ\delta is in target units. In a regression the gradient also multiplies by the features, so an example with an extreme feature value can still move the fit a lot, and Huber loss offers no protection against high-leverage points. With δ=2\delta = 2, an error of size 1 costs 0.50.5 and an error of size 6 costs 10.

The pinball loss penalizes underprediction with slope τ\tau and overprediction with slope 1−τ1 - \tau, so at τ=0.9\tau = 0.9 underpredicting by 10 costs 9 and overpredicting by 10 costs 1. When E∣Y∣E\lvert Y \rvert is finite its expected value is minimized by a τ\tau quantile of YY, so quantile regression, which fits qτ(x)=b+w⊤xq_{\tau}(\mathbf{x}) = b + \mathbf{w}^{\top}\mathbf{x} by minimizing the average pinball loss, estimates a conditional quantile. It expresses an asymmetric cost, and two fitted quantiles are not automatically a calibrated prediction interval.

Lessons Robust Regression and Quantile Prediction

Classification, Probabilities, and Decisions

Classification predicts a category, often through a probability. Logistic regression and softmax turn scores into probabilities fitted by maximum likelihood, a threshold turns a probability into a decision, and the confusion matrix and its rates count the consequences. Ranking quality, threshold performance and calibration are separate properties, and each needs its own check.

Logistic regression

Binary classification predicts a label y∈{0,1}y \in \{0, 1\}. Logistic regression models p(x)=P(Y=1∣x)p(\mathbf{x}) = P(Y = 1 \mid \mathbf{x}) as

p(x)=σ(w⊤x+b),σ(z)=11+e−z.\begin{gathered} p(\mathbf{x}) = \sigma(\mathbf{w}^{\top}\mathbf{x} + b), \\[0.4em] \sigma(z) = \frac{1}{1 + e^{-z}} . \end{gathered}

The sigmoid maps every real score into (0,1)(0, 1), and its inverse is the log-odds,

log⁡p1−p=w⊤x+b,\log\frac{p}{1 - p} = \mathbf{w}^{\top}\mathbf{x} + b,

where p/(1−p)p/(1 - p) is the odds. A one-unit increase in xjx_j with the other features fixed adds wjw_j to the log-odds and multiplies the odds by the odds ratio ewje^{w_j}, while the change in probability is not constant and is largest near p=0.5p = 0.5. The decision boundary w⊤x+b=0\mathbf{w}^{\top}\mathbf{x} + b = 0 is the hyperplane where p=0.5p = 0.5, and other thresholds give parallel hyperplanes. With b=−3b = -3 and w=0.5w = 0.5 per kilometer, p=σ(0)=0.5p = \sigma(0) = 0.5 at 6 kilometers and p=σ(2)≈0.881p = \sigma(2) \approx 0.881 at 10 kilometers, and each kilometer multiplies the odds by e0.5≈1.65e^{0.5} \approx 1.65. The coefficients describe associations in units of the features, and the probabilities are not calibrated just because they lie between 0 and 1.

Lessons Logistic Regression

Likelihood and cross-entropy

If the labels are conditionally independent given their features, and pip_i is the model probability that yi=1y_i = 1, the Bernoulli likelihood of the parameters is

L(θ)=∏i=1npi yi(1−pi)1−yi.\mathcal{L}(\boldsymbol{\theta}) = \prod_{i=1}^{n} p_i^{\,y_i}(1 - p_i)^{1 - y_i} .

It is a function of θ\boldsymbol{\theta} for the observed data, not a probability distribution over θ\boldsymbol{\theta}. Maximum likelihood estimation maximizes it, which is the same as minimizing the negative log likelihood, and dividing that by nn gives the binary cross-entropy J(θ)=1n∑i=1nℓiJ(\boldsymbol{\theta}) = \frac{1}{n}\sum_{i=1}^{n}\ell_i, the average of the per-example losses

ℓi=−yilog⁡pi−(1−yi)log⁡(1−pi).\begin{aligned} \ell_i = {}&-y_i\log p_i \\ &- (1 - y_i)\log(1 - p_i) . \end{aligned}

For logistic regression the gradient is ∇wJ=1nX⊤(p−y)\nabla_{\mathbf{w}}J = \frac{1}{n}X^{\top}(\mathbf{p} - \mathbf{y}), and ∂J/∂b\partial J/\partial b is the mean of pi−yip_i - y_i. The objective is convex in (w,b)(\mathbf{w}, b), and it has no finite minimizer when a hyperplane separates the two classes perfectly. Compute log⁡(1+ez)\log(1 + e^{z}) in a numerically stable form instead of exponentiating large scores. For labels 1, 0 and 1 with probabilities 0.80.8, 0.20.2 and 0.80.8, the likelihood is 0.83=0.5120.8^3 = 0.512 and the cross-entropy is −log⁡0.8≈0.223-\log 0.8 \approx 0.223, while a positive case given probability 0.020.02 alone costs −log⁡0.02≈3.91-\log 0.02 \approx 3.91.

Maximum a posteriori estimation maximizes likelihood times a prior distribution on the parameters. With the mean cross-entropy and the penalty λ2∥w∥22\tfrac{\lambda}{2}\lVert \mathbf{w} \rVert_2^2, independent N(0,s2)N(0, s^2) priors on the weights correspond to λ=1/(ns2)\lambda = 1/(ns^2), and independent Laplace priors with scale aa give the penalty λ∥w∥1\lambda\lVert \mathbf{w} \rVert_1 with λ=1/(na)\lambda = 1/(na). For n=4n = 4 and s2=2s^2 = 2 this gives λ=1/8\lambda = 1/8. A MAP estimate is the posterior mode, a single point that describes no uncertainty, and the prior is an assumption.

Lessons Maximum Likelihood and Cross-Entropy

Multiclass classification and softmax

Multiclass classification gives each example exactly one of KK classes, while multilabel classification allows several labels at once and usually uses one sigmoid per label. For scores z1,…,zKz_1, \dots, z_K the softmax function gives the class probability vector

softmax⁡(z)k=ezk∑j=1Kezj,\operatorname{softmax}(\mathbf{z})_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}},

whose entries are positive and add to 1. Adding the same constant to every score leaves it unchanged, so implementations subtract M=max⁡jzjM = \max_j z_j first, and the log-sum-exp trick computes log⁡∑jezj=M+log⁡∑jezj−M\log\sum_j e^{z_j} = M + \log\sum_j e^{z_j - M}. For the true class yy the multiclass cross-entropy is

−log⁡softmax⁡(z)y=log⁡∑j=1Kezj−zy.\begin{aligned} &-\log\operatorname{softmax}(\mathbf{z})_y \\[0.4em] &\quad = \log\sum_{j=1}^{K} e^{z_j} - z_y . \end{aligned}

Scores 2, 1 and 0 give probabilities of about 0.6650.665, 0.2450.245 and 0.0900.090, and a loss of about 0.4080.408 when the first class is correct. One-vs-rest fits KK binary classifiers, each separating one class from all others, and predicts the class with the largest score. Their probabilities need not add to 1, unlike multinomial logistic regression, which applies the softmax to KK linear scores.

Lessons Multiclass Classification and Softmax

Confusion matrices and decision thresholds

The positive class is the outcome the decision is about, and it is named before anything is counted. A decision threshold tt turns a score into a decision, positive when the score is at least tt.

Predicted positivePredicted negative
Actually positivetrue positive, TPfalse negative, FN
Actually negativefalse positive, FPtrue negative, TN
sensitivity=TPTP+FN,specificity=TNTN+FP.\begin{gathered} \text{sensitivity} = \frac{\text{TP}}{\text{TP} + \text{FN}}, \\[0.4em] \text{specificity} = \frac{\text{TN}}{\text{TN} + \text{FP}} . \end{gathered}

Sensitivity is the true positive rate, also called recall, and the false positive rate is 1−specificity=FP/(FP+TN)1 - \text{specificity} = \text{FP}/(\text{FP} + \text{TN}). Each ratio is undefined when its denominator is 0. Raising tt moves cases from predicted positive to predicted negative, so sensitivity can only fall or stay the same while specificity can only rise or stay the same.

Suppose a false positive costs cFPc_{\text{FP}}, a false negative costs cFNc_{\text{FN}} and correct decisions cost nothing. If p=P(Y=1∣x)p = P(Y = 1 \mid \mathbf{x}) is a calibrated probability, predicting positive has expected cost (1−p)cFP(1 - p)c_{\text{FP}} and predicting negative has p cFNp\,c_{\text{FN}}, so the expected cost is smallest when the rule predicts positive for

p≥cFPcFP+cFN.p \ge \frac{c_{\text{FP}}}{c_{\text{FP}} + c_{\text{FN}}} .

With cFN=5c_{\text{FN}} = 5 and cFP=1c_{\text{FP}} = 1 the threshold is 1/61/6, not 0.50.5. On a set of cases the total cost of a threshold is cFP FP+cFN FNc_{\text{FP}}\,\text{FP} + c_{\text{FN}}\,\text{FN}, and a threshold chosen for accuracy alone ignores these costs.

Lessons Confusion Matrices and Decision Thresholds

Precision, recall, ROC and precision-recall curves

The main threshold metrics are

precision=TPTP+FP,recall=TPTP+FN,F1=2 TP2 TP+FP+FN,\begin{gathered} \text{precision} = \frac{\text{TP}}{\text{TP} + \text{FP}}, \\[0.4em] \text{recall} = \frac{\text{TP}}{\text{TP} + \text{FN}}, \\[0.4em] F_1 = \frac{2\,\text{TP}}{2\,\text{TP} + \text{FP} + \text{FN}}, \end{gathered}

and accuracy, the share of all cases classified correctly. Precision is undefined when nothing is predicted positive, and F1F_1 is undefined only when TP+FP+FN=0\text{TP} + \text{FP} + \text{FN} = 0. When precision PP and recall RR are both positive, F1=2PR/(P+R)F_1 = 2PR/(P + R) is their harmonic mean. It ignores true negatives and the costs of errors, and replacing an undefined value by 0 is a reporting choice that should be stated.

The ROC curve plots the true positive rate against the false positive rate as the threshold moves from above the highest score to below the lowest, with tied scores entering together. ROC AUC, the area under this curve with straight segments, equals the probability that a randomly chosen positive scores above a randomly chosen negative, with ties counted one half. For n+n_+ positives with scores sis_i and n−n_- negatives with scores sjs_j,

AUC=1n+n−∑i∑jcij,\text{AUC} = \frac{1}{n_+n_-}\sum_{i}\sum_{j} c_{ij},

where cijc_{ij} is 1, 1/21/2 or 0 as positive ii scores above, equal to or below negative jj. A constant score has AUC 0.50.5, both classes must be present, and any strictly increasing change of the scores leaves AUC unchanged, so it measures ranking and says nothing about calibration or about a particular threshold. Positive scores 0.80.8 and 0.50.5 against negative scores 0.50.5 and 0.20.2 earn 1+1+0.5+1=3.51 + 1 + 0.5 + 1 = 3.5 of 4 pairs, so AUC =0.875= 0.875.

The precision-recall curve plots precision against recall over the thresholds. Average precision, in the noninterpolated form used in the course, is

AP=∑k(Rk−Rk−1) Pk,\text{AP} = \sum_{k}(R_k - R_{k-1})\,P_k,

over the distinct thresholds in decreasing order, with recall RkR_k, precision PkP_k and R0=0R_0 = 0. A ranking that ignores the features has precision near the prevalence at every threshold, so AP is read against that level. With two positives among ten cases ranked first and fifth, AP=0.5⋅1+0.5⋅0.4=0.7\text{AP} = 0.5 \cdot 1 + 0.5 \cdot 0.4 = 0.7, while ROC AUC is 13/16≈0.8113/16 \approx 0.81. The two summaries reward different parts of the ranking.

Lessons Precision, Recall, and Classification Metrics

Imbalanced classes and cost-sensitive learning

Class imbalance means one class is much rarer than the other, and the prevalence π\pi is the share of positives. Accuracy can look excellent for a useless rule, since always predicting negative is right for a share 1−π1 - \pi of the cases. Precision depends on prevalence. For a fixed true positive rate tt and false positive rate ff,

precision=tπtπ+f(1−π),\text{precision} = \frac{t\pi}{t\pi + f(1 - \pi)},

so at t=0.8t = 0.8, f=0.1f = 0.1 and π=0.01\pi = 0.01 precision is only about 0.0750.075. As another example, 12 true positives, 8 false negatives, 40 false positives and 940 true negatives give accuracy 0.9520.952, below the 0.980.98 of always predicting negative, while recall is 0.60.6, specificity about 0.9590.959 and precision about 0.2310.231.

Balanced accuracy is the mean of sensitivity and specificity, about 0.7800.780 in this example and 0.50.5 for the rule that always predicts negative. A macro average computes a metric for each class and averages the results with equal weights, while a micro average pools the counts of all classes first. In single-label multiclass problems micro precision, micro recall and micro F1F_1 all equal accuracy.

Class weights multiply each example’s loss by a weight that depends on its class, and cost-sensitive learning chooses the weights or the threshold from the costs of errors. Resampling repeats minority rows or drops majority rows, and SMOTE creates a synthetic minority point xi+u(xnn−xi)\mathbf{x}_i + u(\mathbf{x}_{\text{nn}} - \mathbf{x}_i) between a minority example and one of its minority neighbors, with uu uniform on [0,1][0, 1]. Synthetic points are not new evidence. Resample only inside training folds, evaluate on data with the real class mix, and remember that weighting or resampling changes the meaning of predicted probabilities. Moving the threshold is often enough, and it leaves the fitted probabilities unchanged.

Lessons Imbalanced Classes and Cost-Sensitive Learning

Probability calibration

A probability model is calibrated when, among cases given probability pp, the share of positives is pp, that is P(Y=1∣p^=p)=pP(Y = 1 \mid \hat{p} = p) = p for every pp. Calibration is separate from discrimination, the ability to rank positives above negatives, and an increasing change of the scores keeps the ranking and AUC while it can change calibration. A reliability diagram groups the predictions into bins and plots the mean predicted probability against the observed share of positives in each bin. Points near the diagonal suggest calibration in those bins, up to sampling noise that is large for small bins.

For mm cases the Brier score is 1m∑i(pi−yi)2\frac{1}{m}\sum_{i}(p_i - y_i)^2, and the log loss is the binary cross-entropy of the held-out predictions. Both are proper scoring rules that reward calibration and discrimination together, so a better score alone does not show better calibration. Ten cases all given 0.60.6, of which 4 are positive, sit at the point (0.6,0.4)(0.6, 0.4) of the diagram and have Brier score 0.280.28 and log loss about 0.7540.754.

Platt scaling fits p=σ(as+c)p = \sigma(as + c) to a score ss by maximum likelihood, and isotonic regression fits a nondecreasing step function by least squares. Fit the calibrator on a calibration set that was not used to train the model, or on out-of-fold predictions, and check the result on separate evaluation data. Moving the decision threshold changes the decisions, not the calibration.

Lessons Probability Calibration

Naive Bayes classification

A generative classifier models the class prior P(c)=P(Y=c)P(c) = P(Y = c) and the class-conditional distribution of the features, then classifies with Bayes’ rule. The naive Bayes assumption is that the features are conditionally independent given the class, P(x∣c)=∏jP(xj∣c)P(\mathbf{x} \mid c) = \prod_{j} P(x_j \mid c), so the classifier picks the class with the largest log-probability score

sc(x)=log⁡P(c)+∑j=1plog⁡P(xj∣c),\begin{aligned} s_c(\mathbf{x}) &= \log P(c) \\[0.4em] &\quad + \sum_{j=1}^{p}\log P(x_j \mid c), \end{aligned}

and working with logarithms avoids numerical underflow. Normalizing esce^{s_c} over the classes gives the model’s posterior probabilities. With binary features, as in Bernoulli naive Bayes, Laplace smoothing estimates

P(xj=1∣c)=r+1nc+2P(x_j = 1 \mid c) = \frac{r + 1}{n_c + 2}

when feature jj is present in rr of the ncn_c training examples of class cc, so a word never seen in a class does not get probability 0. For word counts, multinomial naive Bayes uses the smoothed estimate (Ncj+α)/(Nc+α∣V∣)(N_{cj} + \alpha)/(N_c + \alpha\lvert V \rvert), where NcjN_{cj} counts word jj in class cc, NcN_c is the total count in that class, ∣V∣\lvert V \rvert is the vocabulary size and α>0\alpha > 0. The independence assumption rarely holds exactly, so the ranking can be useful while the probabilities are overconfident.

Lessons Naive Bayes Classification

Gaussian discriminant analysis

Gaussian discriminant analysis models each class-conditional density as a multivariate Gaussian distribution with mean μc\boldsymbol{\mu}_c and a positive-definite covariance matrix Σc\Sigma_c,

Qc=(x−μc)⊤Σc−1(x−μc),fc(x)=e−Qc/2(2π)pdet⁡Σc.\begin{gathered} Q_c = (\mathbf{x} - \boldsymbol{\mu}_c)^{\top}\Sigma_c^{-1}(\mathbf{x} - \boldsymbol{\mu}_c), \\[0.4em] f_c(\mathbf{x}) = \frac{e^{-Q_c/2}}{\sqrt{(2\pi)^p\det\Sigma_c}} . \end{gathered}

Positive definiteness makes Σc\Sigma_c invertible and the density well defined. The classifier picks the class with the largest log⁡πc+log⁡fc(x)\log\pi_c + \log f_c(\mathbf{x}), where πc\pi_c is the class prior. Linear discriminant analysis (LDA) assumes one shared covariance matrix for all classes, which makes the boundaries between classes linear in x\mathbf{x}, and quadratic discriminant analysis (QDA) lets each class have its own, which gives quadratic boundaries. QDA estimates many more parameters, and a sample covariance matrix computed from pp or fewer observations is singular, so small samples need shrinkage or regularization. In this course LDA always means linear discriminant analysis, not latent Dirichlet allocation.

In one dimension with class means 0 and 2, common variance 1 and priors 0.750.75 and 0.250.25, the boundary is at 1+0.5log⁡3≈1.5491 + 0.5\log 3 \approx 1.549 rather than at the midpoint 1, because the more common class claims more of the line.

Lessons Gaussian Discriminant Analysis

Generalization and Reliable Model Selection

A useful model predicts well on cases it has not seen. Expected squared error splits into bias, variance and noise, cross-validation and nested evaluation keep tuning apart from the final estimate, and resampling measures how uncertain a reported score is. Guarantees about risk exist, but only under assumptions that must be checked for the data at hand.

Bias, variance and irreducible error

Fix an input x\mathbf{x} and write a new outcome as Y=f(x)+εY = f(\mathbf{x}) + \varepsilon, with E[ε]=0E[\varepsilon] = 0 and Var⁡(ε)=σ2(x)\operatorname{Var}(\varepsilon) = \sigma^2(\mathbf{x}). Let f^(x)\hat{f}(\mathbf{x}) be the prediction of a model trained on a random training set, independent of the new ε\varepsilon, and let m(x)=E[f^(x)]m(\mathbf{x}) = E[\hat{f}(\mathbf{x})]. With finite second moments, the expected squared prediction error at x\mathbf{x} is

err⁡(x)=E[(Y−f^(x))2],err⁡(x)=B2+V+σ2(x),B=m(x)−f(x),V=Var⁡(f^(x)),\begin{gathered} \operatorname{err}(\mathbf{x}) = E\big[(Y - \hat{f}(\mathbf{x}))^2\big], \\[0.4em] \operatorname{err}(\mathbf{x}) = B^2 + V + \sigma^2(\mathbf{x}), \\[0.4em] B = m(\mathbf{x}) - f(\mathbf{x}), \\[0.4em] V = \operatorname{Var}(\hat{f}(\mathbf{x})), \end{gathered}

where the expectations average over the training set, any training randomness such as initialization, and the new noise. The three terms are the squared bias, the prediction variance and the irreducible error. The decomposition holds for squared loss in this setup, and classification error has no such additive split. More flexible models tend to have lower bias and higher variance, which is the bias-variance tradeoff, but the terms are not directly observable on real data, where ff and σ2\sigma^2 are unknown.

For example, if f(x)=10f(\mathbf{x}) = 10, the noise is −2-2 or 2 with equal probability, and the fitted prediction is 7, 9, 9 or 11 with equal probability, then m=9m = 9, the squared bias is 1, the variance is 2 and the noise variance is 4. Averaging (Y−f^)2(Y - \hat{f})^2 over all eight equally likely combinations gives the same total, 7.

Lessons Bias, Variance, and Irreducible Error

Cross-validation and preprocessing pipelines

K-fold cross-validation splits the development data into kk folds, fits the whole procedure on k−1k - 1 folds and scores the held-out fold, kk times. The estimate is the average of the fold scores, or the score of all nn out-of-fold predictions pooled, and for an average such as the MSE the two agree when the folds have equal sizes.

FoldsRuleUse
Ordinaryrows assigned to folds at randomindependent, exchangeable rows
Stratifiedevery fold keeps the class proportionsclassification, especially with rare classes
Groupedall rows of a group in the same foldrepeated customers, patients or devices
Temporaltrain on earlier periods and score the next oneforecasting and any data ordered in time

A preprocessing pipeline chains every learned step, such as imputation, scaling, encoding, feature selection and the model, so that each fold refits all of them on its own training part. Fold leakage happens when a step learns from the held-out fold, for example scaling with the statistics of all the data. Folds do not make dependent rows independent, and the spread of the fold scores is not by itself a confidence interval.

Lessons Cross-Validation and Preprocessing Pipelines

Hyperparameter search and nested evaluation

Hyperparameter tuning chooses settings such as λ\lambda, kk or a tree depth by validation performance. Grid search tries every combination from fixed lists. Random search samples settings from stated ranges, and for the same search budget, the number of configurations fitted, it often tries more distinct values of the settings that matter most. The best validation score among many configurations is optimistic, because the winner was picked partly for luck, which is optimistic selection bias.

Nested cross-validation estimates the performance of the whole tuning procedure. Inner folds inside each outer training part choose the hyperparameters, and each outer fold then scores the chosen model on data the tuning never saw. A single untouched test set is the other honest option. Report the search space, the budget and the random seeds along with the result.

Lessons Hyperparameter Search and Nested Evaluation

Learning curves and error analysis

A learning curve plots training and validation error against the training set size.

PatternReadingWhat may help
Both errors high and close togetherunderfittinga more flexible model or better features, while more data of the same kind helps little
Training error far below validation error, gap shrinking with more datahigh variancemore data, regularization or a simpler model

These patterns are evidence to weigh, not certainties. Error analysis sorts validation errors into error slices, such as ranges of a feature or kinds of input, and subgroup evaluation computes the metric separately for each subgroup together with its size. Slices found while developing a model guide the next change, and a claim about a slice needs evaluation on protected data.

Lessons Learning Curves and Error Analysis

Bootstrap uncertainty and model comparisons

Bootstrap resampling draws nn cases with replacement from the nn evaluation cases and recomputes a statistic, many times. The spread of these values, the bootstrap distribution, approximates the sampling variability of the statistic, and the percentile interval takes its α/2\alpha/2 and 1−α/21 - \alpha/2 quantiles. Resample the independent sampling unit, such as the customer rather than the single order, and use blocks or another method for data ordered in time.

To compare two models, resample the same cases for both and recompute the difference of their scores each time. This paired comparison removes the variation the two models share. Bootstrapping the test predictions of a fixed model measures the metric uncertainty that comes from a finite test set, not the variation from refitting and retuning the model. A given case is missing from a bootstrap sample with probability (1−1/n)n(1 - 1/n)^n, about 0.3490.349 for n=10n = 10 and close to e−1≈0.368e^{-1} \approx 0.368 for large nn.

Lessons Bootstrap Uncertainty and Model Comparisons

Prediction intervals and split conformal prediction

A prediction interval targets a new outcome, while a confidence interval targets a fixed parameter. Aleatoric uncertainty is the variation of the outcome itself, and epistemic uncertainty comes from limited knowledge of the model and could shrink with more data.

Split conformal prediction fits a model f^\hat{f} on training data, freezes it, and computes the conformity scores Ri=∣yi−f^(xi)∣R_i = \lvert y_i - \hat{f}(\mathbf{x}_i) \rvert on mm calibration cases. For a miscoverage level α∈(0,1)\alpha \in (0, 1), let

k=⌈(m+1)(1−α)⌉,k = \lceil (m + 1)(1 - \alpha) \rceil,

take qq as the kkth smallest score when k≤mk \le m and q=∞q = \infty when k=m+1k = m + 1, and report the closed interval from f^(x)−q\hat{f}(\mathbf{x}) - q to f^(x)+q\hat{f}(\mathbf{x}) + q. If the calibration cases and the new case are exchangeable, then

P(Ynew∈C(xnew))≥1−α.P\big(Y_{\text{new}} \in C(\mathbf{x}_{\text{new}})\big) \ge 1 - \alpha .

This is marginal coverage, an average over calibration sets and new cases, and it does not promise coverage at every x\mathbf{x} or in every subgroup. Scores 1, 1, 1, 2, 2, 2, 3, 4 and 5 with α=0.2\alpha = 0.2 give k=8k = 8 and q=4q = 4, while α=0.05\alpha = 0.05 gives k=10k = 10 and an infinite interval. Drift over time breaks exchangeability and with it the guarantee.

Lessons Prediction Intervals and Split Conformal Prediction

Generalization bounds and capacity

For a fixed predictor hh, iid examples and a loss with values in [0,1][0, 1], Hoeffding’s inequality gives, for every ε>0\varepsilon > 0,

P(∣R^n(h)−R(h)∣≥ε)≤2e−2nε2.\begin{aligned} &P\big(\lvert \hat{R}_n(h) - R(h) \rvert \ge \varepsilon\big) \\[0.4em] &\quad \le 2e^{-2n\varepsilon^2} . \end{aligned}

For a finite hypothesis class H\mathcal{H} fixed before the data are seen, the union bound adds these probabilities over the members of H\mathcal{H}. Setting the total to δ\delta shows that, with probability at least 1−δ1 - \delta, every h∈Hh \in \mathcal{H} satisfies ∣R^n(h)−R(h)∣<ε\lvert \hat{R}_n(h) - R(h) \rvert < \varepsilon with

ε=log⁡(2∣H∣/δ)2n.\varepsilon = \sqrt{\frac{\log(2\lvert \mathcal{H} \rvert/\delta)}{2n}} .

Because the statement holds for all members at once, which is uniform convergence, it also covers the member chosen by minimizing the training error. With ∣H∣=20\lvert \mathcal{H} \rvert = 20, n=1000n = 1000 and δ=0.05\delta = 0.05 the bound is about 0.05780.0578, and with ∣H∣=2000\lvert \mathcal{H} \rvert = 2000 it is about 0.07510.0751. It grows with the capacity of the class, shrinks like 1/n1/\sqrt{n} and is often loose. It does not apply with a parameter count in place of ∣H∣\lvert \mathcal{H} \rvert, to an unbounded loss, to data that are not iid, or to a class enlarged after looking at the data.

Inductive bias is the set of assumptions that lets a learner prefer some functions over others that fit the data equally well, such as linearity or smoothness. The no free lunch theorem says that, averaged uniformly over all possible target functions, every learner has the same expected error on inputs outside the training set, so no learner is best for every problem.

Lessons Generalization, Model Capacity, and Learning Guarantees

Feature selection, collinearity and the complete workflow

Collinearity means that features are strongly linearly related. It makes individual coefficients unstable and hard to interpret, even while the predictions stay good, and exact collinearity makes them not unique. For least squares the variance inflation factor VIF⁡j=1/(1−Rj2)\operatorname{VIF}_j = 1/(1 - R_j^2), where Rj2R_j^2 comes from regressing xjx_j on the other features, is the factor by which collinearity multiplies the variance of coefficient jj, so Rj2=0.9R_j^2 = 0.9 gives a factor of 10. Feature redundancy means a feature adds little given the others. Feature selection, by filters, stepwise search or a lasso penalty, is part of training and runs inside every training fold. P-values and intervals computed on the same data after selecting features are too optimistic, which is the problem of post-selection inference, and a feature that predicts well need not cause the outcome.

A complete supervised learning workflow follows these steps.

  1. Define the task, the unit of observation, the prediction time and a data contract that fixes the meaning, type and units of every input column.
  2. Split off a test set that matches the intended use, and work only with the remaining development data.
  3. Build baselines and candidate pipelines, with every learned step inside the folds.
  4. Tune on validation data or by cross-validation, then refit the selected pipeline on all development data.
  5. Evaluate once on the test set, report the result with its uncertainty, the population, the metric and the limitations, and compare it with the baseline.
  6. Record the data versions, code, settings and seeds, so that the result can be reproduced.

Lessons Feature Selection and Collinearity, A Complete Supervised Learning Workflow

Margins, Trees, and Ensembles

Separating hyperplanes, decision trees and ensembles are three classic families of models. Margin methods choose a boundary with room on both sides and use kernels for curved boundaries, trees split the feature space into regions with simple predictions, and ensembles combine many models to reduce variance or bias. All of them are compared under one evaluation plan.

Perceptrons and separating hyperplanes

With labels y∈{−1,+1}y \in \{-1, +1\}, a linear classifier predicts +1+1 when w⊤x+b≥0\mathbf{w}^{\top}\mathbf{x} + b \ge 0 and −1-1 otherwise. The separating hyperplane w⊤x+b=0\mathbf{w}^{\top}\mathbf{x} + b = 0 has normal vector w\mathbf{w}, and scaling w\mathbf{w} and bb by the same positive number leaves it unchanged. The data are linearly separable when some (w,b)(\mathbf{w}, b) gives yi(w⊤xi+b)>0y_i(\mathbf{w}^{\top}\mathbf{x}_i + b) > 0 for every example.

The perceptron passes through the data repeatedly, and whenever yi(w⊤xi+b)≤0y_i(\mathbf{w}^{\top}\mathbf{x}_i + b) \le 0 it updates

w←w+η yixi,b←b+η yi,\begin{gathered} \mathbf{w} \leftarrow \mathbf{w} + \eta\,y_i\mathbf{x}_i, \\[0.4em] b \leftarrow b + \eta\,y_i, \end{gathered}

with η>0\eta > 0, stopping after a full pass without updates. The perceptron convergence theorem says that if, for the augmented vectors (xi,1)(\mathbf{x}_i, 1), some unit vector separates the data with margin γ>0\gamma > 0 and every augmented vector has norm at most RR, then starting from zero the perceptron makes at most (R/γ)2(R/\gamma)^2 updates. Without separability it never stops by itself, so a limit on the number of passes is needed.

Starting from w=(0,0)\mathbf{w} = (0, 0) and b=0b = 0 with η=1\eta = 1, the examples (1,0)(1, 0) labeled +1+1, (0,1)(0, 1) labeled −1-1, (2,0)(2, 0) labeled +1+1 and (0,2)(0, 2) labeled −1-1 cause two updates in the first pass, to w=(1,0)\mathbf{w} = (1, 0), b=1b = 1 and then w=(1,−1)\mathbf{w} = (1, -1), b=0b = 0, after which every example is classified correctly. A separating boundary found this way need not have a large margin, and another order of the examples can give another boundary.

Lessons Perceptrons and Separating Hyperplanes

Support vector machines and soft margins

For labels ±1\pm 1 and the score f(x)=w⊤x+bf(\mathbf{x}) = \mathbf{w}^{\top}\mathbf{x} + b, the functional margin of example ii is yif(xi)y_if(\mathbf{x}_i) and its geometric margin is yif(xi)/∥w∥2y_if(\mathbf{x}_i)/\lVert \mathbf{w} \rVert_2, the signed distance to the boundary. Requiring functional margins of at least 1 gives a margin band of width 2/∥w∥22/\lVert \mathbf{w} \rVert_2, so maximizing the margin means minimizing ∥w∥22\lVert \mathbf{w} \rVert_2^2. The soft-margin support vector machine of the course minimizes

ℓi=max⁡(0, 1−yif(xi)),J=12∥w∥22+C∑i=1nℓi,\begin{gathered} \ell_i = \max\big(0,\, 1 - y_if(\mathbf{x}_i)\big), \\[0.4em] J = \tfrac{1}{2}\lVert \mathbf{w} \rVert_2^2 + C\sum_{i=1}^{n}\ell_i, \end{gathered}

with C>0C > 0 and an unpenalized intercept. The hinge loss ℓi\ell_i is 0 on or beyond the correct margin, between 0 and 1 for a correctly classified point inside the margin, and above 1 for a misclassified point. A larger CC makes violations more expensive. The support vectors are the examples with positive dual weight. They lie on or inside the margin, and removing any other example leaves the solution unchanged. Other texts use a parameter λ\lambda with the average hinge loss, so convert before comparing values, and scale the features on training data first.

For inputs −2-2, −1-1, 1 and 2 with labels −1-1, −1-1, +1+1 and +1+1, the hard-margin solution w=1w = 1, b=0b = 0 has objective 0.50.5. With C=0.1C = 0.1 the optimum is w=0.5w = 0.5, with the two inner points inside the margin and objective 0.125+0.1=0.2250.125 + 0.1 = 0.225, and with C=1C = 1 the optimum is again w=1w = 1.

Lessons Support Vector Machines and Soft Margins

Kernel methods

A feature map ϕ\phi sends x\mathbf{x} into a feature space, and a kernel function computes the inner product k(x,z)=ϕ(x)⊤ϕ(z)k(\mathbf{x}, \mathbf{z}) = \phi(\mathbf{x})^{\top}\phi(\mathbf{z}) without forming ϕ\phi. The kernel trick replaces every inner product of an algorithm by kk, as in the kernel SVM, whose decision function is

f(x)=∑i=1nαiyi k(xi,x)+bf(\mathbf{x}) = \sum_{i=1}^{n}\alpha_iy_i\,k(\mathbf{x}_i, \mathbf{x}) + b

with dual weights 0≤αi≤C0 \le \alpha_i \le C that are nonzero only for the support vectors. A function kk is a valid, positive semidefinite kernel when every Gram matrix KK with entries Kij=k(xi,xj)K_{ij} = k(\mathbf{x}_i, \mathbf{x}_j) is symmetric and positive semidefinite, which holds exactly when kk is an inner product in some feature space.

Kernelk(x,z)k(\mathbf{x}, \mathbf{z})Parameters
Linearx⊤z\mathbf{x}^{\top}\mathbf{z}none
Polynomial(x⊤z+c)d(\mathbf{x}^{\top}\mathbf{z} + c)^dc≥0c \ge 0 and a whole number d≥1d \ge 1
Radial basis functionexp⁡(−γ∥x−z∥22)\exp(-\gamma\lVert \mathbf{x} - \mathbf{z} \rVert_2^2)γ>0\gamma > 0

In R2\mathbb{R}^2 the kernel (x⊤z)2(\mathbf{x}^{\top}\mathbf{z})^2 equals ϕ(x)⊤ϕ(z)\phi(\mathbf{x})^{\top}\phi(\mathbf{z}) for ϕ(x)=(x12,2 x1x2,x22)\phi(\mathbf{x}) = (x_1^2, \sqrt{2}\,x_1x_2, x_2^2), and at x=(1,2)\mathbf{x} = (1, 2) and z=(3,1)\mathbf{z} = (3, 1) both sides equal 25. A large γ\gamma makes the radial basis function kernel very local and the boundary very flexible. Choose CC and γ\gamma by cross-validation with feature scaling inside the folds, and note that not every similarity score is a valid kernel.

Lessons Kernel Methods

Classification trees

A classification tree splits the feature space by questions of the form xj≤tx_j \le t, and each leaf predicts the class proportions of the training rows that reach it, its leaf probabilities, or their majority class. For class proportions p1,…,pKp_1, \dots, p_K in a node,

Gini=1−∑k=1Kpk2,H=−∑k=1Kpklog⁡2pk,\begin{gathered} \text{Gini} = 1 - \sum_{k=1}^{K} p_k^2, \\[0.4em] H = -\sum_{k=1}^{K} p_k\log_2 p_k, \end{gathered}

with 0log⁡20=00\log_2 0 = 0. Both are 0 for a pure node, and for two classes both peak at equal proportions, at 0.50.5 and at 1 bit. A split that sends nLn_L of a node’s nn rows left and nRn_R right has weighted child impurity (nL/n)IL+(nR/n)IR(n_L/n)I_L + (n_R/n)I_R, where ILI_L and IRI_R are the child impurities, and a valid split leaves neither child empty. Information gain is the parent entropy minus the weighted child entropy, and the Gini reduction is defined in the same way. Greedy splitting chooses the best split at each node in turn, which does not guarantee the best tree overall.

A node with 4 negatives and 4 positives has Gini 0.50.5. A split into children with counts (3,1)(3, 1) and (1,3)(1, 3) leaves weighted Gini 3/83/8, a reduction of 1/81/8. A split into a pure (2,0)(2, 0) and a (2,4)(2, 4) leaves (6/8)(4/9)=1/3(6/8)(4/9) = 1/3, a reduction of 1/61/6, so it is better, and entropy agrees, with gains of about 0.1890.189 and 0.3110.311 bits. Pure training leaves can overfit, so depth and leaf size are limited.

Lessons Classification Trees

Regression trees and pruning

A regression tree predicts the mean target of the training rows in each leaf, which minimizes squared error within the leaf. A squared-error split is chosen to maximize SSEparent−SSEleft−SSEright\text{SSE}_{\text{parent}} - \text{SSE}_{\text{left}} - \text{SSE}_{\text{right}}, where each SSE is a sum of squared deviations from that node’s mean. Tree depth and minimum leaf size limit complexity. Cost-complexity pruning scores a subtree TT by

Rα(T)=SSE(T)+α ∣T∣,R_{\alpha}(T) = \text{SSE}(T) + \alpha\,\lvert T \rvert,

where ∣T∣\lvert T \rvert is the number of leaves and α≥0\alpha \ge 0, so a larger α\alpha favors smaller trees. A single leaf with SSE 100 and a two-leaf tree with SSE 4 tie at α=96\alpha = 96. Each α\alpha gives a pruned tree built from training data, and α\alpha itself is chosen by validation error or cross-validation, never by the test set. Software that averages the squared errors reports a differently scaled α\alpha.

Lessons Regression Trees and Pruning

Bagging and random forests

Bagging fits the same learner to BB bootstrap samples, each drawn with replacement from the nn training rows, and averages the predictions, or takes a majority vote for classes. A random forest bags deep trees and also chooses each split from a random subset of the features, which lowers the correlation between the trees. If the BB predictions f^1,…,f^B\hat{f}_1, \dots, \hat{f}_B at a point each have variance vv and every pair has correlation ρ\rho, their average fˉ\bar{f} has

Var⁡(fˉ)=v(ρ+1−ρB),\operatorname{Var}(\bar{f}) = v\Big(\rho + \frac{1 - \rho}{B}\Big),

so more trees shrink the second term but not ρv\rho v. With v=9v = 9 and ρ=0.2\rho = 0.2, B=10B = 10 gives 2.522.52 and B=100B = 100 gives 1.8721.872, approaching the floor 1.81.8.

A given row is left out of a bootstrap sample with probability (1−1/n)n(1 - 1/n)^n, about 0.3680.368 for large nn, and its out-of-bag prediction averages only the trees that did not see it. The out-of-bag error is a useful internal estimate for independent rows, but not for grouped or time-ordered data, and not after it has been used to tune the forest. Averaging reduces variance and does not remove a bias shared by all the trees.

Lessons Bagging and Random Forests

Gradient boosting and AdaBoost

Gradient boosting builds a stagewise additive model

Fm(x)=Fm−1(x)+ν hm(x),F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \nu\,h_m(\mathbf{x}),

where each weak learner hmh_m, often a small tree, is fitted to the negative gradient ri=−∂L(yi,F)/∂Fr_i = -\partial L(y_i, F)/\partial F of the loss at the current predictions F=Fm−1(xi)F = F_{m-1}(\mathbf{x}_i), and the shrinkage or learning rate is ν∈(0,1]\nu \in (0, 1]. For L=12(y−F)2L = \tfrac{1}{2}(y - F)^2 the negative gradient is y−Fy - F, the target minus the current prediction, so the familiar residual fitting is the squared-error special case. For log loss with a logit score FF it is y−σ(F)y - \sigma(F), the label minus the current probability.

For targets 1, 3, 7 and 9 at x=1,2,3,4x = 1, 2, 3, 4, the starting constant is F0=5F_0 = 5 and the negative gradients y−F0y - F_0 are −4-4, −2-2, 2 and 4. A stump split at 2.52.5 predicts their means −3-3 and 3, and with ν=0.5\nu = 0.5 the new predictions are 3.53.5, 3.53.5, 6.56.5 and 6.56.5, which lowers the training MSE from 10 to 3.253.25. The number of stages, ν\nu and the tree depth are tuned on validation data, often with early stopping, because many stages can overfit. Probabilities from gradient boosting may need calibration.

AdaBoost, for labels ±1\pm 1, gives a weak classifier with weighted error e∈(0,0.5)e \in (0, 0.5) the vote

αm=12log⁡1−ee,\alpha_m = \tfrac{1}{2}\log\frac{1 - e}{e},

multiplies each case weight by exp⁡(−αmyihm(xi))\exp(-\alpha_my_ih_m(\mathbf{x}_i)), renormalizes the weights to sum to 1, and predicts sign⁡(∑mαmhm(x))\operatorname{sign}\big(\sum_m \alpha_mh_m(\mathbf{x})\big). After the update the misclassified cases carry exactly half of the total weight. At e=0.25e = 0.25 the vote is α≈0.549\alpha \approx 0.549, and a misclassified case gains weight by a factor of 3 relative to a correct one.

Lessons Boosting and Gradient-Boosted Trees

Stacking and ensemble comparison

Model comparison is fair only with one split plan, the same folds and the same metric for every candidate. Stacking trains a meta-model on the predictions of several base models. The meta-model is fitted to out-of-fold predictions, made for each training row by base models that did not see that row, because in-sample predictions look better than they are, and the base models are then refitted on all the training data. Ensemble selection chooses a subset or weighting of models by validation performance, which is again a fitted choice that needs fresh data for its evaluation. An ensemble helps when its members are accurate and make different errors, and the gain is measured rather than assumed.

Lessons Stacking and Ensemble Comparison

Clustering and Dimensionality Reduction

Without labels, learning looks for structure in the inputs themselves. Every clustering method defines a cluster by its own criterion, and none of them shows that the groups it finds are real classes. Principal component analysis finds the directions of largest variance and measures what a low-dimensional reconstruction keeps, and anomaly detection scores new cases against a stated reference population.

Distances and the curse of dimensionality

MeasureFormulaNotes
Euclidean distance∥x−z∥2\lVert \mathbf{x} - \mathbf{z} \rVert_2depends on the scale of every feature
Manhattan distance∥x−z∥1\lVert \mathbf{x} - \mathbf{z} \rVert_1the sum of absolute differences
Weighted Euclidean distance∑jaj(xj−zj)2\sqrt{\sum_j a_j(x_j - z_j)^2}weights aj≥0a_j \ge 0 set how much each feature counts
Cosine similarityx⊤z∥x∥2∥z∥2\dfrac{\mathbf{x}^{\top}\mathbf{z}}{\lVert \mathbf{x} \rVert_2\lVert \mathbf{z} \rVert_2}needs nonzero vectors and ignores their lengths

Cosine similarity is 1 for vectors that point the same way, so (1,2)(1, 2) and (2,4)(2, 4) have cosine similarity 1 and Euclidean distance 5\sqrt{5}. Feature weighting, which includes the choice of units and any scaling, decides which differences count.

The curse of dimensionality is the collection of ways in which high-dimensional spaces defeat methods built on local neighborhoods. For two random points whose pp coordinates are independent and uniform on [0,1][0, 1], the squared distance has mean p/6p/6 and standard deviation 7p/180\sqrt{7p/180}, so its spread relative to its mean shrinks like 1/p1/\sqrt{p}, and the nearest and farthest neighbors of a point end up at similar distances. This distance concentration depends on the distribution, and data that lie near a low-dimensional structure suffer less from it.

Lessons Distance and the Curse of Dimensionality

K-means clustering

K-means divides nn points into kk clusters C1,…,CkC_1, \dots, C_k with centroids μ1,…,μk\boldsymbol{\mu}_1, \dots, \boldsymbol{\mu}_k, the cluster means, to minimize the within-cluster sum of squares

W=∑c=1k∑i∈Cc∥xi−μc∥22.W = \sum_{c=1}^{k}\sum_{i \in C_c}\lVert \mathbf{x}_i - \boldsymbol{\mu}_c \rVert_2^2 .

Lloyd’s algorithm alternates the assignment step, which gives each point to its nearest centroid, and the update step, which moves each centroid to the mean of its points. Neither step increases WW, so with a fixed rule for ties it stops after finitely many steps, at a local optimum that depends on the initialization. An empty cluster needs a stated rule. Running several initializations, for example with k-means++, which picks spread-out starting centroids, and keeping the lowest WW reduces the risk of a poor optimum.

For the corners (0,0)(0, 0), (0,1)(0, 1), (4,0)(4, 0) and (4,1)(4, 1) with k=2k = 2, starting centroids (0,0)(0, 0) and (4,0)(4, 0) end with the left and right pairs and W=1W = 1, while starting centroids (0,0)(0, 0) and (0,1)(0, 1) stop at the bottom and top pairs with W=16W = 16. The best achievable WW never increases as kk grows, so the number of clusters cannot be chosen by WW alone. K-means favors compact, roughly round clusters in the chosen scaling, and its clusters need not match meaningful categories.

Lessons K-Means Clustering

Hierarchical clustering

Agglomerative clustering starts with every point as its own cluster and repeatedly merges the two closest clusters under a linkage rule.

LinkageDistance between clusters AA and BB
Singlethe smallest distance between a point of AA and a point of BB
Completethe largest such distance
Averagethe mean of all such distances
Ward’s criterionthe increase in the within-cluster sum of squares, nAnBnA+nB∥xˉA−xˉB∥22\dfrac{n_An_B}{n_A + n_B}\lVert \bar{\mathbf{x}}_A - \bar{\mathbf{x}}_B \rVert_2^2

Ward’s criterion is defined for Euclidean data. A dendrogram draws the merges at their heights, and cutting it at a height gives a partition. For the points 0, 1, 3 and 6 on a line, single linkage merges at heights 1, 2 and 3, while complete linkage merges at 1, 3 and 6, with a tie at height 3 that needs a stated rule. Single linkage can chain distant points together through intermediate ones. Cluster stability, checked by resampling or perturbing the data, shows how much a partition depends on the particular sample, and neither a dendrogram cut nor a silhouette score shows that the clusters are true classes.

Lessons Hierarchical Clustering

Density-based clustering with DBSCAN

DBSCAN finds dense regions using a radius ε\varepsilon and a count min_samples. The epsilon neighborhood of a point holds every data point within distance ε\varepsilon of it, the point itself included under the course convention.

Point typeDefinition
Core pointat least min_samples points in its epsilon neighborhood
Border pointnot a core point, but inside the epsilon neighborhood of a core point
Noise pointneither a core point nor a border point

A point is density reachable from a core point when a chain of points leads from that core point to it, with each point of the chain within ε\varepsilon of the next and every point except possibly the last a core point. Two points are density connected when both are density reachable from one core point. A cluster is a maximal set of density-connected points. The grouping of the core points does not depend on the order of processing, while a border point near two clusters can be assigned to either.

On a line with points 0, 0.40.4, 0.80.8, 1.21.2, 3, 3.43.4, 3.83.8 and 6, with ε=0.5\varepsilon = 0.5 and min_samples equal to 3, the core points are 0.40.4, 0.80.8 and 3.43.4, the clusters are {0,0.4,0.8,1.2}\{0, 0.4, 0.8, 1.2\} and {3,3.4,3.8}\{3, 3.4, 3.8\}, and 6 is noise. DBSCAN needs no number of clusters, but its result depends on ε\varepsilon, min_samples and the feature scaling.

Lessons Density-Based Clustering with DBSCAN

Gaussian mixtures and expectation-maximization

A Gaussian mixture model has the density

p(x)=∑c=1kπc N(x∣μc,Σc),p(\mathbf{x}) = \sum_{c=1}^{k}\pi_c\,\mathcal{N}(\mathbf{x} \mid \boldsymbol{\mu}_c, \Sigma_c),

with mixing weights πc≥0\pi_c \ge 0 that add to 1. A latent variable zz records which component generated x\mathbf{x}, and the responsibility

ric=πc N(xi∣μc,Σc)∑jπj N(xi∣μj,Σj)r_{ic} = \frac{\pi_c\,\mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_c, \Sigma_c)}{\sum_{j}\pi_j\,\mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_j, \Sigma_j)}

is the posterior probability P(z=c∣xi)P(z = c \mid \mathbf{x}_i), a soft assignment of point ii to component cc. The density values themselves are not probabilities. The expectation-maximization algorithm alternates the E step, which computes the responsibilities from the current parameters, and the M step, which with Nc=∑iricN_c = \sum_i r_{ic} and dic=xi−μc\mathbf{d}_{ic} = \mathbf{x}_i - \boldsymbol{\mu}_c sets

πc=Ncn,μc=1Nc∑iricxi,Σc=1Nc∑iric dicdic⊤,\begin{gathered} \pi_c = \frac{N_c}{n}, \\[0.4em] \boldsymbol{\mu}_c = \frac{1}{N_c}\sum_{i} r_{ic}\mathbf{x}_i, \\[0.4em] \Sigma_c = \frac{1}{N_c}\sum_{i} r_{ic}\,\mathbf{d}_{ic}\mathbf{d}_{ic}^{\top}, \end{gathered}

using the new μc\boldsymbol{\mu}_c in dic\mathbf{d}_{ic}. No iteration decreases the likelihood, but EM can stop at a local optimum, so several starts are used. The likelihood grows without bound when a component centers on one data point and its covariance shrinks toward zero, so a floor on the variances or a small multiple of the identity added to each Σc\Sigma_c is needed. With observations −2-2, −1-1, 2 and 3, equal weights, means −1-1 and 2 and unit variances, the first component takes responsibility about 0.9890.989 for −1-1 and about 0.0110.011 for 2.

Lessons Gaussian Mixtures and Expectation-Maximization

Covariance, eigenvectors and PCA

Principal component analysis needs centered data, each row minus the training mean, and a decision on whether to standardize the features first, since PCA follows the largest variances in whatever units the features have. With the centered n×pn \times p matrix XcX_c and n≥2n \ge 2, the sample covariance matrix is

C=1n−1Xc⊤Xc,C = \frac{1}{n - 1}X_c^{\top}X_c,

which is symmetric and positive semidefinite. A unit vector v\mathbf{v} gives the projected scores XcvX_c\mathbf{v}, whose sample variance is v⊤Cv\mathbf{v}^{\top}C\mathbf{v}. The principal directions are orthonormal eigenvectors v1,v2,…\mathbf{v}_1, \mathbf{v}_2, \dots of CC, with Cvj=λjvjC\mathbf{v}_j = \lambda_j\mathbf{v}_j and eigenvalues λ1≥λ2≥⋯≥0\lambda_1 \ge \lambda_2 \ge \cdots \ge 0. The first direction maximizes v⊤Cv\mathbf{v}^{\top}C\mathbf{v} over unit vectors, with maximum λ1\lambda_1, and each later direction maximizes it among unit vectors orthogonal to the earlier ones. The sign of an eigenvector is arbitrary, and a repeated eigenvalue leaves the directions within its eigenspace unspecified.

The points (1,1)(1, 1), (2,2)(2, 2) and (3,3)(3, 3) center to (−1,−1)(-1, -1), (0,0)(0, 0) and (1,1)(1, 1). Their covariance matrix has every entry equal to 1, its eigenvalues are 2 and 0, and the first principal direction is (1,1)/2(1, 1)/\sqrt{2}.

Lessons Covariance, Eigenvectors, and PCA

PCA with the SVD and reconstruction

The thin singular value decomposition of the centered matrix is Xc=USV⊤X_c = USV^{\top}, where, with q=min⁡(n,p)q = \min(n, p), the matrices UU of size n×qn \times q and VV of size p×qp \times q have orthonormal columns and SS is diagonal with the singular values σ1≥⋯≥σq≥0\sigma_1 \ge \cdots \ge \sigma_q \ge 0. The columns of VV are the principal directions, the principal component scores are XcV=USX_cV = US, and the covariance eigenvalues are

λj=σj2n−1.\lambda_j = \frac{\sigma_j^2}{n - 1} .

The explained variance ratio of component jj is σj2/∑lσl2\sigma_j^2/\sum_l \sigma_l^2, defined when XcX_c is not zero. Keeping the first rr components gives the low-rank reconstruction X^=UrSrVr⊤\hat{X} = U_rS_rV_r^{\top}, the best approximation of rank rr in total squared error, and its reconstruction error, the sum of all squared entries of Xc−X^X_c - \hat{X}, is

∥Xc−X^∥F2=∑j>rσj2.\lVert X_c - \hat{X} \rVert_F^2 = \sum_{j > r} \sigma_j^2 .

Adding the mean back returns the reconstruction to the original units. The centered points (−2,−1)(-2, -1), (−2,1)(-2, 1), (2,−1)(2, -1) and (2,1)(2, 1) have singular values 4 and 2, so the first component explains 16/20=8016/20 = 80 percent of the variation, and the rank-one reconstruction has squared error 4.

Lessons PCA with SVD and Reconstruction

Dimensionality reduction for prediction and visualization

Dimensionality reduction maps pp features to fewer. In a PCA pipeline the centering, the scaling and the components are fitted on the training fold only, and the number of components is a hyperparameter. PCA keeps the directions of largest variance, which need not be the directions that predict the target, so the information loss that matters is measured by validation performance, not only by explained variance.

t-SNE and UMAP are nonlinear methods for drawing the local neighborhood structure of data in two or three dimensions. t-SNE matches neighbor probabilities in the data with those in the map, and its perplexity, roughly the effective number of neighbors, sets the scale of the neighborhoods. Both depend on their settings and on random initialization, and in their maps the distances between separated clusters and the sizes of clusters are not reliable. They are tools for looking at data, not evidence that groups exist in the population.

Lessons Dimensionality Reduction and Visualization

Anomaly and novelty detection

Anomaly detection scores how far an observation departs from a reference population, a stated set of normal cases. Novelty detection fits the reference on data assumed to be clean and scores new observations, while outlier detection searches the fitting data themselves, where training contamination by unusual cases can hide them. An anomaly score needs an explicit definition, such as a z-score ∣x−xˉ∣/s\lvert x - \bar{x} \rvert/s against the reference, a distance to the nearest reference points, or an isolation forest score, which is high for points that random axis-aligned splits isolate in few steps.

Reference readings 9, 10, 10 and 11 have mean 10 and population standard deviation 0.5≈0.707\sqrt{0.5} \approx 0.707, so new readings of 8 and 14 score about 2.832.83 and 5.665.66. An alert threshold turns scores into actions. It is chosen from review capacity and costs, and evaluated with labels or reviewed cases. A rare observation is not necessarily a harmful one.

Lessons Anomaly and Novelty Detection

Neural Network Foundations

A neural network composes linear maps with nonlinear activations. The forward pass computes the prediction layer by layer, backpropagation applies the chain rule to get every gradient, and training repeats gradient steps on mini-batches. Regularization and early stopping are chosen on validation data, and a network is worth its cost only when it beats a simpler baseline.

Neural networks and forward propagation

A feed-forward neural network computes, layer by layer from a(0)=x\mathbf{a}^{(0)} = \mathbf{x},

z(l)=W(l)a(l−1)+b(l),a(l)=ϕ(z(l)),\begin{gathered} \mathbf{z}^{(l)} = W^{(l)}\mathbf{a}^{(l-1)} + \mathbf{b}^{(l)}, \\[0.4em] \mathbf{a}^{(l)} = \phi(\mathbf{z}^{(l)}), \end{gathered}

where W(l)W^{(l)} has one row per unit of layer ll and one column per unit of layer l−1l - 1, and the activation function ϕ\phi acts on each entry. This is forward propagation. A hidden layer uses a nonlinear activation such as ReLU⁡(z)=max⁡(0,z)\operatorname{ReLU}(z) = \max(0, z), and without one the whole network collapses to a single linear map. The output layer matches the task, with an identity output and squared loss for regression, a sigmoid and binary cross-entropy for two classes, or a softmax and cross-entropy for several. Tracking the tensor shape of every layer, with the batch as an extra axis, catches most implementation errors.

For x=(1,2)\mathbf{x} = (1, 2), first-layer rows (1,−1)(1, -1) and (0.5,0.5)(0.5, 0.5), biases (0,−1)(0, -1), ReLU, output weights (2,−2)(2, -2) and output bias 1, the hidden pre-activations are (−1,0.5)(-1, 0.5), the activations (0,0.5)(0, 0.5) and the output 1+0−1=01 + 0 - 1 = 0. Hidden ReLU units can represent XOR, which no linear classifier can. With h1=ReLU⁡(x1+x2)h_1 = \operatorname{ReLU}(x_1 + x_2) and h2=ReLU⁡(x1+x2−1)h_2 = \operatorname{ReLU}(x_1 + x_2 - 1), the output h1−2h2h_1 - 2h_2 is 0, 1, 1 and 0 on (0,0)(0, 0), (0,1)(0, 1), (1,0)(1, 0) and (1,1)(1, 1).

The universal approximation theorem says that a network with one hidden layer and a continuous activation that is not a polynomial, ReLU included, can approximate any continuous function on a closed and bounded subset of Rp\mathbb{R}^p to any accuracy, given enough hidden units. It says nothing about how many units are needed, whether training finds such weights or how well the network generalizes.

Lessons Neural Networks and Forward Propagation

Backpropagation and automatic differentiation

A computational graph records every operation of the forward pass. Backpropagation applies the multivariable chain rule from the loss back through the graph, multiplying local derivatives along each path and adding the contributions where paths merge. For the layers above, with δ(l)=∂L/∂z(l)\boldsymbol{\delta}^{(l)} = \partial L/\partial\mathbf{z}^{(l)},

∂L∂W(l)=δ(l) a(l−1)⊤,∂L∂b(l)=δ(l),δ(l−1)=(W(l)⊤δ(l))⊙ϕ′(z(l−1)),\begin{aligned} \frac{\partial L}{\partial W^{(l)}} &= \boldsymbol{\delta}^{(l)}\,\mathbf{a}^{(l-1)\top}, \\[0.4em] \frac{\partial L}{\partial \mathbf{b}^{(l)}} &= \boldsymbol{\delta}^{(l)}, \\[0.4em] \boldsymbol{\delta}^{(l-1)} &= \big(W^{(l)\top}\boldsymbol{\delta}^{(l)}\big) \\ &\quad \odot \phi'(\mathbf{z}^{(l-1)}), \end{aligned}

where ⊙\odot is the entrywise product. For a sigmoid output with binary cross-entropy, or a softmax output with cross-entropy, the error at the output scores is p−y\mathbf{p} - \mathbf{y}. Reverse-mode automatic differentiation does this in code and computes all partial derivatives of a scalar loss for a small constant multiple of the cost of one forward pass. ReLU has no derivative at 0, and software uses a fixed value there, usually 0.

A gradient check compares a coded gradient with central differences (L(θ+hej)−L(θ−hej))/(2h)(L(\boldsymbol{\theta} + h\mathbf{e}_j) - L(\boldsymbol{\theta} - h\mathbf{e}_j))/(2h) on a small case, where ej\mathbf{e}_j is the jjth unit vector. Agreement to several digits is good evidence that the code is right, not a proof, and points where an activation has a kink can disagree.

Lessons Backpropagation and Automatic Differentiation

Training neural networks

A training loop repeats, for every mini-batch, the forward pass, the loss, backpropagation and a parameter update, and it evaluates the validation data without updating. Weight initialization breaks the symmetry between units with random weights of a suitable scale, such as variance 2/nin2/n_{\text{in}} for ReLU layers (He initialization) or 2/(nin+nout)2/(n_{\text{in}} + n_{\text{out}}) (Glorot or Xavier initialization), where ninn_{\text{in}} and noutn_{\text{out}} count the inputs and outputs of the layer. A vanishing gradient shrinks as it passes back through many layers and an exploding gradient grows, and poor scaling makes both worse.

Momentum, in the course convention, keeps mt=βmt−1+(1−β)gt\mathbf{m}_t = \beta\mathbf{m}_{t-1} + (1 - \beta)\mathbf{g}_t for the gradient gt\mathbf{g}_t and updates θ\boldsymbol{\theta} by −η mt-\eta\,\mathbf{m}_t. Adam keeps two moving averages and corrects their start at zero,

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,m^t=mt/(1−β1t),v^t=vt/(1−β2t),θt=θt−1−η m^tv^t+ϵ,\begin{aligned} \mathbf{m}_t &= \beta_1\mathbf{m}_{t-1} + (1 - \beta_1)\mathbf{g}_t, \\[0.4em] \mathbf{v}_t &= \beta_2\mathbf{v}_{t-1} + (1 - \beta_2)\mathbf{g}_t^{2}, \\[0.4em] \hat{\mathbf{m}}_t &= \mathbf{m}_t/(1 - \beta_1^t), \\[0.4em] \hat{\mathbf{v}}_t &= \mathbf{v}_t/(1 - \beta_2^t), \\[0.4em] \boldsymbol{\theta}_t &= \boldsymbol{\theta}_{t-1} - \frac{\eta\,\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}, \end{aligned}

with the square, the root and the division taken entry by entry, commonly β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and a small ϵ>0\epsilon > 0, and with both averages starting at 0. At the first step with gradient 2, the averages 0.20.2 and 0.0040.004 are corrected to 2 and 4, and with η=0.01\eta = 0.01 the step has size about 0.010.01. Adam does not guarantee convergence or better generalization.

Batch normalization standardizes each feature over the mini-batch during training, (z−μB)/σB2+ϵ(z - \mu_B)/\sqrt{\sigma_B^2 + \epsilon} with the batch mean μB\mu_B and variance σB2\sigma_B^2, and then applies a learned scale and shift. At evaluation it uses running averages collected during training, so the training and evaluation modes of a network behave differently.

Lessons Training Neural Networks

Neural regularization and early stopping

Weight decay shrinks the weights. Adding λ2∥w∥22\tfrac{\lambda}{2}\lVert \mathbf{w} \rVert_2^2 to the mean data loss gives the gradient descent update

w←(1−ηλ) w−η g,\mathbf{w} \leftarrow (1 - \eta\lambda)\,\mathbf{w} - \eta\,\mathbf{g},

where g\mathbf{g} is the gradient of the data loss, usually with the biases left unpenalized. With w=2w = 2, g=0.3g = 0.3, η=0.1\eta = 0.1 and λ=0.2\lambda = 0.2 the new weight is 1.931.93, against 1.971.97 without decay. For plain gradient descent the penalty and this shrinkage are the same thing, but for adaptive optimizers they differ, and decoupled weight decay, as in AdamW, applies the shrinkage outside the adaptive step.

Dropout sets each hidden activation to zero with probability 1−q1 - q during training. Inverted dropout divides the kept activations by the keep probability qq, so each activation keeps its expected value, and dropout is switched off at evaluation. With q=0.75q = 0.75 a kept activation of 2 becomes 8/38/3. Early stopping tracks the validation loss during training and keeps the checkpoint with the best value. That checkpoint selection uses the validation set, so the final performance needs a separate test set.

Lessons Neural Regularization and Early Stopping

A complete neural classification example

A small neural network classifier earns its place only when it beats a simple baseline, such as logistic regression, under the same data roles, the same preprocessing fitted on the training data and the same metric. Record the network architecture, the initialization, the random seed, the optimizer settings, the stopping rule and the decision threshold. Choose the architecture on validation data, never on the test set, and repeat the run with several seeds when the differences are small, since a single seed can mislead.

Lessons A Complete Neural Classification Example

Representations, Vision, and Learning from Few Labels

A learned representation lets a model reuse what was found in another task or in unlabeled data. Convolutions share small filters across an image, embeddings and pretrained networks carry features to new tasks, and autoencoders and self-supervised objectives learn features without labels. Each of these choices is checked on a downstream task with honest splits.

Convolutional neural networks

A convolutional layer slides a small filter over the input and computes a weighted sum at every position, giving a feature map. Deep learning software computes the cross-correlation S=I⋆KS = I \star K of an image II with a filter KK, without flipping the filter,

Sij=∑u∑vIi+u, j+v Kuv,S_{ij} = \sum_{u}\sum_{v} I_{i+u,\,j+v}\,K_{uv},

and calls it convolution. The same filter is used at every position, so a convolutional neural network has far fewer parameters than a fully connected one. For an input side nn, padding pp on each side, filter side kk and stride ss, the output side is

nout=⌊n+2p−ks⌋+1,n_{\text{out}} = \Big\lfloor \frac{n + 2p - k}{s} \Big\rfloor + 1,

so a 7×77 \times 7 input with k=3k = 3, p=1p = 1 and s=2s = 2 gives a 4×44 \times 4 map. A layer with CinC_{\text{in}} input channels and CoutC_{\text{out}} filters of size k×kk \times k has Cout(k2Cin+1)C_{\text{out}}(k^2C_{\text{in}} + 1) parameters, including one bias per filter, which is 168 for k=3k = 3, Cin=3C_{\text{in}} = 3 and Cout=6C_{\text{out}} = 6.

The receptive field of an output is the input region that can affect it, and two stacked 3×33 \times 3 layers with stride 1 see a 5×55 \times 5 region. Pooling summarizes each small window by its maximum or average and shrinks the map. A filter that responds to a pattern detects that local pattern, which is not evidence of understanding in any wider sense.

Lessons Convolutional Neural Networks

Embeddings and transfer learning

An embedding is a learned feature vector for an input, such as the row of a learned table for each token or category, or the last hidden layer of a network. Representation learning fits such features from data, and two embeddings are close only with respect to the objective and the data they were trained on. Transfer learning starts from a pretrained model. A frozen feature extractor keeps the pretrained layers fixed and trains only a new prediction head, while fine-tuning also updates some or all pretrained weights, usually with a small learning rate. Compare both with a model trained from scratch under one protected split, check that the pretrained model’s data and license allow the intended use, and expect transfer to fail when the new data differ too much from the pretraining data.

Lessons Embeddings and Transfer Learning

Autoencoders and nonlinear representations

An autoencoder has an encoder ff that maps an input to a latent representation h=f(x)\mathbf{h} = f(\mathbf{x}) and a decoder gg that maps it back, and it is trained to minimize a reconstruction loss such as ∥x−g(f(x))∥22\lVert \mathbf{x} - g(f(\mathbf{x})) \rVert_2^2. A bottleneck, a latent dimension smaller than the input dimension, forces compression. A linear autoencoder with squared loss on centered data and a bottleneck of size rr reconstructs, at its optimum, through the same rr-dimensional subspace as PCA with rr components when that subspace is unique, although its latent coordinates need not be the principal component scores.

Nonlinear encoders and decoders give nonlinear dimensionality reduction. A denoising autoencoder learns to reconstruct x\mathbf{x} from a corrupted copy of it. A low reconstruction error does not by itself show that the latent features are useful for another task, which is checked on validation data for that task.

Lessons Autoencoders and Nonlinear Representations

Semi-supervised and self-supervised learning

Semi-supervised learning uses a few labeled and many unlabeled examples. Pseudo-labeling trains on the labeled data, adds unlabeled examples with confident predictions as if labeled and retrains, and consistency regularization penalizes different predictions for two perturbed versions of one input. Both can hurt when the confident predictions are wrong or the unlabeled data differ from the labeled data, and pseudo-labels are never counted as verified labels in a report. Active learning chooses which unlabeled examples to send for labeling, for example the ones the model is least sure about.

Self-supervised learning builds its targets from the data themselves, such as a hidden part of the input to be predicted. Contrastive learning pulls together the embeddings of a positive pair, usually two augmented views of one example, and pushes apart negative pairs. With similarity s+s_+ for the positive, sjs_j for each negative and a temperature τ>0\tau > 0, a common loss is

−log⁡es+/τes+/τ+∑jesj/τ.-\log\frac{e^{s_+/\tau}}{e^{s_+/\tau} + \sum_{j} e^{s_j/\tau}} .

With s+=1s_+ = 1, two negatives at 0 and τ=1\tau = 1 the loss is −log⁡(e/(e+2))≈0.551-\log(e/(e + 2)) \approx 0.551. Representation collapse, every input mapped to nearly the same embedding, makes all similarities equal, which gives the larger loss log⁡3≈1.099\log 3 \approx 1.099 here. The augmentations must keep whatever the downstream task needs, and a learned representation is judged by validation on that task.

Lessons Semi-Supervised and Self-Supervised Learning

Image classification and augmentation

Data augmentation adds modified copies of training images, such as crops, flips or small rotations. An augmentation is label-preserving only for the task at hand, since a half turn changes a 6 into a 9. Augment the training data only, after the split. A subject-level split keeps all images of one person, object or scene, and all near-duplicates, on the same side of every split. Compare a simple baseline, a small convolutional network and a frozen-feature model on the same split, and inspect the errors by class and by condition.

Lessons Image Classification and Augmentation

Text, Sequences, and Modern Generative Models

Text and other sequences need representations of their units and of their order. Sparse word counts with TF-IDF weights give strong linear baselines, recurrent networks carry a state along a sequence, and attention lets every position draw on the others. Transformers stack attention with feed-forward layers, and generative models are trained with objectives that are not interchangeable.

Text features and TF-IDF

Tokenization splits text into tokens by a stated rule, and the vocabulary is the list of tokens kept from the training documents. The bag of words representation counts each token in each document and ignores word order, giving a document-term matrix CC in which CijC_{ij} counts term jj in document ii. Most entries are zero, so it is stored as a sparse matrix. In the course convention the term frequency is the raw count, the document frequency df⁡j\operatorname{df}_j is the number of the nn training documents that contain term jj, and

idf⁡j=1+log⁡1+n1+df⁡j,Tij=Cij idf⁡j,\begin{gathered} \operatorname{idf}_j = 1 + \log\frac{1 + n}{1 + \operatorname{df}_j}, \\[0.4em] T_{ij} = C_{ij}\,\operatorname{idf}_j, \end{gathered}

often followed by dividing each row by its Euclidean norm when that norm is positive. With n=4n = 4 documents, terms that occur in 3, 2 and 1 of them get idf weights of about 1.2231.223, 1.5111.511 and 1.9161.916. The vocabulary and the idf weights are fitted on the training documents, and an unknown token in a new document is dropped or mapped to a stated unknown column. TF-IDF names a family of formulas, so the variant is always stated.

Lessons Text Features and TF-IDF

Text classification pipelines

Text classification assigns labels to documents, usually with a sparse pipeline of tokenization, counts or TF-IDF weights and a linear model. Multinomial naive Bayes scores a document with counts CjC_j by log⁡P(c)+∑jCjlog⁡θcj\log P(c) + \sum_j C_j\log\theta_{cj}, with the smoothed word probabilities θcj=(Ncj+α)/(Nc+α∣V∣)\theta_{cj} = (N_{cj} + \alpha)/(N_c + \alpha\lvert V \rvert) from the naive Bayes topic. Regularized logistic regression on TF-IDF features is the usual discriminative alternative.

Text leakage comes from duplicates, from the same author or thread, or from later messages on both sides of a split. A collection artifact, such as a signature or a word typical of one source, can predict the label in the collected data without having anything to do with its meaning. Check the errors by source and subgroup, respect the permissions attached to the data, and remove sensitive information the task does not need.

Lessons Text Classification Pipelines

Recurrent neural networks

A recurrent neural network reads a sequence x1,…,xT\mathbf{x}_1, \dots, \mathbf{x}_T and updates a hidden state with the same parameters at every step,

ut=Wxxt+Whht−1+b,ht=tanh⁡(ut),\begin{aligned} \mathbf{u}_t &= W_x\mathbf{x}_t + W_h\mathbf{h}_{t-1} + \mathbf{b}, \\[0.4em] \mathbf{h}_t &= \tanh(\mathbf{u}_t), \end{aligned}

where, for inputs with dd entries and a state with dhd_h entries, WxW_x is dh×dd_h \times d and WhW_h is dh×dhd_h \times d_h. A prediction at step tt comes from an output layer applied to ht\mathbf{h}_t, such as a softmax over the next symbol. Backpropagation through time unrolls the network over the steps and adds up the gradient contributions of the shared weights from every step, and repeated multiplication by WhW_h can make gradients vanish or explode. With scalar weights 1 and 0.50.5, zero bias and h0=0h_0 = 0, the inputs 1, 0 and −1-1 give the states about 0.7620.762, 0.3630.363 and −0.674-0.674.

A long short-term memory network adds a cell state ct=ft⊙ct−1+it⊙c~t\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t, where the forget gate ft\mathbf{f}_t and the input gate it\mathbf{i}_t are sigmoid outputs between 0 and 1 and c~t\tilde{\mathbf{c}}_t is a candidate update, and an output gate ot\mathbf{o}_t gives ht=ot⊙tanh⁡(ct)\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t). A gated recurrent unit uses two gates and no separate cell state. Sequences of different lengths are padded to a common length, and a sequence mask removes the padded positions from the loss. Teacher forcing feeds the true previous token during training, while generation feeds the model’s own previous output.

Lessons Sequence Models and Recurrent Neural Networks

Attention, queries, keys and values

Scaled dot-product attention takes queries Q∈Rnq×dkQ \in \mathbb{R}^{n_q \times d_k}, keys K∈Rnk×dkK \in \mathbb{R}^{n_k \times d_k} and values V∈Rnk×dvV \in \mathbb{R}^{n_k \times d_v} and returns an nq×dvn_q \times d_v matrix,

A=softmax⁡(QK⊤dk),Attention⁡(Q,K,V)=AV,\begin{gathered} A = \operatorname{softmax}\Big(\frac{QK^{\top}}{\sqrt{d_k}}\Big), \\[0.4em] \operatorname{Attention}(Q, K, V) = AV, \end{gathered}

with the softmax applied to each row of scores. Row ii of the attention weights AA is a probability vector over the keys, and output row ii is the matching weighted average of the value rows. If the entries of a query and a key are independent with mean 0 and variance 1, their dot product has variance dkd_k, and dividing by dk\sqrt{d_k} brings it back to 1.

An attention mask sets disallowed scores to −∞-\infty before the softmax. A causal mask lets position ii attend only to positions 1 to ii, and a padding mask hides padded keys. A row with every key masked has no valid softmax and needs an explicit rule. If a causal row has scores 0 and 1 for its two allowed keys, its weights are 1/(1+e)≈0.2691/(1 + e) \approx 0.269 and e/(1+e)≈0.731e/(1 + e) \approx 0.731. Multi-head attention runs several heads with their own learned projections of the queries, keys and values, concatenates their outputs and applies an output projection. An attention weight says how much one value contributes in one head, not how much an input token causes the prediction.

Lessons Attention, Queries, Keys, and Values

Transformers and self-supervised language models

A transformer block acts on a matrix HH of token vectors, one row per position and dd columns, and adds two sublayers to a residual connection. In the pre-normalization arrangement,

H′=H+MHA⁡(LN⁡(H)),H′′=H′+FFN⁡(LN⁡(H′)),\begin{aligned} H' &= H + \operatorname{MHA}(\operatorname{LN}(H)), \\[0.4em] H'' &= H' + \operatorname{FFN}(\operatorname{LN}(H')), \end{aligned}

where MHA is multi-head self-attention and FFN applies the same small two-layer network to each position. Layer normalization standardizes the dd features of each position with that position’s own mean and variance, (h−mean)/variance+ϵ(h - \text{mean})/\sqrt{\text{variance} + \epsilon}, then applies a learned scale and shift. It does not mix positions and uses no batch statistics. Token embeddings look up a learned vector for each token, and since attention by itself ignores order, positional encoding adds learned or fixed position vectors, such as sinusoids of the position, or uses relative positions.

Masked language modeling hides some tokens and predicts them from the context on both sides, as in encoder models. Next-token prediction trains a decoder-only model with a causal mask to maximize ∑tlog⁡P(xt∣x<t)\sum_t \log P(x_t \mid x_{<t}), so a sequence x1,…,xTx_1, \dots, x_T supplies the training pairs of each prefix x<tx_{<t} with its next token xtx_t. The probabilities of such a model describe what is likely under its training data, not what is true.

Lessons Transformers and Self-Supervised Language Models

Generative models and their evaluation

A generative model describes, or samples from, a distribution of data. An autoregressive model uses the factorization

p(x1:T)=∏t=1Tp(xt∣x<t)p(x_{1:T}) = \prod_{t=1}^{T} p(x_t \mid x_{<t})

and is trained by maximum likelihood. A latent-variable model draws zz from a prior p(z)p(z) and then xx from pθ(x∣z)p_{\theta}(x \mid z), so that pθ(x)=∫p(z) pθ(x∣z) dzp_{\theta}(x) = \int p(z)\,p_{\theta}(x \mid z)\,dz. A variational autoencoder trains an encoder q=qϕ(z∣x)q = q_{\phi}(z \mid x) together with the decoder by maximizing the evidence lower bound

ELBO⁡=Eq[log⁡pθ(x∣z)]−DKL(q ∥ p(z)),\begin{aligned} \operatorname{ELBO} &= E_{q}\big[\log p_{\theta}(x \mid z)\big] \\[0.4em] &\quad - D_{\mathrm{KL}}\big(q \,\Vert\, p(z)\big), \end{aligned}

where the expectation is over zz drawn from qq. For distributions gg and hh on the same states, the Kullback-Leibler divergence DKL(g ∥ h)=∑zg(z)log⁡(g(z)/h(z))D_{\mathrm{KL}}(g \,\Vert\, h) = \sum_z g(z)\log(g(z)/h(z)), summed over the states with g(z)>0g(z) > 0, is never negative and is 0 when the two agree. The gap log⁡pθ(x)−ELBO⁡\log p_{\theta}(x) - \operatorname{ELBO} equals DKL(q ∥ pθ(z∣x))D_{\mathrm{KL}}\big(q \,\Vert\, p_{\theta}(z \mid x)\big), so the ELBO never exceeds the log likelihood.

A generative adversarial network trains a generator against a discriminator that tries to tell real samples from generated ones, and mode collapse is a generator that covers only part of the data distribution. A diffusion model adds noise to data in many small steps, trains a network to remove it, and generates by denoising pure noise step by step. These objectives are not interchangeable likelihood scores, and realistic samples say nothing about factual accuracy or about permission to use the training data.

Lessons Generative Models and Their Evaluation

Recommendations and Forecasting

Recommendation and forecasting apply the same workflow to ranked lists and to future values. A recommender scores candidate items and is evaluated with ranking metrics that state their cutoff and denominator. A forecast is made at an origin for a fixed horizon, compared with naive baselines, and evaluated by replaying the forecasts that could have been made at each past time.

Recommender systems and matrix factorization

A recommender system scores candidate items for a user and shows the top of the ranking. Content-based recommendation compares item features with a user’s profile, and collaborative filtering uses the interactions of similar users or items. Matrix factorization predicts the interaction of user aa with item jj as r^aj=ua⊤vj\hat{r}_{aj} = \mathbf{u}_a^{\top}\mathbf{v}_j, with the user vectors as rows of UU and the item vectors as rows of VV, and fits them on the set Ω\Omega of observed pairs by minimizing

∑(a,j)∈Ω(raj−ua⊤vj)2+λ(∥U∥F2+∥V∥F2),\begin{aligned} &\sum_{(a, j) \in \Omega}(r_{aj} - \mathbf{u}_a^{\top}\mathbf{v}_j)^2 \\[0.4em] &\quad + \lambda\big(\lVert U \rVert_F^2 + \lVert V \rVert_F^2\big), \end{aligned}

where ∥⋅∥F2\lVert \cdot \rVert_F^2 is the sum of squared entries. Explicit feedback is a rating, while implicit feedback is behavior such as a click or a purchase. An unobserved interaction is not a confirmed dislike, since the user may never have seen the item. Cold start is a new user or item without interactions, which content features or popularity have to cover.

With a cutoff kk, precision at kk is the number of relevant items among the top kk divided by kk, and recall at kk divides the same number by all relevant items for that user. Normalized discounted cumulative gain uses the graded relevance relr\text{rel}_r of the item at rank rr,

DCG@k=∑r=1k2relr−1log⁡2(r+1),NDCG@k=DCG@kIDCG@k,\begin{gathered} \text{DCG@}k = \sum_{r=1}^{k}\frac{2^{\text{rel}_r} - 1}{\log_2(r + 1)}, \\[0.4em] \text{NDCG@}k = \frac{\text{DCG@}k}{\text{IDCG@}k}, \end{gathered}

where IDCG@k\text{IDCG@}k is the DCG of the best possible order of the candidates, and NDCG is undefined when no candidate is relevant. With binary relevance, a top two of one relevant and one irrelevant item, when two relevant items exist, has NDCG@2=1/(1+1/log⁡23)≈0.613\text{NDCG@}2 = 1/(1 + 1/\log_2 3) \approx 0.613. A list with relevance 1, 0 and 1 in its top three, out of 4 relevant items in all, has precision at 3 of 2/32/3 and recall at 3 of 1/21/2. Split by time, so that the training interactions come before the recommendation, and keep in mind that offline ranking metrics do not measure the effect of actually showing the recommendations.

Lessons Recommender Systems and Matrix Factorization

Time-series features and forecasting

A time series y1,y2,…y_1, y_2, \dots is ordered in time. A forecast made at the forecast origin TT for the forecast horizon hh is written y^T+h∣T\hat{y}_{T+h \mid T}, and it may use only information available at time TT. A lag feature is an earlier value such as yt−1y_{t-1} or yt−7y_{t-7}, and any rolling summary must end at or before the origin. Seasonality is a pattern that repeats with a period mm. The naive forecast repeats the last value, y^T+h∣T=yT\hat{y}_{T+h \mid T} = y_T, and the seasonal-naive forecast repeats the value from the same point of the last observed season,

y^T+h∣T=yT+h−m⌈h/m⌉.\hat{y}_{T+h \mid T} = y_{T + h - m\lceil h/m \rceil} .

For a daily series ending in 26, 30 and 24 with period 3, the seasonal-naive forecasts for the next three days are 26, 30 and 24, and the naive forecast is 24 for every horizon. These are the baselines a model has to beat. Random row splits do not fit forecasting, and predicting future values is a different task from filling in gaps inside the observed period.

Lessons Time-Series Features and Forecasting

Rolling forecast evaluation

Rolling-origin evaluation, also called time-series backtesting, makes forecasts from a sequence of origins, fitting and tuning each time with data up to that origin only, and scores each forecast against the values that followed. An expanding window uses all data up to the origin, and a sliding window uses only the most recent stretch of fixed length, which adapts faster to drift but uses less data. Report the forecast error by horizon and by period, since errors change as the data drift. The update policy, how often the model is refitted, is part of the procedure being evaluated. Errors from nearby origins are dependent, so their spread is not an ordinary confidence interval.

Lessons Rolling Forecast Evaluation

Reinforcement Learning and Sequential Decisions

In reinforcement learning the data depend on the actions taken. A bandit chooses repeatedly among actions with unknown average rewards and must balance exploration against exploitation. A Markov decision process adds states that actions change, the Bellman equations relate the value of a state to the values that follow, and temporal-difference methods learn those values from single transitions.

Multi-armed bandits and exploration

A stationary multi-armed bandit offers actions aa with fixed unknown mean rewards μa\mu_a. In each round the learner picks one action and sees only that action’s reward. The action value estimate is the average reward of the action so far, and after its nnth reward RnR_n it is updated incrementally by

Qn+1=Qn+1n(Rn−Qn),Q_{n+1} = Q_n + \frac{1}{n}(R_n - Q_n),

where QnQ_n is the average of the first n−1n - 1 rewards. Exploitation picks the action with the highest estimate, and exploration tries other actions to learn about them. An epsilon-greedy policy picks uniformly among all actions with probability ϵ\epsilon and the action with the highest estimate otherwise, so with two actions and ϵ=0.1\epsilon = 0.1 the current best is chosen with probability 0.950.95.

The upper confidence bound rule UCB1, for rewards in [0,1][0, 1], tries every action once and then picks the action with the largest index

Q(a)+2log⁡tN(a),Q(a) + \sqrt{\frac{2\log t}{N(a)}},

where N(a)N(a) counts the pulls of aa so far and tt is the round. At t=10t = 10, an action with average 0.50.5 from 2 pulls has index about 2.0172.017 and one with average 0.6250.625 from 8 pulls about 1.3841.384, so the less tried action is chosen. With μ∗=max⁡aμa\mu^{*} = \max_a\mu_a, the pseudo-regret after TT rounds is ∑t=1T(μ∗−μAt)\sum_{t=1}^{T}(\mu^{*} - \mu_{A_t}) for the chosen actions AtA_t, which is never negative, and the expected regret is its expectation. The realized shortfall, Tμ∗T\mu^{*} minus the rewards actually collected, also contains reward noise and can be negative.

Lessons Multi-Armed Bandits and Exploration

Markov decision processes and Bellman equations

A Markov decision process has states ss, actions aa, transition probabilities Pss′a=P(s′∣s,a)P^{a}_{ss'} = P(s' \mid s, a), expected rewards r(s,a)r(s, a) and a discount factor γ∈[0,1)\gamma \in [0, 1). The Markov property says that the next state and reward depend on the past only through the current state and action. A policy π(a∣s)\pi(a \mid s) gives the probability of each action in each state. The discounted return from time tt is

Gt=∑k=0∞γkRt+k+1,G_t = \sum_{k=0}^{\infty}\gamma^kR_{t+k+1},

which is finite for bounded rewards and γ<1\gamma < 1. An episodic task may instead stop at a terminal state, after which the return is 0. The value function is Vπ(s)=Eπ[Gt∣St=s]V^{\pi}(s) = E_{\pi}[G_t \mid S_t = s], and the action value Qπ(s,a)Q^{\pi}(s, a) also fixes the first action. They satisfy the Bellman expectation equation

Qπ(s,a)=r(s,a)+γ∑s′Pss′aVπ(s′),\begin{aligned} Q^{\pi}(s, a) &= r(s, a) \\ &+ \gamma\textstyle\sum_{s'}P^{a}_{ss'}V^{\pi}(s'), \end{aligned} Vπ(s)=∑aπ(a∣s)Qπ(s,a),V^{\pi}(s) = \textstyle\sum_{a}\pi(a \mid s)Q^{\pi}(s, a),

and the optimal values satisfy the Bellman optimality equation, the same expression for Q∗Q^{*} with V∗V^{*} in place of VπV^{\pi} and

V∗(s)=max⁡aQ∗(s,a).V^{*}(s) = \max_{a}Q^{*}(s, a) .

For example, take γ=0.5\gamma = 0.5 and a policy under which state C earns reward 5 and moves to C or to L with probability 1/21/2 each, while state L earns −1-1 and moves to C. The values solve V(C)=5+0.5 (0.5 V(C)+0.5 V(L))V(C) = 5 + 0.5\,(0.5\,V(C) + 0.5\,V(L)) and V(L)=−1+0.5 V(C)V(L) = -1 + 0.5\,V(C), so V(C)=7.6V(C) = 7.6 and V(L)=2.8V(L) = 2.8. The reward defines the objective, and maximizing it serves people only as far as it measures what matters to them.

Lessons Markov Decision Processes and Bellman Equations

Temporal-difference learning and Q-learning

Temporal-difference learning updates a value estimate from one transition (St,At,Rt+1,St+1)(S_t, A_t, R_{t+1}, S_{t+1}) without waiting for the end of an episode. TD(0) uses the TD error

δt=Rt+1+γV(St+1)−V(St),V(St)←V(St)+α δt,\begin{aligned} \delta_t &= R_{t+1} + \gamma V(S_{t+1}) \\ &\quad - V(S_t), \\[0.4em] V(S_t) &\leftarrow V(S_t) + \alpha\,\delta_t, \end{aligned}

with a step size α∈(0,1]\alpha \in (0, 1]. Using the current estimate V(St+1)V(S_{t+1}) inside the target is called bootstrapping. Q-learning learns action values for control. After a transition from ss with action aa and reward rr to s′s', it computes

δ=r+γmax⁡a′Q(s′,a′)−Q(s,a),Q(s,a)←Q(s,a)+α δ.\begin{aligned} \delta &= r + \gamma\max_{a'}Q(s', a') \\ &\quad - Q(s, a), \\[0.4em] Q(s, a) &\leftarrow Q(s, a) + \alpha\,\delta . \end{aligned}

Q-learning is off-policy, since its target uses the best next action whatever the behavior policy does next, while SARSA is on-policy and uses the action a′a' actually taken, with Q(s′,a′)Q(s', a') in place of the maximum. At a terminal state the target is just the reward rr, with no continuation value.

With V(dock)=2V(\text{dock}) = 2, V(aisle)=4V(\text{aisle}) = 4, a reward of −1-1 for moving from dock to aisle, γ=0.9\gamma = 0.9 and α=0.25\alpha = 0.25, the TD error is −1+3.6−2=0.6-1 + 3.6 - 2 = 0.6 and the new V(dock)V(\text{dock}) is 2.152.15. A transition into a terminal state with reward 5 from Q=2Q = 2 gives Q=2+0.25 (5−2)=2.75Q = 2 + 0.25\,(5 - 2) = 2.75. In a finite discounted MDP with bounded rewards, tabular Q-learning converges to Q∗Q^{*} with probability 1 when every state-action pair is visited infinitely often and the step sizes of each pair satisfy ∑tαt=∞\sum_t\alpha_t = \infty and ∑tαt2<∞\sum_t\alpha_t^2 < \infty. A constant step size, or a neural network in place of the table, does not carry this guarantee.

Lessons Temporal-Difference Learning and Q-Learning

Responsible Use and Deployment

A model that scores well overall can still fail some groups, mislead the people who use it or break when the data change. Fairness criteria, interpretation methods, shift diagnostics, privacy guarantees and deployment checks each answer a specific question, and none of them replaces judgment about the intended use.

Fairness and subgroup evaluation

A subgroup metric is a metric computed separately for each group gg, the cases with G=gG = g, reported with the group’s counts and uncertainty. The group base rate is P(Y=1∣G=g)P(Y = 1 \mid G = g) and the selection rate is P(Y^=1∣G=g)P(\hat{Y} = 1 \mid G = g).

CriterionCondition
Demographic paritythe same selection rate P(Y^=1∣G=g)P(\hat{Y} = 1 \mid G = g) in every group
Equality of opportunitythe same true positive rate P(Y^=1∣Y=1,G=g)P(\hat{Y} = 1 \mid Y = 1, G = g) in every group
Equalized oddsthe same true positive rate and the same false positive rate P(Y^=1∣Y=0,G=g)P(\hat{Y} = 1 \mid Y = 0, G = g) in every group
Predictive paritythe same precision P(Y=1∣Y^=1,G=g)P(Y = 1 \mid \hat{Y} = 1, G = g) in every group
Calibration within groupsP(Y=1∣S=s,G=g)=sP(Y = 1 \mid S = s, G = g) = s for a score SS, in every group and for every score value ss

These criteria answer different questions and can conflict. For a group with base rate π\pi, true positive rate tt and false positive rate ff,

precision=tπtπ+f(1−π),\text{precision} = \frac{t\pi}{t\pi + f(1 - \pi)},

so equal rates t=0.8t = 0.8 and f=0.2f = 0.2 give precision 0.50.5 at π=0.2\pi = 0.2 and 0.80.8 at π=0.5\pi = 0.5. When base rates differ, a classifier with equal precision below 1 and equal positive true positive rates in two groups must have different false positive rates. Likewise a score that is calibrated within groups cannot also have equal average scores among the actual positives and among the actual negatives of both groups, unless the base rates are equal or the prediction is perfect. Choosing among the criteria is a decision tradeoff about which errors matter to whom, and how the group attribute is recorded and used needs care of its own.

Lessons Fairness and Subgroup Evaluation

Model interpretation and feature importance

Interpretability is how well people can understand what a model does. A global importance describes how much a model relies on a feature across a data set, and a local explanation describes one prediction. Permutation importance is the drop in a score when the values of one feature are shuffled across the rows of an evaluation set, with the model fixed, averaged over several shuffles. Partial dependence of feature jj at the value vv averages the predictions with xjx_j set to vv in every row,

PD⁡j(v)=1n∑i=1nf(v,xi,−j),\operatorname{PD}_j(v) = \frac{1}{n}\sum_{i=1}^{n} f(v, \mathbf{x}_{i,-j}),

where xi,−j\mathbf{x}_{i,-j} holds the other features of row ii. Individual conditional expectation curves draw f(v,xi,−j)f(v, \mathbf{x}_{i,-j}) for each row separately, and their average is the partial dependence. With correlated features both methods evaluate combinations of values that never occur in the data.

SHAP values split a prediction into feature contributions ϕj\phi_j that add up to f(x)−E[f]f(\mathbf{x}) - E[f], the difference from the average prediction over a background distribution. They are Shapley values for the payoff v(S)v(S), the average prediction when the features in SS are fixed at their values in x\mathbf{x} and the others come from the background. For the set FF of all pp features,

ϕj=∑S⊆F∖{j}cS Δj(S),Δj(S)=v(S∪{j})−v(S),cS=∣S∣! (p−∣S∣−1)!p!.\begin{gathered} \phi_j = \sum_{S \subseteq F \setminus \{j\}} c_S\,\Delta_j(S), \\[0.4em] \Delta_j(S) = v(S \cup \{j\}) - v(S), \\[0.4em] c_S = \frac{\lvert S \rvert!\,(p - \lvert S \rvert - 1)!}{p!} . \end{gathered}

For a linear model this gives ϕj=wj(xj−xˉj)\phi_j = w_j(x_j - \bar{x}_j), with xˉj\bar{x}_j the background mean of feature jj. Every one of these explanations describes the model and depends on the evaluation or background data. None of them measures a causal effect in the world.

Lessons Model Interpretation and Feature Importance

Distribution shift and robustness

Distribution shift is a difference between the source distribution PsP_s of the training data and the target distribution PtP_t met in use.

ShiftWhat changesWhat stays the same
Covariate shiftP(x)P(\mathbf{x})P(y∣x)P(y \mid \mathbf{x})
Label shiftP(y)P(y)P(x∣y)P(\mathbf{x} \mid y)
Concept shiftP(y∣x)P(y \mid \mathbf{x})nothing is guaranteed

Under covariate shift with overlapping support, so that Ps(x)>0P_s(\mathbf{x}) > 0 wherever Pt(x)>0P_t(\mathbf{x}) > 0, the target risk equals the source risk reweighted by w(x)=Pt(x)/Ps(x)w(\mathbf{x}) = P_t(\mathbf{x})/P_s(\mathbf{x}). For example, if a feature has two levels with source shares 0.80.8 and 0.20.2, target shares 0.20.2 and 0.80.8, and error rates 0.10.1 and 0.30.3, the risk is 0.140.14 on the source and 0.260.26 on the target, and the weights 0.250.25 and 4 turn the source average into 0.260.26.

A stress test measures performance under a stated change of the inputs, and an out-of-distribution input lies outside the conditions the model was developed for. A feedback loop arises when the model’s decisions change the data it later learns from. Abstention, declining to predict and passing the case on, gives up coverage, the share of cases predicted, and lowers the risk on the cases kept when the declined cases are the riskier ones. An alarm from a shift detector does not prove that the model fails, and the absence of an alarm does not prove that it works.

Lessons Distribution Shift and Robustness

Privacy, data rights and model security

Personal data identify or relate to a person. A careful workflow uses them only for a stated, permitted purpose, collects no more than the task needs, limits retention and controls access. A dataset license states the permitted uses of the data. A model can memorize training examples, and membership inference tries to tell from the model’s outputs whether a particular record was in the training data.

A randomized mechanism MM is (ε,δ)(\varepsilon, \delta) differentially private when, for all datasets DD and D′D' that differ in one person’s record and every set SS of outputs,

P(M(D)∈S)≤eεP(M(D′)∈S)+δ.\begin{aligned} &P(M(D) \in S) \\[0.4em] &\quad \le e^{\varepsilon}P(M(D') \in S) + \delta . \end{aligned}

The privacy budget ε\varepsilon measures the privacy loss, and a smaller value is more private. Under basic composition the budgets of several releases add up, both the ε\varepsilon values and the δ\delta values. The Laplace mechanism adds Laplace noise with scale Δf/ε\Delta f/\varepsilon to a numerical query whose sensitivity Δf\Delta f is the most one record can change it, and it is (ε,0)(\varepsilon, 0) differentially private, so a count, with Δf=1\Delta f = 1, needs scale 2 for ε=0.5\varepsilon = 0.5. Differential privacy is a property of the whole mechanism, and a pipeline is private only with accounting for every release. Data poisoning inserts or alters training data to change the model, and an adversarial input is a small deliberate change of an input that changes the prediction.

Lessons Privacy, Data Rights, and Model Security

Deployment, monitoring and documentation

An inference pipeline packages the fitted preprocessing together with the model, so that new inputs pass through exactly the steps fitted on the training data, which is training-serving consistency. Schema validation checks the columns, types, units and ranges of each incoming record before prediction. Model versioning records the data, code, settings and fitted parameters of every released model, so that a rollback to an earlier version is possible.

Drift monitoring compares the distributions of inputs and predictions with a reference period, and the performance itself can be measured only once outcomes arrive, which for a delayed label can take weeks. A drift alert is a reason to investigate, not proof that performance has fallen. A model card documents the intended use, the training data, the evaluation population, the metrics with their uncertainty, the subgroup results, the limitations and the uses to avoid.

Lessons Deployment, Monitoring, and Model Documentation

Integrated Projects

The course ends with complete projects that apply the whole workflow to one question each. Their claims are limited to the population, the metric and the evaluation that the study protected, and every step that used the data is reported.

Regression project from data to evaluation

A data audit checks units, duplicates, missing values, time stamps and the independent unit before any modeling. A protected test set is split off first, by group or by time when the intended use requires it. A baseline, a regularized linear model and a tree ensemble are compared with the same folds and metric, and the chosen pipeline is refitted on the development data and scored once on the test set.

Residual analysis plots the residuals against the predictions, the features and time. The signed mean error, the mean of the residuals y^−y\hat{y} - y, is negative for systematic underprediction and positive for overprediction. Out-of-range inputs, values outside the training range, are flagged, because a tree’s prediction stops changing beyond its outermost splits while a linear model extrapolates without support.

Lessons Regression Project from Data to Evaluation

Rare-event classification project

Rare-event classification starts with an exact event definition, the positive class and the prediction time, and it reports the prevalence with its count. Resampling, weighting and calibration stay inside the development data, with the calibrator fitted on a calibration sample separate from the training rows. The threshold comes from the review costs and the review capacity, such as the number of cases a team can check per day, and the whole procedure is frozen before the final evaluation. The report gives precision, recall, the expected cost and calibration on the test data with their uncertainty, together with a subgroup audit of the error rates. A small constructed system is not a validated tool for high-stakes use.

Lessons Rare-Event Classification Project

Designing and defending a study

A study protocol fixes the question, the population, the independent unit of analysis, the split, the metric, the baselines and the final comparison before the test data are used. Every feature is checked for post-outcome information, data recorded after the outcome it would predict. Uncertainty is measured by resampling the independent unit. The report states at least one failed alternative and the limitations that remain unresolved. Reproducibility, getting the same result from the same data and code, is different from validity, which asks whether the result answers the question for the intended population. A critical review asks how the data were produced, what could have leaked, and what the final score does and does not show.

Lessons Design and Defend a Machine Learning Study