Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 8: Supervised Learning

Open in Colab

In God we trust. All others must bring data.

W. Edwards Deming

8.1 From Rules to Data

Chapters 2 to 5 built deductive systems: a person writes the knowledge (a search problem, a set of rules, a knowledge base) and the program reasons from it. That works when the rules are known. It fails when nobody can write them down: what exact rule tells a cat photo from a dog photo, or a fraudulent payment from a normal one?

Machine learning is the inductive route. Instead of rules, we give the program examples, and it finds a rule that fits them, a rule we hope will also work on examples it has never seen.

Deductive AI (Ch. 2–5)Inductive AI (Parts II–III)
InputRules, facts, a model of the problemExamples (data)
OutputConclusions that follow for certainA rule (model) that is probably right
StrengthExact, explainableFinds patterns no one wrote down
WeaknessSomeone must write the rulesNeeds data; can be wrong; harder to explain

Three kinds of learning

  • Supervised learning (this chapter): every example comes with the right answer, its label. Learn to predict the label of new examples.

  • Unsupervised learning (Chapter 13): no labels. Find structure, such as groups or a compact description.

  • Reinforcement learning (Chapter 14): an agent acts, receives rewards, and learns which actions pay off.

The supervised setting

We are given a training set of nn examples:

D={(x1,y1),(x2,y2),…,(xn,yn)}\mathcal{D} = \{(\mathbf{x}_1, y_1), (\mathbf{x}_2, y_2), \dots, (\mathbf{x}_n, y_n)\}
  • xi∈Rd\mathbf{x}_i \in \mathbb{R}^d is the feature vector of example ii (for a house: area, rooms, age…).

  • yiy_i is its label: a class in classification (spam / not spam), a number in regression (a price).

We want a function hh, the hypothesis or model, with h(x)≈yh(\mathbf{x}) \approx y, not only on the training set but on new data drawn from the same source. That ability is called generalisation, and it is the whole point.

8.2 The Learning Problem

Loss and risk

A loss function ℓ(h(x),y)\ell(h(\mathbf{x}), y) says how bad one prediction is:

TaskLossFormula
Regressionsquared error(h(x)−y)2(h(\mathbf{x}) - y)^2
Classification0–1 loss1 if h(x)≠yh(\mathbf{x}) \ne y, else 0
Probabilistic classificationcross-entropy (log loss)−log⁡ph(y∣x)-\log p_h(y \mid \mathbf{x})

Learning picks the model with the smallest average loss on the training set, the empirical risk:

R^(h)=1n∑i=1nℓ(h(xi),yi)\hat{R}(h) = \frac{1}{n}\sum_{i=1}^{n} \ell(h(\mathbf{x}_i), y_i)

But what we really care about is the expected loss on new data. The gap between the two is where things go wrong.

Overfitting and underfitting

  • Underfitting: the model is too simple to capture the pattern. It is poor on the training data and on new data.

  • Overfitting: the model is so flexible that it memorises the training data, noise included. It is excellent on the training data and poor on new data.

The figure below fits polynomials of degree 1, 4 and 15 to the same 15 noisy points taken from a sine curve.

Source
/tmp/ipykernel_2420854/1187566595.py:11: RankWarning: Polyfit may be poorly conditioned
  coef = np.polyfit(x, y, deg)
<Figure size 1200x320 with 3 Axes>

The bias–variance trade-off

For squared error, the expected error of a model on a new point splits into three parts:

E[(h(x)−y)2]=Bias2⏟wrong assumptions+Variance⏟sensitivity to the sample+σ2⏟noise\mathbb{E}\big[(h(\mathbf{x}) - y)^2\big] = \underbrace{\text{Bias}^2}_{\text{wrong assumptions}} + \underbrace{\text{Variance}}_{\text{sensitivity to the sample}} + \underbrace{\sigma^2}_{\text{noise}}
  • High bias (underfitting): a straight line for a curved pattern. More data does not help.

  • High variance (overfitting): a degree-15 polynomial changes wildly if a single training point moves. More data, or a simpler model, helps.

  • The noise σ2\sigma^2 cannot be removed by any model.

As a model gets more flexible, bias falls and variance rises; the best model sits in between.

Training, validation and test sets

To measure generalisation honestly, we must judge the model on data it has never seen:

  1. Training set (about 60–70%): fit the model’s parameters.

  2. Validation set (about 15–20%): compare models and choose hyperparameters (the degree of a polynomial, the depth of a tree, kk in k-NN).

  3. Test set (about 15–20%): one final, unbiased estimate of performance. Use it once, at the very end.

When data are scarce, k-fold cross-validation (Section 8.9) replaces the single validation set.

8.3 Linear Regression

The model

Linear regression predicts a number as a weighted sum of the features:

hw(x)=w0+w1x1+⋯+wdxd=w⊤xh_{\mathbf{w}}(\mathbf{x}) = w_0 + w_1 x_1 + \dots + w_d x_d = \mathbf{w}^\top \mathbf{x}

where we add a constant feature x0=1x_0 = 1 so that w0w_0 (the bias or intercept) fits in the same vector.

We choose w\mathbf{w} to minimise the mean squared error (MSE):

J(w)=1n∑i=1n(w⊤xi−yi)2=1n∥Xw−y∥2J(\mathbf{w}) = \frac{1}{n}\sum_{i=1}^{n}\big(\mathbf{w}^\top \mathbf{x}_i - y_i\big)^2 = \frac{1}{n}\lVert X\mathbf{w} - \mathbf{y}\rVert^2

where XX is the n×(d+1)n \times (d+1) matrix whose rows are the examples.

Solution 1: the normal equation

Setting the gradient to zero gives a closed-form answer:

∇J=2nX⊤(Xw−y)=0⟹w∗=(X⊤X)−1X⊤y\nabla J = \frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y}) = 0 \quad\Longrightarrow\quad \mathbf{w}^* = (X^\top X)^{-1} X^\top \mathbf{y}

The normal equation costs about O(d3)O(d^3) to invert X⊤XX^\top X: fine for tens or hundreds of features, too slow for millions.

Solution 2: gradient descent

Gradient descent starts from any w\mathbf{w} and repeatedly takes a small step downhill:

w←w−η ∇J(w)=w−η⋅2nX⊤(Xw−y)\mathbf{w} \leftarrow \mathbf{w} - \eta\, \nabla J(\mathbf{w}) = \mathbf{w} - \eta \cdot \frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y})

The learning rate η\eta sets the step size:

  • too small: training crawls;

  • too large: the steps overshoot and the loss explodes;

  • just right: the loss falls quickly and settles.

Variants used everywhere in Chapters 15 and 18:

  • Batch gradient descent uses all nn examples per step.

  • Stochastic gradient descent (SGD) uses one random example per step: noisy but cheap.

  • Mini-batch gradient descent uses, say, 32 examples: the usual compromise.

Source
<Figure size 1100x340 with 2 Axes>

Feature scaling

Gradient descent is slow when features have very different ranges (an area in m² next to a number of rooms): the loss surface becomes a long, narrow valley. Standardise each feature first:

xj←xj−μjσjx_j \leftarrow \frac{x_j - \mu_j}{\sigma_j}

using the mean and standard deviation of the training set only (computing them on all the data is a form of leakage).

Nonlinear patterns with linear models

A linear model can fit curves if we give it nonlinear features: with x,x2,x3x, x^2, x^3 as features, w0+w1x+w2x2+w3x3w_0 + w_1 x + w_2 x^2 + w_3 x^3 is still linear in the weights, so everything above still applies. This is polynomial regression, and it is exactly what overfitted in Section 8.2.

Regularisation

Regularisation fights overfitting by penalising large weights:

MethodObjectiveEffect
Ridge (L2)J(w)+λ∑jwj2J(\mathbf{w}) + \lambda \sum_j w_j^2shrinks all weights smoothly
Lasso (L1)J(w)+λ∑j∣wj∣J(\mathbf{w}) + \lambda \sum_j \lvert w_j \rvertsets some weights exactly to 0: selects features

The strength λ\lambda is a hyperparameter, chosen on the validation set. Ridge also has a closed form: w∗=(X⊤X+λI)−1X⊤y\mathbf{w}^* = (X^\top X + \lambda I)^{-1}X^\top \mathbf{y}.

8.4 Logistic Regression

Despite its name, logistic regression is a classifier. For two classes (y∈{0,1}y \in \{0, 1\}), it computes a linear score and squashes it into a probability with the sigmoid function:

p(y=1∣x)=σ(w⊤x)=11+e−w⊤xp(y = 1 \mid \mathbf{x}) = \sigma(\mathbf{w}^\top \mathbf{x}) = \frac{1}{1 + e^{-\mathbf{w}^\top \mathbf{x}}}
  • A score of 0 gives probability 0.5; large positive scores approach 1, large negative scores approach 0.

  • Predict class 1 when the probability exceeds 0.5, that is when w⊤x>0\mathbf{w}^\top\mathbf{x} > 0: the decision boundary w⊤x=0\mathbf{w}^\top\mathbf{x} = 0 is a straight line (a hyperplane).

Training with cross-entropy

The squared error is a poor loss for probabilities. Logistic regression minimises the cross-entropy (log loss):

J(w)=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)],pi=σ(w⊤xi)J(\mathbf{w}) = -\frac{1}{n}\sum_{i=1}^{n}\Big[y_i \log p_i + (1 - y_i)\log(1 - p_i)\Big], \qquad p_i = \sigma(\mathbf{w}^\top\mathbf{x}_i)

It punishes confident mistakes hard: predicting p=0.01p = 0.01 for a true 1 costs −log⁡0.01≈4.6-\log 0.01 \approx 4.6. Its gradient has the same simple form as linear regression’s:

∇J=1nX⊤(p−y)\nabla J = \frac{1}{n} X^\top (\mathbf{p} - \mathbf{y})

There is no closed form, so we use gradient descent.

More than two classes: softmax

With KK classes, keep one weight vector per class and turn the KK scores into probabilities with the softmax:

p(y=k∣x)=ewk⊤x∑j=1Kewj⊤xp(y = k \mid \mathbf{x}) = \frac{e^{\mathbf{w}_k^\top \mathbf{x}}}{\sum_{j=1}^{K} e^{\mathbf{w}_j^\top \mathbf{x}}}

The same idea, a linear score followed by softmax and cross-entropy, is the last layer of almost every neural network classifier (Chapter 15).

8.5 Decision Trees

A decision tree classifies by asking a sequence of questions about the features, each answer leading down one branch, until a leaf gives the class. Trees are easy to read, need no feature scaling, and handle categorical and numeric features alike.

  • Internal node: a test on one feature (Outlook = ?, or Age ≤ 30).

  • Branch: one outcome of the test.

  • Leaf: a predicted class (the majority class of the training examples that reach it).

Choosing a good question: entropy and information gain

A good test splits the examples into groups that are as pure as possible. Entropy measures the impurity of a set SS in which class jj has proportion pjp_j:

H(S)=−∑jpjlog⁡2pjH(S) = -\sum_{j} p_j \log_2 p_j
  • A pure set (all one class) has H=0H = 0.

  • A 50/50 set of two classes has H=1H = 1 bit, the maximum for two classes.

The information gain of splitting SS on attribute AA is the drop in entropy:

Gain(S,A)=H(S)−∑v∈values(A)∣Sv∣∣S∣H(Sv)\text{Gain}(S, A) = H(S) - \sum_{v \in \text{values}(A)} \frac{\lvert S_v\rvert}{\lvert S\rvert} H(S_v)

Worked example: should we play tennis?

The classic 14-day dataset (9 Yes, 5 No):

DayOutlookTemp.HumidityWindPlay
1SunnyHotHighWeakNo
2SunnyHotHighStrongNo
3OvercastHotHighWeakYes
4RainMildHighWeakYes
5RainCoolNormalWeakYes
6RainCoolNormalStrongNo
7OvercastCoolNormalStrongYes
8SunnyMildHighWeakNo
9SunnyCoolNormalWeakYes
10RainMildNormalWeakYes
11SunnyMildNormalStrongYes
12OvercastMildHighStrongYes
13OvercastHotNormalWeakYes
14RainMildHighStrongNo

Step 1. H(S)=−914log⁡2914−514log⁡2514=0.940H(S) = -\tfrac{9}{14}\log_2\tfrac{9}{14} - \tfrac{5}{14}\log_2\tfrac{5}{14} = 0.940 bits.

Step 2. Split on Outlook: Sunny (2 Yes, 3 No, H=0.971H = 0.971), Overcast (4 Yes, H=0H = 0), Rain (3 Yes, 2 No, H=0.971H = 0.971):

Gain(S,Outlook)=0.940−514(0.971)−414(0)−514(0.971)=0.247\text{Gain}(S, \text{Outlook}) = 0.940 - \tfrac{5}{14}(0.971) - \tfrac{4}{14}(0) - \tfrac{5}{14}(0.971) = 0.247

Step 3. The same computation for the others gives Humidity 0.152, Wind 0.048, Temperature 0.029. Outlook wins and becomes the root.

Step 4. Recurse. Overcast is pure: a Yes leaf. Among the 5 Sunny days, Humidity splits perfectly (gain 0.971); among the 5 Rain days, Wind does (gain 0.971). The final tree:

Gini impurity

CART, the algorithm behind scikit-learn’s trees, uses the Gini impurity instead of entropy:

Gini(S)=1−∑jpj2\text{Gini}(S) = 1 - \sum_j p_j^2

For the tennis data, Gini(S)=1−(9/14)2−(5/14)2=0.459\text{Gini}(S) = 1 - (9/14)^2 - (5/14)^2 = 0.459. Gini and entropy almost always choose the same split; Gini is a little cheaper to compute.

Three classic algorithms

ID3C4.5CART
Split criterioninformation gaingain ratioGini (classification), MSE (regression)
Numeric featuresnoyes (thresholds)yes (thresholds)
Tree shapemultiwaymultiwaybinary
Pruningnoyesyes (cost-complexity)

Information gain favours attributes with many values (a Day attribute with 14 values would split perfectly and generalise not at all). C4.5’s gain ratio divides the gain by the split information −∑v∣Sv∣∣S∣log⁡2∣Sv∣∣S∣-\sum_v \frac{|S_v|}{|S|}\log_2\frac{|S_v|}{|S|} to correct that bias.

Numeric features are split with a threshold: sort the values, try the midpoints between consecutive values whose classes differ, and keep the threshold with the best gain.

Overfitting and pruning

A tree grown until every leaf is pure fits the training set perfectly, noise included. Two cures:

  • Pre-pruning (stop early): a maximum depth, a minimum number of examples per leaf, a minimum gain.

  • Post-pruning (grow, then cut): replace a subtree by a leaf whenever that does not hurt accuracy on the validation set (reduced-error pruning), or penalise the number of leaves (cost-complexity pruning, CART’s ccp_alpha).

8.6 Ensembles: Many Models Are Better Than One

Single deep trees have high variance: change a few training examples and the tree can change completely. Ensembles combine many models so that their individual errors cancel out.

Bagging and random forests

Bagging (bootstrap aggregating):

  1. Draw BB bootstrap samples: nn examples drawn with replacement from the training set (each sample leaves out about 37% of the examples).

  2. Train one tree on each sample.

  3. Predict by majority vote (classification) or average (regression).

A random forest adds one more source of randomness: at each split, a tree may only choose among a random subset of mm features (often m=dm = \sqrt{d}). The trees become less correlated, and averaging uncorrelated errors cancels them better.

Random forests are one of the best “default” models for tabular data: accurate, robust, little tuning. As a bonus, the left-out examples of each tree give a free validation estimate, the out-of-bag error, and the forest reports feature importances.

Boosting

Boosting builds models in sequence, each one focusing on the mistakes of the ones before:

  • AdaBoost reweights the training examples, increasing the weight of misclassified ones.

  • Gradient boosting fits each new tree to the residual errors of the current ensemble. Libraries such as XGBoost and LightGBM win most competitions on tabular data.

Bagging / random forestBoosting
Trees trainedindependently, in parallelone after another
Mainly reducesvariancebias
Risklittle overfittingcan overfit if run too long

8.7 k-Nearest Neighbours

k-NN does no training at all. To classify a new point, it finds the kk training points closest to it and takes a majority vote of their labels (or the average of their values, for regression). It is a lazy, instance-based method: all the work happens at prediction time.

Distances

DistanceFormulaNotes
Euclidean∑j(xj−zj)2\sqrt{\sum_j (x_j - z_j)^2}the default
Manhattan∑j∣xj−zj∣\sum_j \lvert x_j - z_j\rvertless sensitive to one large difference
Cosine1−x⋅z∥x∥∥z∥1 - \frac{\mathbf{x}\cdot\mathbf{z}}{\lVert\mathbf{x}\rVert\lVert\mathbf{z}\rVert}for text and other sparse vectors

Choosing k

  • Small kk (e.g. 1): a very wiggly boundary; sensitive to noise (high variance).

  • Large kk: a smooth boundary that may miss real detail (high bias).

  • Choose kk by cross-validation; an odd kk avoids ties between two classes.

Weighted k-NN gives closer neighbours more say, for example a weight of 1/d1/d.

The curse of dimensionality

In many dimensions, all points end up roughly the same distance from each other, so “nearest” stops meaning much. k-NN works best with a modest number of meaningful features; with hundreds, reduce the dimension first (PCA, Chapter 13).

TrainingPredictionMemory
O(1)O(1)O(nd)O(nd) per querystores all nn examples
Source
<Figure size 1200x320 with 3 Axes>

8.8 Naive Bayes

Naive Bayes is a probabilistic classifier built on Bayes’ theorem:

P(y∣x)=P(x∣y) P(y)P(x)  ∝  P(y) P(x∣y)P(y \mid \mathbf{x}) = \frac{P(\mathbf{x} \mid y)\, P(y)}{P(\mathbf{x})} \;\propto\; P(y)\, P(\mathbf{x} \mid y)

Estimating P(x∣y)P(\mathbf{x} \mid y) for every combination of features is impossible. The naive assumption is that the features are independent given the class:

P(x∣y)=∏j=1dP(xj∣y)⟹y^=arg⁡max⁡y  P(y)∏jP(xj∣y)P(\mathbf{x} \mid y) = \prod_{j=1}^{d} P(x_j \mid y) \qquad\Longrightarrow\qquad \hat{y} = \arg\max_{y}\; P(y) \prod_{j} P(x_j \mid y)

The assumption is almost never true (in an email, “free” and “money” are not independent), yet Naive Bayes classifies surprisingly well, trains in one pass over the data, and is a strong baseline for text.

Laplace smoothing

If a word never appeared in a spam email, its estimated probability given spam is 0, and the whole product becomes 0. Laplace (add-one) smoothing adds 1 to every count:

P(w∣c)=count(w,c)+1total words in c+∣V∣P(w \mid c) = \frac{\text{count}(w, c) + 1}{\text{total words in } c + \lvert V\rvert}

where ∣V∣|V| is the vocabulary size.

In practice, multiply many small probabilities by adding their logarithms instead, to avoid numerical underflow. For numeric features, Gaussian Naive Bayes models each P(xj∣y)P(x_j \mid y) as a normal distribution.

8.9 Evaluating Classifiers

The confusion matrix

For a binary classifier (positive = the class we are looking for, such as disease):

Predicted positivePredicted negative
Actually positiveTrue positive (TP)False negative (FN)
Actually negativeFalse positive (FP)True negative (TN)

From it:

MetricFormulaQuestion it answers
AccuracyTP+TNTP+TN+FP+FN\frac{TP + TN}{TP + TN + FP + FN}How often is it right?
PrecisionTPTP+FP\frac{TP}{TP + FP}When it says positive, how often is it right?
Recall (sensitivity)TPTP+FN\frac{TP}{TP + FN}Of the real positives, how many does it find?
F1 score2⋅precision⋅recallprecision+recall2\cdot\frac{\text{precision}\cdot\text{recall}}{\text{precision} + \text{recall}}A balance of the two

Which error matters more depends on the application: a cancer screen wants high recall (do not miss a patient); a spam filter wants high precision (do not lose a real email).

Thresholds and ROC curves

A probabilistic classifier predicts positive when p>tp > t. Lowering the threshold tt catches more positives (recall up) at the cost of more false alarms. The ROC curve plots the true-positive rate (recall) against the false-positive rate FPFP+TN\frac{FP}{FP+TN} for every threshold; the area under the curve (AUC) summarises it: 1.0 is perfect, 0.5 is random guessing.

k-fold cross-validation

  1. Split the data into kk equal folds (often k=5k = 5 or 10).

  2. For each fold: train on the other k−1k-1 folds, evaluate on this one.

  3. Report the mean (and standard deviation) of the kk scores.

Every example is used for evaluation exactly once, and the spread of the scores shows how stable the model is. For classification, use stratified folds that keep the class proportions. Cross-validation is for choosing models and hyperparameters; the test set is still kept for the end.

8.10 A Practical Workflow

Putting it all together, with scikit-learn:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)

# The scaler is inside the pipeline: within each fold it is fitted on the training part only (no leakage)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
search = GridSearchCV(model, {'logisticregression__C': [0.01, 0.1, 1, 10]}, cv=5, scoring='f1')
search.fit(X_train, y_train)

print(search.best_params_, search.best_score_)
print('test F1:', search.score(X_test, y_test))   # the test set, used once

Which model when?

SituationGood first choices
Tabular data, want accuracyrandom forest, gradient boosting
Need to explain each decisiona shallow decision tree, logistic regression
Few examples, many text featuresNaive Bayes, logistic regression
Few features, irregular boundaryk-NN (with scaling)
Images, sound, text at scaleneural networks (Part III)

8.11 Summary

  • Supervised learning fits a model hh to labelled examples so that it generalises to new ones.

  • Overfitting is the central danger: judge models on data they have not seen, keep the test set for the end, and avoid leakage.

  • Linear regression minimises squared error, in closed form or by gradient descent; regularisation (ridge, lasso) controls complexity.

  • Logistic regression turns a linear score into a probability with the sigmoid (softmax for many classes) and is trained with cross-entropy.

  • Decision trees split on the feature with the highest information gain or lowest Gini impurity; prune them to generalise.

  • Random forests (bagging + random features) and boosting combine many trees into strong models.

  • k-NN votes among the nearest training points; scale the features and choose kk by cross-validation.

  • Naive Bayes applies Bayes’ theorem with an independence assumption; use Laplace smoothing.

  • Evaluate with the confusion matrix, precision, recall, F1, ROC/AUC and cross-validation.

Exercises

  1. Compute the information gain of Wind on the tennis data and check that it is 0.048.

  2. A classifier has TP = 30, FP = 10, FN = 20, TN = 940. Compute accuracy, precision, recall and F1. Is accuracy a good summary here?

  3. Why must the mean and standard deviation used for scaling be computed on the training set only?

  4. With k=1k = 1, what is the training accuracy of k-NN? Why does that not mean it is a good model?

  5. Explain in your own words why averaging many random trees reduces variance.

  6. In the Naive Bayes example, what would P(spam∣free)P(\text{spam} \mid \text{free}) be for the one-word email “free”?

Further Reading

  • G. James, D. Witten, T. Hastie, R. Tibshirani, An Introduction to Statistical Learning, 2nd ed., Springer, 2021 (free online).

  • A. Géron, Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow, 3rd ed., O’Reilly, 2022.

  • C. C. Aggarwal, Artificial Intelligence: A Textbook, Springer, 2021, Chapter 6.

  • The scikit-learn user guide: https://scikit-learn.org/stable/user_guide.html