Chapter 8: Supervised Learning
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) | |
|---|---|---|
| Input | Rules, facts, a model of the problem | Examples (data) |
| Output | Conclusions that follow for certain | A rule (model) that is probably right |
| Strength | Exact, explainable | Finds patterns no one wrote down |
| Weakness | Someone must write the rules | Needs 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 examples:
is the feature vector of example (for a house: area, rooms, age…).
is its label: a class in classification (spam / not spam), a number in regression (a price).
We want a function , the hypothesis or model, with , 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 says how bad one prediction is:
| Task | Loss | Formula |
|---|---|---|
| Regression | squared error | |
| Classification | 0–1 loss | 1 if , else 0 |
| Probabilistic classification | cross-entropy (log loss) |
Learning picks the model with the smallest average loss on the training set, the empirical risk:
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
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
x = np.sort(rng.uniform(0, 1, 15))
y = np.sin(2 * np.pi * x) + rng.normal(0, 0.2, 15)
grid = np.linspace(0, 1, 300)
fig, axes = plt.subplots(1, 3, figsize=(12, 3.2), sharey=True)
for ax, deg, name in zip(axes, [1, 4, 15], ['degree 1: underfits', 'degree 4: about right', 'degree 15: overfits']):
coef = np.polyfit(x, y, deg)
ax.plot(grid, np.sin(2 * np.pi * grid), '--', color='gray', label='true function')
ax.plot(grid, np.clip(np.polyval(coef, grid), -2, 2), color='C1', lw=2, label='model')
ax.scatter(x, y, color='C0', zorder=3, label='training data')
ax.set_title(name); ax.set_ylim(-1.8, 1.8)
axes[0].legend(loc='lower left', fontsize=8)
plt.tight_layout(); plt.show()/tmp/ipykernel_2420854/1187566595.py:11: RankWarning: Polyfit may be poorly conditioned
coef = np.polyfit(x, y, deg)

The bias–variance trade-off¶
For squared error, the expected error of a model on a new point splits into three parts:
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 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:
Training set (about 60–70%): fit the model’s parameters.
Validation set (about 15–20%): compare models and choose hyperparameters (the degree of a polynomial, the depth of a tree, in k-NN).
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:
where we add a constant feature so that (the bias or intercept) fits in the same vector.
We choose to minimise the mean squared error (MSE):
where is the matrix whose rows are the examples.
Solution 1: the normal equation¶
Setting the gradient to zero gives a closed-form answer:
The normal equation costs about to invert : fine for tens or hundreds of features, too slow for millions.
Solution 2: gradient descent¶
Gradient descent starts from any and repeatedly takes a small step downhill:
The learning rate 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 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
X = np.array([1, 2, 3, 4.]); Y = np.array([3, 5, 7, 9.])
fig, axes = plt.subplots(1, 2, figsize=(11, 3.4))
for eta, col in [(0.01, 'C0'), (0.05, 'C1'), (0.12, 'C3')]:
w0 = w1 = 0.0; hist = []
for _ in range(60):
err = w0 + w1 * X - Y
hist.append(np.mean(err ** 2))
w0 -= eta * 2 * err.mean(); w1 -= eta * 2 * (err * X).mean()
axes[0].plot(np.minimum(hist, 120), color=col, label=f'η = {eta}')
axes[0].set_xlabel('step'); axes[0].set_ylabel('MSE'); axes[0].set_title('The learning rate matters'); axes[0].legend()
w = np.linalg.lstsq(np.c_[np.ones(4), X], Y, rcond=None)[0]
axes[1].scatter(X, Y, zorder=3); g = np.linspace(0, 5, 10); axes[1].plot(g, w[0] + w[1] * g, color='C1')
axes[1].scatter([5], [11], marker='*', s=200, color='C2', zorder=4); axes[1].set_title('y = 1 + 2x, and the prediction for x = 5')
plt.tight_layout(); plt.show()
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:
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 as features, 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:
| Method | Objective | Effect |
|---|---|---|
| Ridge (L2) | shrinks all weights smoothly | |
| Lasso (L1) | sets some weights exactly to 0: selects features |
The strength is a hyperparameter, chosen on the validation set. Ridge also has a closed form: .
8.4 Logistic Regression¶
Despite its name, logistic regression is a classifier. For two classes (), it computes a linear score and squashes it into a probability with the sigmoid function:
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 : the decision boundary 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):
It punishes confident mistakes hard: predicting for a true 1 costs . Its gradient has the same simple form as linear regression’s:
There is no closed form, so we use gradient descent.
More than two classes: softmax¶
With classes, keep one weight vector per class and turn the scores into probabilities with the softmax:
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 in which class has proportion :
A pure set (all one class) has .
A 50/50 set of two classes has bit, the maximum for two classes.
The information gain of splitting on attribute is the drop in entropy:
Worked example: should we play tennis?¶
The classic 14-day dataset (9 Yes, 5 No):
| Day | Outlook | Temp. | Humidity | Wind | Play |
|---|---|---|---|---|---|
| 1 | Sunny | Hot | High | Weak | No |
| 2 | Sunny | Hot | High | Strong | No |
| 3 | Overcast | Hot | High | Weak | Yes |
| 4 | Rain | Mild | High | Weak | Yes |
| 5 | Rain | Cool | Normal | Weak | Yes |
| 6 | Rain | Cool | Normal | Strong | No |
| 7 | Overcast | Cool | Normal | Strong | Yes |
| 8 | Sunny | Mild | High | Weak | No |
| 9 | Sunny | Cool | Normal | Weak | Yes |
| 10 | Rain | Mild | Normal | Weak | Yes |
| 11 | Sunny | Mild | Normal | Strong | Yes |
| 12 | Overcast | Mild | High | Strong | Yes |
| 13 | Overcast | Hot | Normal | Weak | Yes |
| 14 | Rain | Mild | High | Strong | No |
Step 1. bits.
Step 2. Split on Outlook: Sunny (2 Yes, 3 No, ), Overcast (4 Yes, ), Rain (3 Yes, 2 No, ):
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:
For the tennis data, . Gini and entropy almost always choose the same split; Gini is a little cheaper to compute.
Three classic algorithms¶
| ID3 | C4.5 | CART | |
|---|---|---|---|
| Split criterion | information gain | gain ratio | Gini (classification), MSE (regression) |
| Numeric features | no | yes (thresholds) | yes (thresholds) |
| Tree shape | multiway | multiway | binary |
| Pruning | no | yes | yes (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 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):
Draw bootstrap samples: examples drawn with replacement from the training set (each sample leaves out about 37% of the examples).
Train one tree on each sample.
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 features (often ). 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 forest | Boosting | |
|---|---|---|
| Trees trained | independently, in parallel | one after another |
| Mainly reduces | variance | bias |
| Risk | little overfitting | can 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 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¶
| Distance | Formula | Notes |
|---|---|---|
| Euclidean | the default | |
| Manhattan | less sensitive to one large difference | |
| Cosine | for text and other sparse vectors |
Choosing k¶
Small (e.g. 1): a very wiggly boundary; sensitive to noise (high variance).
Large : a smooth boundary that may miss real detail (high bias).
Choose by cross-validation; an odd avoids ties between two classes.
Weighted k-NN gives closer neighbours more say, for example a weight of .
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).
| Training | Prediction | Memory |
|---|---|---|
| per query | stores all examples |
Source
from sklearn.datasets import make_moons
from sklearn.neighbors import KNeighborsClassifier
Xm, ym = make_moons(200, noise=0.3, random_state=1)
xx, yy = np.meshgrid(np.linspace(-2, 3, 200), np.linspace(-1.5, 2, 200))
fig, axes = plt.subplots(1, 3, figsize=(12, 3.2))
for ax, k in zip(axes, [1, 15, 100]):
m = KNeighborsClassifier(k).fit(Xm, ym)
zz = m.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
ax.contourf(xx, yy, zz, alpha=0.25, cmap='coolwarm'); ax.scatter(Xm[:, 0], Xm[:, 1], c=ym, cmap='coolwarm', s=12)
ax.set_title(f'k = {k}'); ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout(); plt.show()
8.8 Naive Bayes¶
Naive Bayes is a probabilistic classifier built on Bayes’ theorem:
Estimating for every combination of features is impossible. The naive assumption is that the features are independent given the class:
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:
where 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 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 positive | Predicted negative | |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
From it:
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | How often is it right? | |
| Precision | When it says positive, how often is it right? | |
| Recall (sensitivity) | Of the real positives, how many does it find? | |
| F1 score | 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 . Lowering the threshold 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 for every threshold; the area under the curve (AUC) summarises it: 1.0 is perfect, 0.5 is random guessing.
k-fold cross-validation¶
Split the data into equal folds (often or 10).
For each fold: train on the other folds, evaluate on this one.
Report the mean (and standard deviation) of the 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 onceWhich model when?¶
| Situation | Good first choices |
|---|---|
| Tabular data, want accuracy | random forest, gradient boosting |
| Need to explain each decision | a shallow decision tree, logistic regression |
| Few examples, many text features | Naive Bayes, logistic regression |
| Few features, irregular boundary | k-NN (with scaling) |
| Images, sound, text at scale | neural networks (Part III) |
8.11 Summary¶
Supervised learning fits a model 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 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¶
Compute the information gain of Wind on the tennis data and check that it is 0.048.
A classifier has TP = 30, FP = 10, FN = 20, TN = 940. Compute accuracy, precision, recall and F1. Is accuracy a good summary here?
Why must the mean and standard deviation used for scaling be computed on the training set only?
With , what is the training accuracy of k-NN? Why does that not mean it is a good model?
Explain in your own words why averaging many random trees reduces variance.
In the Naive Bayes example, what would 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