Machine Learning · Topic 1 · Introduction to Machine Learning · Interactive sheet · Advanced

The Introduction to Machine Learning Blueprint

A learning algorithm picks, from a space of candidate functions, the one with the smallest error on observed data, and is judged only by its error on data it has never seen. What changes between supervised, unsupervised, reinforcement and transfer learning is the feedback the data provides; what limits all of them is how the number of features stretches the space the data must fill.

Every number on this page is clickable. Every underlined term has a definition.

Before you start: least-squares fitting of a line (Linear Regression), expectation and variance of a random variable, and vectors with the dot product and Euclidean distance. The basics of every idea here are on the Introduction to Machine Learning Intermediate page.

1959
“machine learning” named
E · T · P
Mitchell's definition, 1997
bias²+var+σ²
test error, decomposed
0.25 %
of a 10-D cube inside its ball
79 %
of each axis to hold 10 % of data in 10-D
01

From writing rules to learning them

Some tasks have no rule a programmer can write down; machine learning replaces the rule with a function fitted to examples, and Mitchell's E, T, P turns “learning” into a measurable claim.

Experience improves performance: measured, not claimed

Two classes drawn from Gaussians with means (−1, −0.5) and (1, 0.5) and σ = 1.1. A nearest-centroid learner sees n labelled examples (E), classifies (T) and is scored on 2,000 fresh points (P). A hand-written rule never improves; the Bayes error is the floor no learner can pass.

experience E: labelled examples n8
learned (mean of 25 draws)hand rule “x₁ > 0”Bayes floorthis n, this draw
E · experience
8
labelled pairs (x, y)
P · test accuracy
–
hand rule error
–
Bayes error Φ(−Δ/2σ)
–

The formal problem

Data (xᵢ, yᵢ) ~ P(X, Y) i.i.d. Choose f from a hypothesis class 𝓗 to minimise the risk R(f) = 𝔼[ℓ(f(X), Y)]. P is unknown, so we minimise the empirical risk R̂ₙ(f) = (1/n) Σ ℓ(f(xᵢ), yᵢ) and hope R̂ₙ ≈ R. That hope is generalisation.

1950 Turing: learning machines 1957 Bellman: curse of dimensionality 1958 perceptron 1959 Samuel names the field 1967 nearest neighbour 1989 Q-learning 1997 Mitchell: E, T, P 2012 deep learning wins ImageNet 2016 AlphaGo
02

Walk one dataset through the pipeline

Twenty students, two features (hours studied, hours slept), one label (passed?): follow them from raw records to a trained logistic regression and one prediction, every number computed live.
passed (y = 1) failed (y = 0) test (held out) boundary p = 0.5
stage 1 of 11100%
stage scrubberraw records
beads: click, or focus one and use ← →
stage

train loss
–
train accuracy
–

Derivation: the gradient the walker follows

Model: a linear score passed through the sigmoid
s = w·z + b, p = σ(s) = 1 ÷ (1 + e−s), and σ′(s) = σ(s)(1 − σ(s))
Loss for one example: the negative log-likelihood of a Bernoulli label (cross-entropy)
ℓ = −[y ln p + (1 − y) ln(1 − p)]
Chain rule through p
∂ℓ/∂p = −y/p + (1 − y)/(1 − p) = (p − y) ÷ [p(1 − p)]
Multiply by ∂p/∂s = p(1 − p): the p(1 − p) cancels
∂ℓ/∂s = p − y, so ∂ℓ/∂w = (p − y)·z and ∂ℓ/∂b = p − y
Average over the n training examples and step downhill (gradient descent, learning rate η = 0.5)
w ← w − η·(1/n) Σ (pᵢ − yᵢ) zᵢ, b ← b − η·(1/n) Σ (pᵢ − yᵢ). The loss is convex in (w, b), so there are no bad local minima.

The training data here are linearly separable, so the minimum of L is approached only as ‖w‖ → ∞: the loss keeps falling after the accuracy reaches 100 %. Watch the boundary sharpen between epoch 100 and 1000.

Quick check
At stage 5 (w = 0, b = 0) the training loss is 0.693 whatever the labels are. Why?
With w = 0 and b = 0 every score is 0, so p = 0.5 for everyone; each example contributes −ln 0.5 = ln 2 whether y is 0 or 1. The class balance doesn't matter: it is 8 to 7 in this training set anyway.
03

Three ideas that make learning work

The right feature map makes a hard problem linear, the right capacity balances underfitting against overfitting, and when no labels exist a reward can still drive learning.

Idea 1 · Features: a non-linear problem becomes linear in φ(x)

threshold t on x₃ = x₁² + x₂²1.5
best straight line in x
–
vs
threshold on x₃
–
φ(x) = (x₁, x₂, x₁² + x₂²) · rule: ŷ = 1 ⇔ φ₃(x) > t

A linear classifier in φ-space is a quadric in x-space. Kernel methods use the same trick with φ implicit: k(x, x′) = φ(x)·φ(x′).

Idea 2 · Capacity: training error falls, test error turns back up

true f(x) = sin 2πxleast-squares polynomial10 training points, noise σ = 0.3
polynomial degree M3
train RMS
–
vs
test RMS
–

Idea 3 · Reward: a three-armed bandit learns with no labels at all

No pulls yet. Each arm pays 1 with an unknown probability.

exploration rate ε0.10
QN+1(a) = QN(a) + (1/N)·(r − QN(a))
pulls T
0
total reward
0
regret
0
best arm share
–

With ε = 0 the agent can lock onto a poor arm forever; with large ε it keeps paying for exploration. Expected regret per step ≥ ε·(μ* − mean μ).

Quick check
An arm has Q = 0.50 after N = 4 pulls. The fifth pull pays r = 1. What is the new Q?
Q₅ = Q₄ + (1/5)(r − Q₄) = 0.5 + 0.2 × 0.5 = 0.60, which is the mean of the five rewards (2 + 1) ÷ 5. The update is an exact running average, not a fixed-size nudge.
04

The defining choice: learn from labels, or find structure

The same 90 points, two objectives: supervised learning minimises a loss against given labels, unsupervised learning minimises a criterion of the data alone, here the k-means inertia.

labelled examples per class m3
μ̂c = (1/m) Σyᵢ=c xᵢ · ŷ(x) = argminc ‖x − μ̂c‖²
labels used
9
→
accuracy
–

Same geometry, different question. Nearest-centroid and k-means use the identical rule argmin ‖x − μ‖². Supervised learning gets μ from labels in one pass; k-means must guess μ and c together, so it alternates, converges to a local minimum of J, and cannot name its clusters.

Quick check
Why can a k-means iteration never increase J?
It is coordinate descent: the assignment step is the exact minimiser over c, the update step the exact minimiser over μ. J is not jointly convex (that is why different starts end in different local minima), but each block step can only lower it, and there are finitely many assignments, so it converges.
05

Empirical risk, by hand and by eye

The central quantity of supervised learning is the average loss on the training data; for a line ŷ = wx + b with squared loss it is the mean squared error, and its minimiser has a closed form.

Worked example by hand: three points, one line

data and model
Press Next step.

Data (1, 2), (2, 3), (3, 5); first the guess ŷ = 1.5x, then the least-squares line. Redo every step on paper: there are only three points.

MSE(w, b) = (1/n) Σ (yᵢ − (wxᵢ + b))² · w* = Sxy ÷ Sxx, b* = ȳ − w* x̄
inputs xᵢ
targets yᵢ
empirical risk (MSE)
–
data, line and the squared residuals it pays for100%

Derivation: why w* = Sxy ÷ Sxx

Differentiate with respect to b and set to zero
∂MSE/∂b = −(2/n) Σ (yᵢ − wxᵢ − b) = 0 ⇒ b = ȳ − w x̄
Substitute: residuals become centred
yᵢ − wxᵢ − b = (yᵢ − ȳ) − w(xᵢ − x̄)
Differentiate with respect to w and set to zero
Σ (xᵢ − x̄)[(yᵢ − ȳ) − w(xᵢ − x̄)] = 0 ⇒ w* = Σ(xᵢ − x̄)(yᵢ − ȳ) ÷ Σ(xᵢ − x̄)²
In matrix form for d features (column of 1s for b)
∇ ‖y − Xθ‖² = −2Xᵀ(y − Xθ) = 0 ⇒ θ* = (XᵀX)⁻¹Xᵀy, defined when XᵀX is invertible (needs n ≥ d + 1)
Why squared loss: it is maximum likelihood under Gaussian noise
y = wx + b + ε, ε ~ 𝒩(0, σ²) ⇒ −ln L = (n/2σ²)·MSE + const, so minimising MSE = maximising L

MSE is a convex quadratic bowl in (w, b): the gradient step button above slides down it, and the “set w*, b*” button jumps to its bottom.

Quick check
Data (1, 2) and (2, 4), model w = 1, b = 0. What is ∂MSE/∂w?
Residuals r = (2 − 1, 4 − 2) = (1, 2). ∂MSE/∂w = −(2/n) Σ xᵢrᵢ = −(2/2)(1·1 + 2·2) = −5. Negative, so increasing w lowers the error, as it should: the true slope is 2.
06

Where the test error comes from

Expected squared test error splits exactly into bias², variance and irreducible noise; the bars below are computed from 400 simulated training sets for each polynomial degree.
100%
bias²variancenoise σ²
click a bar

The arithmetic for that degree appears here.

Best degree

–

The data specification

Derivation: the decomposition at a fixed x

Write the target as truth plus noise, y = f(x) + ε, 𝔼ε = 0, Var ε = σ², ε independent of the training set D
𝔼[(y − f̂)²] = 𝔼[(f − f̂ + ε)²]
Expand; the cross term vanishes because ε is independent of f̂ and has mean 0
= 𝔼[(f − f̂)²] + 2𝔼[ε]𝔼[f − f̂] + 𝔼[ε²] = 𝔼[(f − f̂)²] + σ²
Add and subtract the average fit f̄ = 𝔼D[f̂]
𝔼[(f − f̄ + f̄ − f̂)²] = (f − f̄)² + 2(f − f̄)𝔼[f̄ − f̂] + 𝔼[(f̄ − f̂)²]
𝔼[f̄ − f̂] = 0 by definition of f̄, so
𝔼[(y − f̂)²] = (f − f̄)² + 𝔼[(f̂ − f̄)²] + σ² = bias² + variance + noise

The chart averages each term over 60 test inputs x on [0, 1]. Monte Carlo error makes the parts sum to the empirical test MSE only approximately; the chart shows the three parts and their exact sum.

Quick check
Noise σ² = 0.09. A model's expected test MSE is 0.15 and its bias² is 0.02. What is its variance?
0.15 = 0.02 + Var + 0.09, so Var = 0.04. Variance is now twice bias², a sign the model may be too flexible for the data.
07

The family of learning paradigms

Paradigms differ by the feedback in the data: full labels, none, a few, labels made from the data itself, a scalar reward, or knowledge carried over from another task (transfer). Click a row for its formal statement.
paradigm

Pick a row above.

Transfer learning, formally. Pan & Yang (2010): a domain is 𝒟 = {𝒳, P(X)}, a task is 𝒯 = {𝒴, f}. Given a source (𝒟ₛ, 𝒯ₛ) and a target (𝒟ₜ, 𝒯ₜ) with 𝒟ₛ ≠ 𝒟ₜ or 𝒯ₛ ≠ 𝒯ₜ, transfer learning improves the target predictor fₜ using knowledge from the source. It helps when source and target share low-level structure; when they don't, it can hurt (negative transfer).

Quick check
A model is trained to predict a masked word in a sentence from the surrounding words, on text no human annotated. Which paradigm is this?
The loss is supervised in form, ℓ(f(x_visible), x_hidden), but the label is manufactured from the data. That is what lets language models pre-train on billions of words before being transferred to labelled tasks.
08

The limit: the curse of dimensionality

Every added feature multiplies the volume the data must cover; the curse of dimensionality shows up as huge neighbourhoods, exponential sample needs, empty centres and distances that stop discriminating.
dimensions d (features)10
fraction of data in the neighbourhood r0.10
bins per axis b (resolution)10
edge = r1/d · cells = bd · ball/cube = πd/2(½)d ÷ Γ(d/2+1)
neighbourhood edge
–
samples for one per cell
–
cube inside its ball
–
distance contrast
–
as d grows from 1 to 100 · current d marked100%
edge r1/dball / cubedistance contrast (scaled ÷ max)
Quick check
Uniform data in d = 20 dimensions. What edge must a sub-cube have to contain 10 % of the data?
e = 0.1^(1/20) = e^(ln 0.1 ÷ 20) = e^(−0.115) ≈ 0.89. To see 10 % of the data you must span 89 % of every feature's range, so the neighbourhood is no longer local. Set d = 20 above to check.
09

Apply it to a new problem

A seven-step procedure, a decision on the paradigm from the feedback you actually have, and a short reference implementation you can copy and run.
Pin down T, P and E. What is predicted, which metric (accuracy, F1, RMSE, reward), what data exist and how they were collected.
e.g. T = flag fraud, P = recall at 1 % false-positive rate, E = 2 years of transactions
Read the feedback to pick the paradigm (tool on the right).
labels? how many? a reward? a related pretrained model?
Split before anything else. Hold out a test set; split by time or by group when examples are not independent.
train / validation / test, or k-fold cross-validation on train
Build features and fit every preprocessing step (scaling, imputation, encoding) on the training fold only.
fitting the scaler on all data = leakage
Start with a baseline: majority class, mean prediction, or a linear model.
a model that does not beat the baseline has learned nothing
Tune capacity on validation (degree, k, regularisation λ), watching the U-curve of section 06.
choose by validation score, never by test score
Test once, then monitor. Report the test score once; after deployment watch for distribution shift.
P(X) or P(Y | X) drifts → retrain

Which paradigm?

Feedback you have
Pretrained model from a related task?

Reference implementation: the learning step from scratch

# logistic regression by batch gradient descent: the loop of section 02
import numpy as np

def fit_logistic(X, y, lr=0.5, epochs=1000):
    mu, sd = X.mean(0), X.std(0)          # fit scaling on TRAIN only
    Z = (X - mu) / sd
    w, b = np.zeros(Z.shape[1]), 0.0
    for _ in range(epochs):
        p = 1 / (1 + np.exp(-(Z @ w + b)))  # sigma(w.z + b)
        g = p - y                          # dl/ds = p - y
        w -= lr * Z.T @ g / len(y)
        b -= lr * g.mean()
    return w, b, mu, sd

def predict_proba(X, w, b, mu, sd):
    return 1 / (1 + np.exp(-(((X - mu) / sd) @ w + b)))

Twelve lines contain the whole of section 02: scaling with training statistics, the sigmoid, the gradient p − y from the derivation, and the update. Return μ and σ with the weights: a model is the weights and the preprocessing it was trained with.

Quick check
You select the polynomial degree that gives the lowest error on the test set and report that error. What is wrong?
Choosing the minimum over several candidates on the same data biases that minimum downwards. Select on validation (or cross-validation) and touch the test set once, at the end.
10

From hand-written rules to learned representations

Seventy years of milestones on five lanes; the 1959 point marks where the field got its name. Click a point for what changed, before and after.
milestones by paradigm, 1943–2020100%
click a point

Before and after learning · tap a card to flip

Quick check
What made Samuel's 1959 checkers program “machine learning” rather than a clever hand-written player?
Samuel tuned the weights of a board-evaluation polynomial from self-play: in Mitchell's terms, P (games won) improved with E (games played). Search depth alone is not learning.
11

Where it is used today

Each application is tagged with the paradigm that powers it and with what came next; most real systems combine several.
Quick check
A fraud model's precision drops a year after deployment, although its code and weights never changed. What is the most likely cause?
Generalisation is guaranteed only for data from the training distribution. Adversarial domains (fraud, spam) change on purpose; monitoring and periodic retraining are part of the method, not an afterthought.
12

Key takeaways

Eight sentences to remember. Click each for the evidence on this page.
Section 01 measures it: test accuracy of a nearest-centroid learner rises with n towards the Bayes floor, while a hand rule stays flat.
R̂ₙ(f) = (1/n) Σ ℓ(f(xᵢ), yᵢ) is an optimistic estimate of R for the f that minimises it; held-out data are the only honest estimate. Sections 01, 05 and 09.
Supervised minimises a loss against labels, unsupervised a criterion of x alone (k-means J), reinforcement maximises expected return, transfer starts the target learner from a source solution. Sections 04 and 07.
The rings of section 03 are inseparable by any line in (x₁, x₂) but separable by one threshold on x₁² + x₂².
Section 06 computes the three parts for degrees 0–9; the minimum is in the middle, and σ² is a floor.
It is the MLE under Gaussian noise; logistic regression has no closed form but a convex loss with gradient (p − y)x. Sections 02 and 05.
Capturing 10 % of uniform data needs 0.1^(1/d) of each axis, about 79 % at d = 10; the inscribed ball holds 0.25 % of a 10-D cube; distance contrast collapses. Section 08.
Leakage and test-set selection both bias the reported score; distribution shift degrades a deployed model. Sections 09 and 11.
13

Check your understanding

Five questions on derivations, calculations and what-ifs, with immediate feedback. Score 4 or more and the stamp is yours.
0 / 5
■ STAMPED · ML BLUEPRINT · ADVANCED
14

Glossary

Every term used on this page. Type to filter; click a term to open its definition.