Write the task as E, T and P
⏱ 3 min · match pairs
The running example starts here: 200 past students of this course, and a program that should predict who passes.
Arthur Samuel named the field in 1959. Tom Mitchell made it testable in 1997: a program learns from experience E with respect to tasks T and performance measure P if its performance at T, measured by P, improves with E.
Formally, examples (xᵢ, yᵢ) are drawn i.i.d. from an unknown P(X, Y). The learner picks f from a hypothesis class 𝓗 by minimising the empirical risk R̂ₙ(f), but it is judged by the true risk R(f) on data it has never seen. P therefore estimates R, never R̂ₙ: accuracy on the training students is optimistically biased for the very f chosen to minimise it.
- x
- (hours studied, hours slept)
- y
- passed ∈ {0, 1}
- n
- 200 past students
Match each part of the pass-predictor to its role.
- (a) The labelled records (xᵢ, yᵢ), i = 1…200, are the experience E.
- (b) Mapping a new x to ŷ ∈ {0, 1} is the task T.
- (c) Accuracy on next semester's students is measured on fresh draws from P(X, Y): it estimates 1 − R(f) under 0–1 loss, so it is P.
- (d) The two columns are the input features x of each example, not E as a whole.
- (e) Accuracy on the 200 training students is 1 − R̂ₙ(f̂) for the f̂ that minimised R̂ₙ: not a valid P, because 𝔼[R̂ₙ(f̂)] ≤ R(f̂) — the selection made it optimistic.
Standardise one student's features
⏱ 4 min · type two numbers
Each student becomes a vector x ∈ ℝ². Before any distance or gradient is computed, the axes must be put on the same scale.
A feature is one measurable property; the feature map φ turns a raw record into the vector the learner sees. Euclidean distance ‖x − x′‖² and the gradient of a linear model both scale with each feature's units, so a column in minutes would dominate one in hours. Standardisation fixes this:
with μⱼ and σⱼ computed on the training set only, then reused unchanged for every new student (otherwise test information leaks into training). Each zⱼ then has mean 0 and variance 1 across the cohort, and the loss surface of a linear model becomes far less elongated, so gradient descent converges in fewer steps.
| feature | mean μ | std σ |
|---|---|---|
| x₁ hours studied / week | 6 | 2 |
| x₂ hours slept / night | 7 | 1 |
Aisha studied 9 h a week and slept 5 h a night. Give her standardised vector z = (z₁, z₂), to 2 decimals (±0.01).
- z₁ = (9 − 6) ÷ 2 = 3 ÷ 2 = 1.5: Aisha studies 1.5 standard deviations more than the average student.
- z₂ = (5 − 7) ÷ 1 = −2: she sleeps 2 standard deviations less.
- So z = (1.5, −2). In raw units her distance to the mean student is √(3² + 2²) = 3.61; in z-units it is √(1.5² + 2²) = 2.5, and now the sleep deficit, not the study surplus, dominates — the scale changed which feature matters.
- Unit check: (h − h) ÷ h has no unit, which is why z-scores from different columns can be added in w·z.
Compute the empirical risk of a guess
⏱ 4 min · type a number
Three students of the cohort, hours studied x against exam score y. A first guess at the rule: ŷ = 5x + 40.
For regression with squared loss ℓ(ŷ, y) = (y − ŷ)², the empirical risk is the mean squared error:
Each residual rᵢ = yᵢ − ŷᵢ is drawn below as a vertical gap; squaring it gives the area of the red square the line “pays” for that point. Squared loss is not arbitrary: if y = wx + b + ε with ε ~ 𝒩(0, σ²), then −ln L = (n/2σ²)·MSE + const, so minimising MSE is maximum likelihood under Gaussian noise. It also punishes one big miss more than several small ones.
Data (2, 50), (4, 60), (6, 76). Compute the MSE of ŷ = 5x + 40 (exact; ±0.01).
| xᵢ | yᵢ | ŷᵢ | rᵢ | rᵢ² |
|---|---|---|---|---|
| 2 | 50 | ? | ? | ? |
| 4 | 60 | ? | ? | ? |
| 6 | 76 | ? | ? | ? |
- Predictions: ŷ = 5·2 + 40 = 50, 5·4 + 40 = 60, 5·6 + 40 = 70.
- Residuals r = y − ŷ = (0, 0, 6).
- Squares: 0, 0, 36; sum 36.
- MSE = 36 ÷ 3 = 12 points² (RMSE = √12 ≈ 3.46 points, back in the units of y).
Solve for the least-squares line
⏱ 5 min · fill in the blanks
The guess paid MSE = 12. Calculus finds the line with the smallest possible MSE in one shot.
MSE is a convex quadratic bowl in (w, b), so its minimum is where both partial derivatives vanish. ∂MSE/∂b = 0 gives b = ȳ − w x̄; substituting centres the residuals, and ∂MSE/∂w = 0 then gives
For d features with a column of 1s in X, the same conditions are the normal equations XᵀXθ = Xᵀy, so θ* = (XᵀX)⁻¹Xᵀy, defined when XᵀX is invertible (needs n ≥ d + 1 and no collinear columns). Cost: O(nd² + d³), which is why large d is solved by gradient descent instead (next step).
import numpy as np x = np.array([2, 4, 6]); y = np.array([50, 60, 76]) X = np.column_stack([np.ones_like(x), x]) # 1s column for b theta = np.linalg.lstsq(X, y, rcond=None)[0] # solves XᵀXθ = Xᵀy print(theta) # [36. 6.5] print(np.mean((y - X @ theta) ** 2)) # 2.0
Same three students (2, 50), (4, 60), (6, 76). Fill in the blanks (±0.01).
- x̄ = (2 + 4 + 6) ÷ 3 = 4; ȳ = (50 + 60 + 76) ÷ 3 = 62.
- Sxy = (−2)(−12) + (0)(−2) + (2)(14) = 24 + 0 + 28 = 52; Sxx = 4 + 0 + 4 = 8.
- w* = 52 ÷ 8 = 6.5 points per hour.
- b* = 62 − 6.5 × 4 = 36 points.
- Check: predictions 49, 62, 75; residuals (1, −2, 1) sum to 0 and Σxᵢrᵢ = 2 − 8 + 6 = 0, so both gradients vanish. MSE = (1 + 4 + 1) ÷ 3 = 2, down from 12.
Differentiate the risk
⏱ 4 min · choose one
Most models have no closed form. They follow the gradient downhill — so you must be able to compute it.
Differentiate MSE = (1/n) Σ (yᵢ − wxᵢ − b)² by the chain rule. The inner derivative of the residual is −xᵢ with respect to w and −1 with respect to b:
Gradient descent then updates θ ← θ − η ∇MSE with learning rate η. Each step costs O(nd) instead of the O(d³) solve, and on a convex bowl a small enough η (η < 2 ÷ λmax of the Hessian) is guaranteed to converge to the step-4 answer.
At the guess w = 5, b = 40 (residuals 0, 0, 6 from step 3), what is ∂MSE/∂w?
- Σ xᵢrᵢ = 2·0 + 4·0 + 6·6 = 36.
- ∂MSE/∂w = −(2/3) × 36 = −24. (For comparison ∂MSE/∂b = −(2/3) × 6 = −4.)
- Negative means raising w lowers the error — consistent with w* = 6.5 > 5.
- One step with η = 0.02: w ← 5 − 0.02(−24) = 5.48, b ← 40 − 0.02(−4) = 40.08. New predictions 50.96, 62.0, 72.96; MSE ≈ (0.92 + 4.0 + 9.24) ÷ 3 ≈ 4.72, down from 12.
Score a probability with cross-entropy
⏱ 5 min · type a number
Back to pass/fail. A logistic regression trained on the 200 standardised students learned w = (1.2, 0.8), b = −0.2.
A linear score s = w·z + b is squashed by the sigmoid p = σ(s) = 1 ÷ (1 + e⁻ˢ) into P(y = 1 | z). The loss is the negative log-likelihood of a Bernoulli label, the cross-entropy:
Because σ′(s) = σ(s)(1 − σ(s)), the chain rule cancels neatly: ∂ℓ/∂s = p − y, so ∂ℓ/∂w = (p − y)z and ∂ℓ/∂b = p − y. The loss is convex in (w, b): no bad local minima. Natural logs are used throughout.
Aisha (z = (1.5, −2) from step 2) failed: y = 0. What cross-entropy loss does the model pay on her? (natural log, ±0.005)
- s = 1.2 × 1.5 + 0.8 × (−2) − 0.2 = 1.8 − 1.6 − 0.2 = 0.
- p = σ(0) = 1 ÷ (1 + 1) = 0.5: the model is undecided about Aisha.
- y = 0, so ℓ = −ln(1 − 0.5) = ln 2 ≈ 0.693 nats.
- Gradient on her: ∂ℓ/∂b = p − y = 0.5 and ∂ℓ/∂w = 0.5 × (1.5, −2) = (0.75, −1.0): a descent step lowers w₁ and raises w₂, pushing her score below 0.
Run k-means without the labels
⏱ 4 min · put in order
Hide the pass/fail column. The same 200 z-vectors can still be grouped — that is unsupervised learning.
Supervised nearest-centroid gets each class mean μ̂_c from the labels in one pass and predicts argmin_c ‖x − μ̂_c‖². k-means uses the identical rule but must guess the assignments c(i) and the centres μ together, so it minimises the inertia
by coordinate descent: the assignment step is the exact minimiser over c with μ fixed, the update step (centroid = mean) the exact minimiser over μ with c fixed. Neither can raise J and there are finitely many assignments, so it stops — at a local minimum, since J is not jointly convex. It costs O(nkd) per iteration and cannot name its clusters.
def kmeans(X, k, iters=100, seed=0): rng = np.random.default_rng(seed) mu = X[rng.choice(len(X), k, replace=False)] for _ in range(iters): d = ((X[:, None] - mu[None]) ** 2).sum(-1) # n × k c = d.argmin(1) new = np.array([X[c == j].mean(0) if (c == j).any() else mu[j] for j in range(k)]) if np.allclose(new, mu): break mu = new return c, mu, ((X - mu[c]) ** 2).sum()
Put one run of k-means on the unlabelled students in order (use ↑ ↓; each button is keyboard operable).
- 1Choose k and place k initial centroids μ₁…μₖ (e.g. k random students)
- 2Assign each student to the nearest centroid: c(i) ← argminₖ ‖zᵢ − μₖ‖²
- 3Move each centroid to the mean of its students: μₖ ← mean{zᵢ : c(i) = k}
- 4Recompute the inertia J — it cannot have increased
- 5Stop if no assignment changed; otherwise return to the assignment step
- Initialise k centroids — nothing else can run without them.
- Assign each zᵢ to its nearest centroid (minimises J over c for fixed μ).
- Update each centroid to its cluster mean (minimises J over μ for fixed c, since ∂/∂μₖ Σ‖zᵢ − μₖ‖² = 0 gives the mean).
- Recompute J: both block steps were exact minimisers, so J is non-increasing.
- Stop when no c(i) changes, else repeat from step 2. Different initialisations can stop at different local minima — run several and keep the smallest J for a fixed k (never choose k by J itself: J falls to 0 at k = n).
Your turn: split the test error
⏱ 6 min · three-part task
You fit two polynomial models of exam score (standardised) on hours studied. Repeated over many training sets, each model's error splits into three parts.
Let y = f(x) + ε with 𝔼ε = 0, Var ε = σ², and let f̄ = 𝔼_D[f̂] be the average fit over training sets D. Expanding and dropping the two cross terms (ε is independent of f̂; 𝔼[f̄ − f̂] = 0):
Raising capacity (polynomial degree M) lowers bias² and raises variance; σ² sets a floor no model can pass. Here the score noise is σ = 0.3, so σ² = 0.09.
Noise σ² = 0.09. Answer all three parts (±0.005).
Model A (degree 1): bias² = 0.10, variance = 0.01. Its expected test MSE?
Model B (degree 9): expected test MSE = 0.40, bias² = 0.005. Its variance?
Which diagnosis is right?
- (a) MSE_A = 0.10 + 0.01 + 0.09 = 0.20.
- (b) 0.40 = 0.005 + Var_B + 0.09 ⇒ Var_B = 0.40 − 0.095 = 0.305.
- (c) B's variance (0.305) is 61 times its bias² (0.005): B overfits. A's reducible error is 0.11 against B's 0.31, so A wins at this sample size.
- Neither reaches 0.09: A's reducible part is mostly bias, so a degree between 1 and 9 (or B with regularisation or more data, which shrinks variance roughly like 1/n) would sit nearer the bottom of the U.
Update a value from a reward
⏱ 4 min · predict with a slider
The course app can send one of three study reminders. Nobody labels the “right” message; it only sees a reward: r = 1 if the student opens the material within a day, else 0.
This is a three-armed bandit, the simplest reinforcement learning problem. The agent keeps an estimate Q(a) of each arm's mean reward μ(a), updated incrementally so it never stores the history:
where N + 1 is the arm's new pull count. With step size 1/(N+1) this is exactly the sample mean. ε-greedy picks the best-looking arm with probability 1 − ε and a random arm otherwise; with ε = 0 it can lock onto a poor arm forever, while with fixed ε > 0 the per-step regret stays ≥ ε·(μ* − mean μ). Replacing 1/N by a constant α gives an exponentially weighted average that tracks changing rewards.
Message B has been sent N = 5 times with Q₅(B) = 0.40. The sixth send pays r = 1. Set the slider to your prediction of Q₆(B), then press Check to reveal the true value (±0.01).
- Error: r − Q₅ = 1 − 0.40 = 0.60.
- Step size 1/6 because this is the 6th reward of arm B.
- Q₆ = 0.40 + 0.60 ÷ 6 = 0.40 + 0.10 = 0.50.
- Check as a mean: Q₅ = 0.40 means 2 successes in 5; with one more, 3 ÷ 6 = 0.50. ✓
- With ε = 0.1 and three arms, the greedy arm is chosen with probability 1 − ε + ε/3 ≈ 0.933 per send.
Choose what to retrain
⏱ 4 min · click the diagram
A partner university offers a network trained on 50,000 of its own student records. Your course has only 40 labelled students this year.
In Pan & Yang's (2010) formal terms, a domain is 𝒟 = {𝒳, P(X)} and a task 𝒯 = {𝒴, f}. Transfer learning uses a source (𝒟_S, 𝒯_S) to improve the target f_T when 𝒟_S ≠ 𝒟_T or 𝒯_S ≠ 𝒯_T. In a layered model, early layers compute general features and later layers task-specific ones (Yosinski et al., 2014).
The rule of thumb follows from step 8: every retrained parameter adds variance, and with n = 40 there is little data to pay for it. Small n and a similar source → freeze everything and replace only the output head; more data → also fine-tune the top block at a small learning rate; a very different source can even hurt (negative transfer). The input layer must keep the source's features in the same order and scaling.
general blocktask-specific blockinput / output
The partner's task is the same (pass/fail) and its features are yours. With 40 labelled students, click the one part you should replace and train, keeping the rest frozen.
- n = 40 is tiny: each retrained weight adds variance (step 8), so retrain as few as possible.
- Same features (𝒳_S = 𝒳_T) and same label space; what differs is P(X) and the partner's pass threshold — that lives in the output head.
- So replace and train the output head only (feature extraction), with the hidden blocks frozen.
- With a few hundred labelled students you could next unfreeze block 3 and fine-tune at about 1/10–1/100 of the original learning rate; block 1 stays frozen longest because its general features transfer best.
Measure the curse of dimensionality
⏱ 5 min · type a number
The department wants to add more columns to the 200 student records. Every feature stretches the space those 200 points must fill.
Bellman (1957) named the curse of dimensionality. Take data uniform in the unit cube [0, 1]ᵈ. A sub-cube holding a fraction r of the data has volume r, so its edge is
In 10-D, holding 10 % of the data needs 79 % of each axis (Hastie, Tibshirani & Friedman, The Elements of Statistical Learning, 2009, §2.5): a “local” neighbourhood is no longer local. Volume also flees to the corners: the ball of radius ½ inside the cube has volume π^(d/2) ÷ Γ(d/2 + 1) · (½)ᵈ, only 0.25 % of a 10-D cube. To keep the same density as n points give in 1-D you need nᵈ points.
| d | edge for r = 10 % |
|---|---|
| 1 | 10 % |
| 2 | 32 % |
| 3 | 46 % |
| 5 | ? |
| 10 | 79 % |
from math import pi, gamma edge = lambda r, d: r ** (1 / d) ball = lambda d: pi ** (d / 2) / gamma(d / 2 + 1) / 2 ** d print(edge(0.1, 10), ball(10)) # 0.794… 0.00249…
With d = 5 features, what share of each axis must a sub-cube span to hold 10 % of the students? (in %, ±1)
- e₅(0.1) = 0.1^(1/5) = exp(ln 0.1 ÷ 5) = exp(−2.3026 ÷ 5) = exp(−0.4605).
- exp(−0.4605) ≈ 0.631, so the sub-cube spans ≈ 63 % of each axis.
- Check: 0.631⁵ = 0.100 ✓. Going from d = 5 to d = 10 raises it to 79 %; at d = 20 it is 0.1^(1/20) ≈ 89 %.
- Ball check for d = 10: π⁵ ÷ 5! ÷ 2¹⁰ = 306.02 ÷ 120 ÷ 1024 ≈ 0.00249 = 0.25 %.
Put it all together
⏱ 7 min · capstone
A new student, Ben, studied 8 h a week and slept 6 h a night. Use the cohort statistics of step 2 and the model of step 6: w = (1.2, 0.8), b = −0.2.
No new idea here: chain the earlier steps. Standardise with the training μ and σ (step 2), compute s = w·z + b and p = σ(s) (step 6), score with cross-entropy, read the gradient ∂ℓ/∂b = p − y (steps 5–6), and judge a proposed change of feature space with steps 8 and 11.
- μ, σ
- studied 6, 2 · slept 7, 1
- model
- w = (1.2, 0.8), b = −0.2
- outcome
- Ben failed: y = 0
- σ(0.2)
- compute it: 1 ÷ (1 + e^(−0.2)), e^(−0.2) ≈ 0.8187
Answer every part (numbers ±0.01).
Ben's standardised features.
The model's P(pass) for Ben.
The cross-entropy loss on Ben (he failed, y = 0).
The gradient ∂ℓ/∂b on Ben.
The department proposes 18 more columns (d = 20) for the same 200 students. Best judgement?
- z₁ = (8 − 6) ÷ 2 = 1; z₂ = (6 − 7) ÷ 1 = −1.
- s = 1.2 × 1 + 0.8 × (−1) − 0.2 = 0.2; p = 1 ÷ (1 + 0.8187) = 0.55 (0.5498).
- y = 0, so ℓ = −ln(1 − 0.5498) = −ln 0.4502 = 0.80 nats (0.798) — more than the 0.693 of an undecided model, because it leaned the wrong way.
- ∂ℓ/∂b = p − y = 0.55: positive, so a descent step lowers b; ∂ℓ/∂w = 0.55 × (1, −1).
- d = 20: e₂₀(0.1) = 0.1^(1/20) ≈ 0.89, so with n = 200 every “neighbourhood” spans almost the whole range; the extra parameters raise variance. Noise σ² is a property of the data, not of the model. Select features, regularise, or collect more students.
What you can do now
Each outcome is ticked when the steps that teach it are done (solved, or worked answer viewed).
- Frame a learning problem as E, T and P, and tell true risk from training errorstep 1
- Build feature vectors and standardise them with training statisticsstep 2
- Compute an empirical risk and its least-squares minimiser by handsteps 3–4
- Derive and use the gradients of MSE and cross-entropysteps 5–6
- Contrast supervised and unsupervised learning and run k-meansstep 7
- Decompose test error into bias², variance and noisestep 8
- Update a reinforcement learner's value estimate from rewardsstep 9
- Decide what to freeze and what to retrain in transfer learningstep 10
- Quantify the curse of dimensionalitystep 11
- Apply the whole pipeline to a new casestep 12