Part I · Foundations
Chapter 3
Machine Learning
Learning a function from examples — and the art of not fooling yourself.
In one sentenceMachine learning fits a function to data so that it generalizes to examples it has never seen, and most of the craft is about measuring whether it really does.
The idea
What does it mean to learn?
Chapter 1 ended with a turn: instead of writing rules, collect examples and let the machine find the pattern. This chapter makes that precise. Machine learning means choosing a family of functions with adjustable parameters, then using data to pick the parameters that make the function fit — in a way that keeps working on examples it hasn't seen.
Everything depends on where the training signal comes from. With labelled examples, you learn a mapping from inputs to answers (supervised). Without labels, you look for structure (unsupervised). And with only raw data, you can invent labels from the data itself — hide a word and predict it — which is self-supervised learning, the way every LLM is pretrained.
Learning paradigms differ in where the training signal comes from: human-provided labels (supervised), structure in the data alone (unsupervised), or labels manufactured from the data itself (self-supervised).
Open the concept page →
For supervised learning the data is a table you'll recognize from data engineering: rows are examples, columns are features, one column is the label. If the label is a number it's regression; if it's a category, classification.
A supervised learning problem is a table: each row is an example described by features, and the label is what the model must predict — a category (classification) or a number (regression).
Open the concept page →
How it works
Your first models: lines and curves
Every model in this site — up to GPT — follows the same three-part recipe you met in Chapter 2: a model with parameters, a loss that scores it, and an optimizer that lowers the loss. The simplest instance is linear regression: predict a number as a weighted sum of the features, and choose the weights that minimize the squared error.
Linear regression predicts a number as a weighted sum of the features plus a constant, choosing the weights that minimize the average squared error on the training data.
Open the concept page →
Swap the output for a probability — pass the weighted sum through a sigmoid — and swap squared error for cross-entropy, and you have logistic regression, the basic classifier. Train one below and watch the boundary settle; then try the XOR data and watch it fail.
Try it · toy model
Train a linear classifier with gradient descent and watch its decision boundary settle — then see it fail on XOR.
Logistic regression is a linear classifier: it computes a weighted sum of the features and squashes it through a sigmoid to get a probability, trained by minimizing cross-entropy.
Open the concept page →
The central problem
The central problem: generalization
Here is the most important idea in machine learning. A model can always fit its training data better by becoming more flexible — but fitting the training data isn't the goal. Predicting new data is. Move the slider and watch the two errors part ways.
Try it · toy model
Fit curves of increasing complexity to 12 noisy points. Training error keeps falling; error on new data falls, then soars. Then add regularization.
At degree 11, the curve passes exactly through all twelve training points — zero training error — and is wildly wrong everywhere else. That is overfitting: memorizing noise instead of learning the pattern. At degree 0 the model is too simple to capture anything — underfitting. The job is to find the middle, and the only honest way to find it is to measure on data the model never trained on.
The goal of learning is generalization — good performance on data the model has never seen — and a model that memorizes its training data (overfits) or is too simple to capture the pattern (underfits) fails at it.
Open the concept page →
When you can't simplify the model, you can penalize complexity instead. Turn on regularization in the lab at degree 11 and the test error drops back near the best simple model.
Regularization is anything that discourages a model from fitting the training data too closely — most commonly a penalty on large weights — so that it generalizes better.
Open the concept page →
Failure modes
How ML goes wrong
Two failures account for a large share of models that look great in evaluation and disappoint in production — and both are, at heart, data pipeline problems.
Leakage: the training data contains information that won't exist at prediction time — a feature computed from the future, a preprocessing step fitted on the test set, the same customer in both splits. The model learns the leak, not the task.
Data leakage is when training or evaluation data contains information that won't be available when the model is actually used — making results look far better than they really are.
Open the concept page →
Distribution shift: the world the model is deployed into differs from the one it was trained on. A test-set score is a promise only about data like the test set.
Distribution shift is when the data a model meets in use differs from the data it was trained on, so its measured performance no longer applies.
Open the concept page →
Measurement
Measuring a classifier
Accuracy is the obvious metric and often the wrong one. When one class is rare — fraud, disease, spam — a model that always says "no" scores high accuracy while being useless. The fix is to count which kind of mistakes the model makes, and to choose where on the precision–recall trade-off you want to be.
Try it · toy model
Precision, Recall and the Threshold
A fraud detector on imbalanced data: move the threshold and watch precision, recall, the confusion matrix and the ROC curve respond.
Accuracy alone can mislead; precision (how many flagged items were right), recall (how many true items were caught) and the confusion matrix show what kind of mistakes a classifier makes.
Open the concept page →
The toolbox
The classical toolbox
You don't need to memorize algorithms — but you should recognize the main families and what each is good for. Each is a different answer to the same question: what shape of function should the model be allowed to learn?
A decision tree predicts by asking a sequence of yes/no questions about the features; a random forest averages many randomized trees to get a much more accurate and stable model.
Open the concept page →
A support vector machine chooses the separating boundary with the widest possible margin to the nearest points, and with the kernel trick it can draw curved boundaries by implicitly working in a higher-dimensional feature space.
Open the concept page →
Naive Bayes classifies by applying Bayes' theorem with the simplifying ('naive') assumption that features are independent given the class — crude, but fast and often surprisingly effective for text.
Open the concept page →
k-means groups unlabelled points into k clusters by alternating two steps: assign each point to its nearest centre, then move each centre to the mean of its points.
Open the concept page →
PCA finds the few directions along which data varies the most, so high-dimensional data can be summarized, compressed or plotted with little loss.
Open the concept page →
The limit
From hand-crafted features to learned ones
Every model in this chapter learns only the last step: from features to answer. Someone still has to design the features — and for images, audio and text that was years of expert work per domain, the knowledge-acquisition bottleneck from Chapter 1, one level down. The XOR example in the logistic regression lab is this problem in miniature: a linear model fails until someone invents the right feature.
Classical ML learns only the final mapping from features to labels — people design the features — while deep learning learns the features too, directly from raw data.
Open the concept page →
The next step is to learn the features too. That is what neural networks do.
The arc so far
Why it matters
Why it matters
Everything later is this chapter at scale. An LLM is a model with parameters, trained by gradient descent on a loss (cross-entropy) over data, and evaluated on held-out benchmarks. Overfitting, leakage (called contamination for LLMs), distribution shift and misleading metrics are exactly the failure modes you'll meet in Chapter 16.
For your day job, much of this is directly usable. On tabular data — the kind data engineers own — well-featured linear models and tree ensembles remain strong, fast and explainable. Knowing when that's enough is as valuable as knowing how a Transformer works.
Concepts in this chapter
Mark each one as you go. Must-know concepts are the core path.
- Data LeakageData leakage is when training or evaluation data contains information that won't be available when the model is actually used — making results look far better than they really are.Know wellMust know
- Distribution ShiftDistribution shift is when the data a model meets in use differs from the data it was trained on, so its measured performance no longer applies.UnderstandMust know
- Evaluation Metrics for ClassifiersAccuracy alone can mislead; precision (how many flagged items were right), recall (how many true items were caught) and the confusion matrix show what kind of mistakes a classifier makes.Know wellMust know
- Hand-Crafted Features vs Learned FeaturesClassical ML learns only the final mapping from features to labels — people design the features — while deep learning learns the features too, directly from raw data.Know wellMust know
- Features, Labels and TasksA supervised learning problem is a table: each row is an example described by features, and the label is what the model must predict — a category (classification) or a number (regression).Know wellMust know
- Generalization, Overfitting and UnderfittingThe goal of learning is generalization — good performance on data the model has never seen — and a model that memorizes its training data (overfits) or is too simple to capture the pattern (underfits) fails at it.Know wellMust know
- Supervised, Unsupervised and Self-Supervised LearningLearning paradigms differ in where the training signal comes from: human-provided labels (supervised), structure in the data alone (unsupervised), or labels manufactured from the data itself (self-supervised).Know wellMust know
- Linear RegressionLinear regression predicts a number as a weighted sum of the features plus a constant, choosing the weights that minimize the average squared error on the training data.ImplementMust know
- Logistic RegressionLogistic regression is a linear classifier: it computes a weighted sum of the features and squashes it through a sigmoid to get a probability, trained by minimizing cross-entropy.ImplementMust know
- RegularizationRegularization is anything that discourages a model from fitting the training data too closely — most commonly a penalty on large weights — so that it generalizes better.Know wellMust know
- Decision Trees and Random ForestsA decision tree predicts by asking a sequence of yes/no questions about the features; a random forest averages many randomized trees to get a much more accurate and stable model.UnderstandShould know
- k-Means Clusteringk-means groups unlabelled points into k clusters by alternating two steps: assign each point to its nearest centre, then move each centre to the mean of its points.Know wellShould know
- Naive BayesNaive Bayes classifies by applying Bayes' theorem with the simplifying ('naive') assumption that features are independent given the class — crude, but fast and often surprisingly effective for text.UnderstandShould know
- Principal Component Analysis (PCA)PCA finds the few directions along which data varies the most, so high-dimensional data can be summarized, compressed or plotted with little loss.UnderstandShould know
- Support Vector MachinesA support vector machine chooses the separating boundary with the widest possible margin to the nearest points, and with the kernel trick it can draw curved boundaries by implicitly working in a higher-dimensional feature space.UnderstandShould know
What do I actually need to remember?
- ML = a model with parameters + a loss + an optimizer, fitted to data.
- Supervised learns from labels; unsupervised finds structure; self-supervised makes labels from the data (how LLMs are pretrained).
- Linear regression: weighted sum + squared error. Logistic regression: weighted sum → sigmoid + cross-entropy.
- The goal is generalization: performance on data the model has never seen.
- More flexibility always lowers training error; test error falls then rises (underfit → overfit).
- Train to fit, validate to choose, test once to report.
- Regularization (e.g. L2 / weight decay) trades a little fit for better generalization.
- Leakage and distribution shift make offline scores lie — both are usually data-pipeline problems.
- On imbalanced data, accuracy misleads; use precision, recall and the right baseline.
- Classical ML learns only the last step; features were hand-crafted — the bottleneck deep learning removes.
You do not need to memorize everything else. This list is the revision sheet.
Key papers
A few useful things to know about machine learning
Pedro Domingos · 2012 · Communications of the ACM
A short, practical essay on the lessons ML practitioners learn the hard way: generalization is what counts, data beats cleverness, and intuition fails in high dimensions.
- Problem
- The folk knowledge that separates successful ML projects from failed ones was rarely written down.
- What was new
- Twelve compact lessons — overfitting, the curse of dimensionality, feature engineering, more data vs smarter algorithms, and more.
How to read it: The best single reading for Chapter 3. Read it after the chapter; much of it will click.
Leakage in data mining
Shachar Kaufman, Saharon Rosset et al. · 2012 · ACM Transactions on Knowledge Discovery from Data
Named and systematized data leakage — information in training data that won't exist at prediction time — one of the most common ways ML results turn out to be fake.
- Problem
- Models that looked excellent in evaluation failed in deployment because their training data contained hints about the answer.
- What was new
- A formal definition of leakage, a catalogue of real examples, and methods to detect and avoid it.
Support-vector networks
Corinna Cortes, Vladimir Vapnik · 1995 · Machine Learning
Introduced the soft-margin support vector machine, the dominant classifier of the late 1990s and 2000s.
- Problem
- How do you pick, among all boundaries that separate the data, the one most likely to generalize — and handle data that isn't perfectly separable?
- What was new
- Maximize the margin to the nearest points, allow some violations with a penalty, and use kernels to separate data in high-dimensional feature spaces.
Random Forests
Leo Breiman · 2001 · Machine Learning
Random forests — many decision trees trained on random subsets of data and features, then averaged — remain one of the strongest methods for tabular data.
- Problem
- Single decision trees overfit easily and are unstable: small data changes produce very different trees.
- What was new
- Average many decorrelated trees, each grown on a bootstrap sample with a random subset of features at each split.
Regression Shrinkage and Selection Via the Lasso
Robert Tibshirani · 1996 · Journal of the Royal Statistical Society, Series B
Introduced the lasso (L1 regularization), which shrinks weights and sets many exactly to zero — regularization and feature selection at once.
- Problem
- Least-squares regression overfits with many features and produces hard-to-interpret models.
- What was new
- Penalize the sum of absolute weight values; the geometry of this penalty drives many weights to exactly zero.
On lines and planes of closest fit to systems of points in space
Karl Pearson · 1901 · Philosophical Magazine
The origin of principal component analysis: find the directions along which data varies most.
- Problem
- How can many correlated measurements be summarized by a few underlying directions?
- What was new
- Fit the line or plane that minimizes perpendicular distances to the points — what we now call the first principal components.
Least squares quantization in PCM
S. Lloyd · 1982 · IEEE Transactions on Information Theory
The paper behind 'Lloyd's algorithm', the standard iterative procedure for k-means clustering (circulated at Bell Labs in 1957, published 1982).
- Problem
- How should a continuous signal be quantized into a few levels with the least squared error?
- What was new
- Alternate between assigning points to their nearest centre and moving each centre to the mean of its points.
Watch
StatQuest with Josh Starmer
Machine Learning Fundamentals: Bias and Variance
Seven minutes on the most important trade-off in machine learning.
Covers: Bias, variance, overfitting, underfitting.
StatQuest with Josh Starmer
Machine Learning Fundamentals: Cross Validation
Why you never test on your training data, and how to use limited data well.
Covers: Train/test splits, k-fold cross-validation.
StatQuest with Josh Starmer
Linear Regression, Clearly Explained!!!
Least squares, R², and what a fitted line actually tells you — from the ground up.
Covers: Fitting a line, residuals, R², p-values.
StatQuest with Josh Starmer
StatQuest: Logistic Regression
A short, clear picture of how logistic regression turns a line into probabilities.
Covers: The S-shaped curve, classification with probabilities, maximum likelihood.
StatQuest with Josh Starmer
Regularization Part 1: Ridge (L2) Regression
Regularization made concrete: accept a little bias to reduce a lot of variance.
Covers: Ridge penalty, λ, bias–variance, fitting with few data points.
StatQuest with Josh Starmer
ROC and AUC, Clearly Explained!
How to evaluate a classifier across every possible threshold.
Covers: Confusion matrices, true/false positive rates, ROC curves, AUC.
StatQuest with Josh Starmer
Decision and Classification Trees, Clearly Explained!!!
How a tree chooses its questions — the most interpretable model in this chapter.
Covers: Splits, impurity (Gini), leaves, building a tree.
StatQuest with Josh Starmer
StatQuest: Random Forests Part 1 - Building, Using and Evaluating
Why many random trees beat one careful tree.
Covers: Bootstrapping, random feature subsets, voting, out-of-bag error.
StatQuest with Josh Starmer
StatQuest: K-means clustering
The k-means loop, animated.
Covers: Assign, update, repeat; choosing k.
StatQuest with Josh Starmer
StatQuest: Principal Component Analysis (PCA), Step-by-Step
PCA built up geometrically, with no linear algebra assumed beyond the basics.
Covers: Principal components, variance explained, projection.
What came next?
Chapter 4
Hand-designed features limit what a model can learn. Can a model learn the features too?