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 examples and features. The feature vector of example is the column , the design matrix has the rows and size , the targets form the vector , and a prediction is . Vectors are bold lowercase, matrices are capitals and scalars are italic. A linear model has weights and an intercept , and a general parameter vector is . A hat marks an estimate or a fitted value, so estimates the parameter . The transpose is , and and are the Euclidean norm and the sum of the absolute entries.
A loss scores one prediction of the target . The empirical risk of a predictor is its average loss on the training examples, and its population risk is its expected loss on a new example drawn from the data distribution ,
Probabilities are written and , expectations and variances . The letter is a standard deviation, except that applied to a score is the logistic sigmoid and are the singular values of a matrix. The learning rate is , and 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.
| Setting | Data | Goal | Example |
|---|---|---|---|
| Regression | features with a numerical target | predict the number | delivery time in minutes |
| Classification | features with a categorical target | predict the class or its probability | late or on time |
| Unsupervised learning | features only | find groups, directions or unusual cases | groups of similar customers |
| Reinforcement learning | states, actions and rewards that depend on the learner’s own choices | choose actions with a large long-run reward | choosing 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.
| Operation | Code | Result for X of shape (n, p) |
|---|---|---|
| Select rows | X[0:3] | the first three rows, shape (3, p) |
| Column means | X.mean(axis=0) | one mean per feature, shape (p,) |
| Row sums | X.sum(axis=1) | one value per example, shape (n,) |
| Elementwise product | A * B | entry by entry, for arrays of the same shape |
| Matrix product | X @ w | one prediction per row, shape (n,), for w of shape (p,) |
| Broadcasting | X - 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
| Set | Job | Used |
|---|---|---|
| Training set | fits the model parameters, the values learned from data such as weights | for every fit |
| Validation set | compares models and chooses hyperparameters, the settings fixed before fitting such as in nearest neighbors | during development |
| Test set | estimates performance after every choice is frozen | once, 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.
| Leakage | How it happens | Prevention |
|---|---|---|
| Target leakage | a feature recorded after the outcome or computed from it | keep only features known at prediction time |
| Duplicate leakage | the same or a nearly identical record on both sides of a split | remove duplicates before splitting |
| Group leakage | rows of one customer, patient or device on both sides | split by group |
| Temporal leakage | later data used to predict earlier outcomes | split by time |
| Preprocessing leakage | scaling, imputation, encoding or feature selection fitted on all the data | fit 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 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 quantile has a fraction of about 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.
| Mechanism | The probability that a value is missing | Consequence |
|---|---|---|
| Missing completely at random | does not depend on any data, observed or not | the complete cases are a random subset of the rows |
| Missing at random | depends only on observed values | methods that use those observed values can correct for it under this assumption |
| Missing not at random | depends on the unobserved value itself, even given the observed ones | the 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 training rows,
and applies the same and unchanged to validation, test and future rows. The course divides by here, and dividing by is another convention, so record which one a fitted scaler used. A column with 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 have mean 0 and standard deviation 1, and standardizing does not make a distribution normal. Min-max scaling maps to with the training minimum and maximum , and new values can fall outside .
For example, training weights of 2, 4, 6 and 8 kilograms have mean 5 and standard deviation , so a new parcel of 9 kilograms gets . Scaling matters for distances. With weight in kilograms and distance in kilometers, the query has squared distances 5 to and to , while with distance in meters the squared distances become 4,000,001 and 10,009, and becomes the nearer point.
One-hot encoding turns a categorical feature with categories into indicator columns, where column is 1 for an example of category and 0 otherwise. It imposes no order on the categories. Next to an intercept the 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 , k-nearest neighbors finds the training examples with the smallest Euclidean distance
Classification predicts the majority class among those 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 th place and for a tied vote, for example the class of the single nearest neighbor or the smallest class index. The number of neighbors 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 gives a flexible and noisy rule, returns the stored label of any training input that is not repeated, and predicts the training majority class or the training mean everywhere.
For the query and the training points labeled red, labeled blue and labeled blue, the distances are 1, 1 and . With two points of different classes tie, so the answer depends on the tie rule, while 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 in nearest neighbors, a high polynomial degree or a deep tree.
| Pattern | Training error | Validation error | Typical cause |
|---|---|---|---|
| Underfitting | high | high, close to training | the model is too simple for the pattern |
| Good fit | low | low, a little above training | flexibility matches the signal |
| Overfitting | very low | clearly higher than training | the 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 and in is . A linear prediction for one example and for all examples at once is
where is , has entries, is the column of ones and has entries. Entry of the matrix-vector product is , and the product needs exactly as many entries in as has columns. Adding an intercept column of ones gives the augmented design matrix of size and the parameter vector , so that is a single product. The intercept column is a modeling device, not a feature.
For example, with weights of 2 minutes per kilometer and minutes per package and an intercept of 10 minutes, a delivery of 12 kilometers with 4 packages gets minutes.
Lessons Vectors, Matrices, and Linear Predictions
Norms, rank and orthogonal projection
The Euclidean norm is , 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 is the span of its columns, the set of all possible . The columns are linearly independent when only for , and the rank of is the largest number of linearly independent columns, the dimension of the column space.
The orthogonal projection of onto a subspace is the unique vector of the subspace with orthogonal to the whole subspace, and it is the point of the subspace closest to . Onto the span of one nonzero vector ,
For and , both and equal 5, so , and the difference is orthogonal to . The projection is unique even when the coefficients are not. If the column is duplicated, , every with gives the same .
A square matrix is singular when it has no inverse, which happens exactly when its columns are linearly dependent, and is invertible exactly when has full column rank. Conditioning describes near dependence. For with full column rank, the condition number 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 at is
when this limit exists, and is differentiable at when it does. The partial derivative differentiates in with the other coordinates held fixed. The gradient is the column of partial derivatives in the order of the parameter vector, so it has the same shape as . For differentiable , the directional derivative along a unit vector is , a nonzero gradient points in the direction of steepest increase, and for small .
The chain rule says that if and , then , and when affects through several paths the contributions of the paths add. For one example with feature and target , the squared error has
With , , and the prediction misses by , so the partial derivatives are and . The central difference approximates with an error of order for smooth . Agreement between it and a coded derivative is a numerical check, not a proof. Where is not differentiable, as 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
with a learning rate . At a differentiable point with nonzero gradient the negative gradient is a descent direction, so a small enough step lowers , but a large step can raise it. A stationary point has . A local minimum is lowest within a neighborhood and a global minimum is lowest overall.
For the gradient at is , and one step with gives . Each step multiplies the error by , so the iterates converge to 3 exactly when . At they jump between 0 and 6 forever, and at they move farther away at every step. In general, if the gradient is -Lipschitz, which means for all and , a constant step never increases , and for a convex that attains its minimum the values converge to that minimum.
A function is convex when, for all and and every ,
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 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 is the joint probability that and both occur. For , the conditional probability and Bayes’ rule are
with . Here is the prior probability or base rate, is the likelihood of the evidence and is the posterior probability. Events are independent when , and conditionally independent given , with , when . 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
where and . The probability 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 is nondecreasing, with limits 0 and 1. A discrete variable has a probability mass function whose values add to 1, written with summation notation as . A continuous variable has a probability density function with
The integral is the area under the density between and . Every single value has probability 0, and a density can exceed 1, as the uniform density on , which equals 2 there.
| Distribution | Probabilities | Mean | Variance | Conditions |
|---|---|---|---|---|
| Bernoulli | , | |||
| Binomial | for | successes in independent Bernoulli trials with the same | ||
| Normal | density |
With independent trials and , the probability of no success is . About 95 percent of a normal distribution lies within standard deviations of its mean.
Lessons Random Variables and Probability Distributions
Expectation, variance and covariance
The expected value is for a discrete variable and for a continuous one, when the sum or integral converges absolutely. Expectation is linear, , whether or not and are independent. With and , and finite second moments, the variance and the covariance are
Variance is in squared units and . Covariance depends on the units, while the correlation , defined when both variances are positive, has no units and lies in . Zero covariance does not imply independence. If is , 0 or 1 with equal probabilities and , then , although is a function of .
The covariance matrix of a random vector with mean is . It is symmetric and positive semidefinite, with the variances on its diagonal. The conditional expectation is the mean of among cases with , and the law of total expectation says . When is finite, the function of with the smallest expected squared error for predicting is . 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 and finite variance , the sample mean satisfies
and the standard error is estimated by , where . The law of large numbers says that converges to as grows, for iid observations with a finite mean, and it gives no guarantee for a particular finite .
An approximate 95 percent confidence interval for is , justified for large by the central limit theorem. It is only approximate in general, and for independent normal observations the interval with the Student quantile for degrees of freedom in place of is exact. With and the estimated standard error is 2 and the interval is . Coverage describes the procedure, so about 95 percent of the intervals from repeated samples contain , while one computed interval either contains 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 scores a single prediction. The common regression losses are the squared error and the absolute error . 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 , the expected squared error is smallest at when is finite, and the expected absolute error is smallest at any median of when is finite. Given the features, squared loss therefore targets the conditional mean and absolute loss a conditional median. For residuals 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 with at least two distinct values, least squares minimizes and gives
The fitted value is , and the residual is , prediction minus target in the course convention, while some texts use the opposite sign. The residuals satisfy and , and the line passes through . The slope is the difference in fitted value per unit of , 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 , and give , , and , with residuals , and . Extrapolation beyond the observed range of 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 .
Lessons Simple Linear Regression
Multiple linear regression and least squares
With the augmented design matrix of size and , least squares minimizes , and every minimizer solves the normal equations
When has full column rank, which needs , the matrix is invertible and the solution is unique. Without full column rank infinitely many coefficient vectors fit equally well, yet they all give the same fitted vector , the orthogonal projection of onto the column space of . The residual vector is orthogonal to every column of .
A coefficient is a partial effect, the difference in prediction for a one-unit difference in 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 , with orthonormal columns in and an upper triangular , turns the problem into , solved by back substitution when has full column rank. The SVD also handles the rank-deficient case. Forming 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 examples at every step. Stochastic gradient descent replaces it with the average gradient over a mini-batch of examples,
where is the loss on example . 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 updates. A learning-rate schedule lowers over time. With a fixed the iterates keep fluctuating near a minimum, and the classical convergence results for convex objectives use steps with and .
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 ,
so least squares and the penalized methods still apply, even when is a curved function of . Polynomial features give curves, an interaction term lets the effect of one feature depend on another, and indicator variables code categories, with indicators for levels next to an intercept. A spline is a piecewise polynomial joined smoothly at chosen knots, built from local basis functions such as for a knot .
In , a one-unit step in changes by , so the effect of is positive for and negative for . 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 and an unpenalized intercept , the course writes the penalized least-squares objectives as
with regularization strength and mixing weight . At all three are least squares. Ridge shrinks the coefficients smoothly toward zero and has a unique solution for every . With the centered and standardized matrix and the centered target , it is
and 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 be its average product with the centered target. The three solutions are
where the soft-thresholding function is . For and they are about , and, with , . The regularization path plots the fitted coefficients against . Choose and 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 can mean different fits.
Lessons Ridge, Lasso, and Elastic Net
Regression metrics and baselines
For evaluated predictions with errors , prediction minus target,
where is the mean of the evaluation targets. The MAE and RMSE are in target units and the MSE in squared units. The value is undefined when all evaluation targets are equal. Otherwise it is 1 for perfect predictions, 0 when every prediction equals , and negative for predictions worse than that, which can happen on held-out data. The mean absolute percentage error, in percent, needs every and becomes huge near zero targets.
Targets 2, 4, 6 and 8 with predictions 3, 4, 5 and 12 have errors 1, 0, and 4, so the MAE is , the MSE is , the RMSE is about , and the MAPE is about 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 on the evaluation data, with equality only when the constant equals , so a mean baseline fitted on training data usually has a negative on test data.
Lessons Regression Metrics and Baseline Comparisons
Huber loss and quantile prediction
Robust regression limits the pull of large errors. With , the target minus the prediction,
| Loss | Formula | Best constant prediction |
|---|---|---|
| Squared | the mean | |
| Absolute | a median | |
| Huber with | for , otherwise | the mean when is large enough, tending to a median as |
| Pinball at level | for , for | a quantile |
Huber loss is quadratic near zero and linear in the tails, with its slope capped at , so one large error pulls with bounded force. The threshold 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 , an error of size 1 costs and an error of size 6 costs 10.
The pinball loss penalizes underprediction with slope and overprediction with slope , so at underpredicting by 10 costs 9 and overpredicting by 10 costs 1. When is finite its expected value is minimized by a quantile of , so quantile regression, which fits 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 . Logistic regression models as
The sigmoid maps every real score into , and its inverse is the log-odds,
where is the odds. A one-unit increase in with the other features fixed adds to the log-odds and multiplies the odds by the odds ratio , while the change in probability is not constant and is largest near . The decision boundary is the hyperplane where , and other thresholds give parallel hyperplanes. With and per kilometer, at 6 kilometers and at 10 kilometers, and each kilometer multiplies the odds by . 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 is the model probability that , the Bernoulli likelihood of the parameters is
It is a function of for the observed data, not a probability distribution over . Maximum likelihood estimation maximizes it, which is the same as minimizing the negative log likelihood, and dividing that by gives the binary cross-entropy , the average of the per-example losses
For logistic regression the gradient is , and is the mean of . The objective is convex in , and it has no finite minimizer when a hyperplane separates the two classes perfectly. Compute in a numerically stable form instead of exponentiating large scores. For labels 1, 0 and 1 with probabilities , and , the likelihood is and the cross-entropy is , while a positive case given probability alone costs .
Maximum a posteriori estimation maximizes likelihood times a prior distribution on the parameters. With the mean cross-entropy and the penalty , independent priors on the weights correspond to , and independent Laplace priors with scale give the penalty with . For and this gives . 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 classes, while multilabel classification allows several labels at once and usually uses one sigmoid per label. For scores the softmax function gives the class probability vector
whose entries are positive and add to 1. Adding the same constant to every score leaves it unchanged, so implementations subtract first, and the log-sum-exp trick computes . For the true class the multiclass cross-entropy is
Scores 2, 1 and 0 give probabilities of about , and , and a loss of about when the first class is correct. One-vs-rest fits 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 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 turns a score into a decision, positive when the score is at least .
| Predicted positive | Predicted negative | |
|---|---|---|
| Actually positive | true positive, TP | false negative, FN |
| Actually negative | false positive, FP | true negative, TN |
Sensitivity is the true positive rate, also called recall, and the false positive rate is . Each ratio is undefined when its denominator is 0. Raising 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 , a false negative costs and correct decisions cost nothing. If is a calibrated probability, predicting positive has expected cost and predicting negative has , so the expected cost is smallest when the rule predicts positive for
With and the threshold is , not . On a set of cases the total cost of a threshold is , 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
and accuracy, the share of all cases classified correctly. Precision is undefined when nothing is predicted positive, and is undefined only when . When precision and recall are both positive, 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 positives with scores and negatives with scores ,
where is 1, or 0 as positive scores above, equal to or below negative . A constant score has AUC , 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 and against negative scores and earn of 4 pairs, so AUC .
The precision-recall curve plots precision against recall over the thresholds. Average precision, in the noninterpolated form used in the course, is
over the distinct thresholds in decreasing order, with recall , precision and . 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, , while ROC AUC is . 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 is the share of positives. Accuracy can look excellent for a useless rule, since always predicting negative is right for a share of the cases. Precision depends on prevalence. For a fixed true positive rate and false positive rate ,
so at , and precision is only about . As another example, 12 true positives, 8 false negatives, 40 false positives and 940 true negatives give accuracy , below the of always predicting negative, while recall is , specificity about and precision about .
Balanced accuracy is the mean of sensitivity and specificity, about in this example and 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 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 between a minority example and one of its minority neighbors, with uniform on . 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 , the share of positives is , that is for every . 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 cases the Brier score is , 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 , of which 4 are positive, sit at the point of the diagram and have Brier score and log loss about .
Platt scaling fits to a score 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 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, , so the classifier picks the class with the largest log-probability score
and working with logarithms avoids numerical underflow. Normalizing over the classes gives the model’s posterior probabilities. With binary features, as in Bernoulli naive Bayes, Laplace smoothing estimates
when feature is present in of the training examples of class , so a word never seen in a class does not get probability 0. For word counts, multinomial naive Bayes uses the smoothed estimate , where counts word in class , is the total count in that class, is the vocabulary size and . 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 and a positive-definite covariance matrix ,
Positive definiteness makes invertible and the density well defined. The classifier picks the class with the largest , where is the class prior. Linear discriminant analysis (LDA) assumes one shared covariance matrix for all classes, which makes the boundaries between classes linear in , 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 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 and , the boundary is at 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 and write a new outcome as , with and . Let be the prediction of a model trained on a random training set, independent of the new , and let . With finite second moments, the expected squared prediction error at is
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 and are unknown.
For example, if , the noise is or 2 with equal probability, and the fitted prediction is 7, 9, 9 or 11 with equal probability, then , the squared bias is 1, the variance is 2 and the noise variance is 4. Averaging 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 folds, fits the whole procedure on folds and scores the held-out fold, times. The estimate is the average of the fold scores, or the score of all out-of-fold predictions pooled, and for an average such as the MSE the two agree when the folds have equal sizes.
| Folds | Rule | Use |
|---|---|---|
| Ordinary | rows assigned to folds at random | independent, exchangeable rows |
| Stratified | every fold keeps the class proportions | classification, especially with rare classes |
| Grouped | all rows of a group in the same fold | repeated customers, patients or devices |
| Temporal | train on earlier periods and score the next one | forecasting 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 , 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.
| Pattern | Reading | What may help |
|---|---|---|
| Both errors high and close together | underfitting | a 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 data | high variance | more 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 cases with replacement from the 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 and 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 , about for and close to for large .
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 on training data, freezes it, and computes the conformity scores on calibration cases. For a miscoverage level , let
take as the th smallest score when and when , and report the closed interval from to . If the calibration cases and the new case are exchangeable, then
This is marginal coverage, an average over calibration sets and new cases, and it does not promise coverage at every or in every subgroup. Scores 1, 1, 1, 2, 2, 2, 3, 4 and 5 with give and , while gives 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 , iid examples and a loss with values in , Hoeffding’s inequality gives, for every ,
For a finite hypothesis class fixed before the data are seen, the union bound adds these probabilities over the members of . Setting the total to shows that, with probability at least , every satisfies with
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 , and the bound is about , and with it is about . It grows with the capacity of the class, shrinks like and is often loose. It does not apply with a parameter count in place of , 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 , where comes from regressing on the other features, is the factor by which collinearity multiplies the variance of coefficient , so 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.
- 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.
- Split off a test set that matches the intended use, and work only with the remaining development data.
- Build baselines and candidate pipelines, with every learned step inside the folds.
- Tune on validation data or by cross-validation, then refit the selected pipeline on all development data.
- 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.
- 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 , a linear classifier predicts when and otherwise. The separating hyperplane has normal vector , and scaling and by the same positive number leaves it unchanged. The data are linearly separable when some gives for every example.
The perceptron passes through the data repeatedly, and whenever it updates
with , stopping after a full pass without updates. The perceptron convergence theorem says that if, for the augmented vectors , some unit vector separates the data with margin and every augmented vector has norm at most , then starting from zero the perceptron makes at most updates. Without separability it never stops by itself, so a limit on the number of passes is needed.
Starting from and with , the examples labeled , labeled , labeled and labeled cause two updates in the first pass, to , and then , , 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 and the score , the functional margin of example is and its geometric margin is , the signed distance to the boundary. Requiring functional margins of at least 1 gives a margin band of width , so maximizing the margin means minimizing . The soft-margin support vector machine of the course minimizes
with and an unpenalized intercept. The hinge loss 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 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 with the average hinge loss, so convert before comparing values, and scale the features on training data first.
For inputs , , 1 and 2 with labels , , and , the hard-margin solution , has objective . With the optimum is , with the two inner points inside the margin and objective , and with the optimum is again .
Lessons Support Vector Machines and Soft Margins
Kernel methods
A feature map sends into a feature space, and a kernel function computes the inner product without forming . The kernel trick replaces every inner product of an algorithm by , as in the kernel SVM, whose decision function is
with dual weights that are nonzero only for the support vectors. A function is a valid, positive semidefinite kernel when every Gram matrix with entries is symmetric and positive semidefinite, which holds exactly when is an inner product in some feature space.
| Kernel | Parameters | |
|---|---|---|
| Linear | none | |
| Polynomial | and a whole number | |
| Radial basis function |
In the kernel equals for , and at and both sides equal 25. A large makes the radial basis function kernel very local and the boundary very flexible. Choose and 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 , and each leaf predicts the class proportions of the training rows that reach it, its leaf probabilities, or their majority class. For class proportions in a node,
with . Both are 0 for a pure node, and for two classes both peak at equal proportions, at and at 1 bit. A split that sends of a node’s rows left and right has weighted child impurity , where and 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 . A split into children with counts and leaves weighted Gini , a reduction of . A split into a pure and a leaves , a reduction of , so it is better, and entropy agrees, with gains of about and 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 , 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 by
where is the number of leaves and , so a larger favors smaller trees. A single leaf with SSE 100 and a two-leaf tree with SSE 4 tie at . Each gives a pruned tree built from training data, and itself is chosen by validation error or cross-validation, never by the test set. Software that averages the squared errors reports a differently scaled .
Lessons Regression Trees and Pruning
Bagging and random forests
Bagging fits the same learner to bootstrap samples, each drawn with replacement from the 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 predictions at a point each have variance and every pair has correlation , their average has
so more trees shrink the second term but not . With and , gives and gives , approaching the floor .
A given row is left out of a bootstrap sample with probability , about for large , 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
where each weak learner , often a small tree, is fitted to the negative gradient of the loss at the current predictions , and the shrinkage or learning rate is . For the negative gradient is , the target minus the current prediction, so the familiar residual fitting is the squared-error special case. For log loss with a logit score it is , the label minus the current probability.
For targets 1, 3, 7 and 9 at , the starting constant is and the negative gradients are , , 2 and 4. A stump split at predicts their means and 3, and with the new predictions are , , and , which lowers the training MSE from 10 to . The number of stages, 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 , gives a weak classifier with weighted error the vote
multiplies each case weight by , renormalizes the weights to sum to 1, and predicts . After the update the misclassified cases carry exactly half of the total weight. At the vote is , 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
| Measure | Formula | Notes |
|---|---|---|
| Euclidean distance | depends on the scale of every feature | |
| Manhattan distance | the sum of absolute differences | |
| Weighted Euclidean distance | weights set how much each feature counts | |
| Cosine similarity | needs nonzero vectors and ignores their lengths |
Cosine similarity is 1 for vectors that point the same way, so and have cosine similarity 1 and Euclidean distance . 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 coordinates are independent and uniform on , the squared distance has mean and standard deviation , so its spread relative to its mean shrinks like , 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 points into clusters with centroids , the cluster means, to minimize the within-cluster sum of squares
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 , 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 reduces the risk of a poor optimum.
For the corners , , and with , starting centroids and end with the left and right pairs and , while starting centroids and stop at the bottom and top pairs with . The best achievable never increases as grows, so the number of clusters cannot be chosen by 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.
| Linkage | Distance between clusters and |
|---|---|
| Single | the smallest distance between a point of and a point of |
| Complete | the largest such distance |
| Average | the mean of all such distances |
| Ward’s criterion | the increase in the within-cluster sum of squares, |
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 and a count min_samples. The epsilon neighborhood of a point holds every data point within distance of it, the point itself included under the course convention.
| Point type | Definition |
|---|---|
| Core point | at least min_samples points in its epsilon neighborhood |
| Border point | not a core point, but inside the epsilon neighborhood of a core point |
| Noise point | neither 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 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, , , , 3, , and 6, with and min_samples equal to 3, the core points are , and , the clusters are and , and 6 is noise. DBSCAN needs no number of clusters, but its result depends on , min_samples and the feature scaling.
Lessons Density-Based Clustering with DBSCAN
Gaussian mixtures and expectation-maximization
A Gaussian mixture model has the density
with mixing weights that add to 1. A latent variable records which component generated , and the responsibility
is the posterior probability , a soft assignment of point to component . 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 and sets
using the new in . 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 is needed. With observations , , 2 and 3, equal weights, means and 2 and unit variances, the first component takes responsibility about for and about 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 matrix and , the sample covariance matrix is
which is symmetric and positive semidefinite. A unit vector gives the projected scores , whose sample variance is . The principal directions are orthonormal eigenvectors of , with and eigenvalues . The first direction maximizes over unit vectors, with maximum , 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 , and center to , and . Their covariance matrix has every entry equal to 1, its eigenvalues are 2 and 0, and the first principal direction is .
Lessons Covariance, Eigenvectors, and PCA
PCA with the SVD and reconstruction
The thin singular value decomposition of the centered matrix is , where, with , the matrices of size and of size have orthonormal columns and is diagonal with the singular values . The columns of are the principal directions, the principal component scores are , and the covariance eigenvalues are
The explained variance ratio of component is , defined when is not zero. Keeping the first components gives the low-rank reconstruction , the best approximation of rank in total squared error, and its reconstruction error, the sum of all squared entries of , is
Adding the mean back returns the reconstruction to the original units. The centered points , , and have singular values 4 and 2, so the first component explains 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 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 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 , so new readings of 8 and 14 score about and . 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 ,
where has one row per unit of layer and one column per unit of layer , and the activation function acts on each entry. This is forward propagation. A hidden layer uses a nonlinear activation such as , 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 , first-layer rows and , biases , ReLU, output weights and output bias 1, the hidden pre-activations are , the activations and the output . Hidden ReLU units can represent XOR, which no linear classifier can. With and , the output is 0, 1, 1 and 0 on , , and .
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 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 ,
where 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 . 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 on a small case, where is the th 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 for ReLU layers (He initialization) or (Glorot or Xavier initialization), where and 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 for the gradient and updates by . Adam keeps two moving averages and corrects their start at zero,
with the square, the root and the division taken entry by entry, commonly , and a small , and with both averages starting at 0. At the first step with gradient 2, the averages and are corrected to 2 and 4, and with the step has size about . Adam does not guarantee convergence or better generalization.
Batch normalization standardizes each feature over the mini-batch during training, with the batch mean and variance , 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 to the mean data loss gives the gradient descent update
where is the gradient of the data loss, usually with the biases left unpenalized. With , , and the new weight is , against 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 during training. Inverted dropout divides the kept activations by the keep probability , so each activation keeps its expected value, and dropout is switched off at evaluation. With a kept activation of 2 becomes . 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 of an image with a filter , without flipping the filter,
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 , padding on each side, filter side and stride , the output side is
so a input with , and gives a map. A layer with input channels and filters of size has parameters, including one bias per filter, which is 168 for , and .
The receptive field of an output is the input region that can affect it, and two stacked layers with stride 1 see a 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 that maps an input to a latent representation and a decoder that maps it back, and it is trained to minimize a reconstruction loss such as . 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 reconstructs, at its optimum, through the same -dimensional subspace as PCA with 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 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 for the positive, for each negative and a temperature , a common loss is
With , two negatives at 0 and the loss is . Representation collapse, every input mapped to nearly the same embedding, makes all similarities equal, which gives the larger loss 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 in which counts term in document . 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 is the number of the training documents that contain term , and
often followed by dividing each row by its Euclidean norm when that norm is positive. With documents, terms that occur in 3, 2 and 1 of them get idf weights of about , and . 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 by , with the smoothed word probabilities 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 and updates a hidden state with the same parameters at every step,
where, for inputs with entries and a state with entries, is and is . A prediction at step comes from an output layer applied to , 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 can make gradients vanish or explode. With scalar weights 1 and , zero bias and , the inputs 1, 0 and give the states about , and .
A long short-term memory network adds a cell state , where the forget gate and the input gate are sigmoid outputs between 0 and 1 and is a candidate update, and an output gate gives . 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 , keys and values and returns an matrix,
with the softmax applied to each row of scores. Row of the attention weights is a probability vector over the keys, and output row 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 , and dividing by brings it back to 1.
An attention mask sets disallowed scores to before the softmax. A causal mask lets position attend only to positions 1 to , 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 and . 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 of token vectors, one row per position and columns, and adds two sublayers to a residual connection. In the pre-normalization arrangement,
where MHA is multi-head self-attention and FFN applies the same small two-layer network to each position. Layer normalization standardizes the features of each position with that position’s own mean and variance, , 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 , so a sequence supplies the training pairs of each prefix with its next token . 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
and is trained by maximum likelihood. A latent-variable model draws from a prior and then from , so that . A variational autoencoder trains an encoder together with the decoder by maximizing the evidence lower bound
where the expectation is over drawn from . For distributions and on the same states, the Kullback-Leibler divergence , summed over the states with , is never negative and is 0 when the two agree. The gap equals , 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 with item as , with the user vectors as rows of and the item vectors as rows of , and fits them on the set of observed pairs by minimizing
where 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 , precision at is the number of relevant items among the top divided by , and recall at divides the same number by all relevant items for that user. Normalized discounted cumulative gain uses the graded relevance of the item at rank ,
where 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 . A list with relevance 1, 0 and 1 in its top three, out of 4 relevant items in all, has precision at 3 of and recall at 3 of . 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 is ordered in time. A forecast made at the forecast origin for the forecast horizon is written , and it may use only information available at time . A lag feature is an earlier value such as or , and any rolling summary must end at or before the origin. Seasonality is a pattern that repeats with a period . The naive forecast repeats the last value, , and the seasonal-naive forecast repeats the value from the same point of the last observed season,
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 with fixed unknown mean rewards . 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 th reward it is updated incrementally by
where is the average of the first 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 and the action with the highest estimate otherwise, so with two actions and the current best is chosen with probability .
The upper confidence bound rule UCB1, for rewards in , tries every action once and then picks the action with the largest index
where counts the pulls of so far and is the round. At , an action with average from 2 pulls has index about and one with average from 8 pulls about , so the less tried action is chosen. With , the pseudo-regret after rounds is for the chosen actions , which is never negative, and the expected regret is its expectation. The realized shortfall, 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 , actions , transition probabilities , expected rewards and a discount factor . The Markov property says that the next state and reward depend on the past only through the current state and action. A policy gives the probability of each action in each state. The discounted return from time is
which is finite for bounded rewards and . An episodic task may instead stop at a terminal state, after which the return is 0. The value function is , and the action value also fixes the first action. They satisfy the Bellman expectation equation
and the optimal values satisfy the Bellman optimality equation, the same expression for with in place of and
For example, take and a policy under which state C earns reward 5 and moves to C or to L with probability each, while state L earns and moves to C. The values solve and , so and . 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 without waiting for the end of an episode. TD(0) uses the TD error
with a step size . Using the current estimate inside the target is called bootstrapping. Q-learning learns action values for control. After a transition from with action and reward to , it computes
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 actually taken, with in place of the maximum. At a terminal state the target is just the reward , with no continuation value.
With , , a reward of for moving from dock to aisle, and , the TD error is and the new is . A transition into a terminal state with reward 5 from gives . In a finite discounted MDP with bounded rewards, tabular Q-learning converges to with probability 1 when every state-action pair is visited infinitely often and the step sizes of each pair satisfy and . 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 , the cases with , reported with the group’s counts and uncertainty. The group base rate is and the selection rate is .
| Criterion | Condition |
|---|---|
| Demographic parity | the same selection rate in every group |
| Equality of opportunity | the same true positive rate in every group |
| Equalized odds | the same true positive rate and the same false positive rate in every group |
| Predictive parity | the same precision in every group |
| Calibration within groups | for a score , in every group and for every score value |
These criteria answer different questions and can conflict. For a group with base rate , true positive rate and false positive rate ,
so equal rates and give precision at and at . 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 at the value averages the predictions with set to in every row,
where holds the other features of row . Individual conditional expectation curves draw 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 that add up to , the difference from the average prediction over a background distribution. They are Shapley values for the payoff , the average prediction when the features in are fixed at their values in and the others come from the background. For the set of all features,
For a linear model this gives , with the background mean of feature . 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 of the training data and the target distribution met in use.
| Shift | What changes | What stays the same |
|---|---|---|
| Covariate shift | ||
| Label shift | ||
| Concept shift | nothing is guaranteed |
Under covariate shift with overlapping support, so that wherever , the target risk equals the source risk reweighted by . For example, if a feature has two levels with source shares and , target shares and , and error rates and , the risk is on the source and on the target, and the weights and 4 turn the source average into .
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 is differentially private when, for all datasets and that differ in one person’s record and every set of outputs,
The privacy budget measures the privacy loss, and a smaller value is more private. Under basic composition the budgets of several releases add up, both the values and the values. The Laplace mechanism adds Laplace noise with scale to a numerical query whose sensitivity is the most one record can change it, and it is differentially private, so a count, with , needs scale 2 for . 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 , 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.