Machine Learning · Topic 1 · Introduction to Machine Learning · Guided tutorial · Advanced

Introduction to Machine Learning: learn it by doing it

By the end you will state a learning problem as E, T and P, build and standardise features, minimise and differentiate an empirical risk by hand, score probabilities with cross-entropy, run k-means, split test error into bias², variance and noise, update a value from rewards, decide what to retrain in transfer learning, and put a number on the curse of dimensionality.

Before you startLeast-squares fitting of a line, derivatives of a sum (chain rule), expectation and variance, vectors with the dot product and Euclidean distance. The theory of every step is on the Blueprint page; the basics are in the Intermediate tutorial.
12
steps, one idea each
≈ 55 min
estimated time
✎
you need: pen and paper
1
running example: one course cohort
01

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.

In plain wordsA program learns when a number you fixed in advance gets better as it sees more examples. Basics: Intermediate tutorial, step 1.
Explain

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.

R(f) = 𝔼[ℓ(f(X), Y)]  ·  R̂ₙ(f) = (1/n) Σᵢ ℓ(f(xᵢ), yᵢ)
x
(hours studied, hours slept)
y
passed ∈ {0, 1}
n
200 past students
Try it

Match each part of the pass-predictor to its role.

(a) the 200 past records, each with its pass/fail outcome
(b) predicting pass or fail for a student who has not sat the exam
(c) the share of next semester's students it predicts correctly
(d) the columns “hours studied” and “hours slept”
(e) the share of the 200 past students it classifies correctly
02

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.

In plain wordsMeasure every column in “how unusual is this” units so no column wins just because its numbers are bigger. Basics: Intermediate tutorial, step 2.
Explain

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:

zⱼ = (xⱼ − μⱼ) ÷ σⱼ

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.

featuremean μstd σ
x₁ hours studied / week62
x₂ hours slept / night71
Try it

Aisha studied 9 h a week and slept 5 h a night. Give her standardised vector z = (z₁, z₂), to 2 decimals (±0.01).

no unit (std. deviations)
no unit (std. deviations)
03

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.

In plain wordsScore a rule by how far each prediction misses, squared, then averaged. Basics: Intermediate tutorial, step 3.
Explain

For regression with squared loss ℓ(ŷ, y) = (y − ŷ)², the empirical risk is the mean squared error:

MSE(w, b) = (1/n) Σᵢ (yᵢ − (w xᵢ + b))²

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.

(2, 50)(4, 60)(6, 76) ŷ = 5x + 40r² x (h)y
Try it

Data (2, 50), (4, 60), (6, 76). Compute the MSE of ŷ = 5x + 40 (exact; ±0.01).

xᵢyᵢŷᵢrᵢrᵢ²
250???
460???
676???
points²
04

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.

In plain wordsSet the slope of the error to zero in both directions and the best line drops out. Basics: Intermediate tutorial, step 4.
Explain

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

w* = Sxy ÷ Sxx = Σ(xᵢ − x̄)(yᵢ − ȳ) ÷ Σ(xᵢ − x̄)²  ·  b* = ȳ − w* x̄

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
Try it

Same three students (2, 50), (4, 60), (6, 76). Fill in the blanks (±0.01).

h
points
points per hour
points
05

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.

In plain wordsThe gradient says which way and how steeply the error rises; step the other way. Basics: Intermediate tutorial, step 5.
Explain

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:

∂MSE/∂w = −(2/n) Σ xᵢ rᵢ  ·  ∂MSE/∂b = −(2/n) Σ rᵢ

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.

Common mistakeForgetting the xᵢ weight (that gives ∂/∂b) or the minus sign (the gradient then points uphill and the step makes the fit worse).
Try it

At the guess w = 5, b = 40 (residuals 0, 0, 6 from step 3), what is ∂MSE/∂w?

06

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.

In plain wordsTurn a score into a probability, then charge the model more the less probability it gave to what really happened. Basics: Intermediate tutorial, step 6.
Explain

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:

ℓ = −[ y ln p + (1 − y) ln(1 − p) ]

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.

sp = 10.5
Try it

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)

nats
07

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.

In plain wordsWith no answers given, group what lies close together and let the groups' centres settle. Basics: Intermediate tutorial, step 7.
Explain

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

J(c, μ) = Σᵢ ‖xᵢ − μ_c(i)‖²

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()
Try it

Put one run of k-means on the unlabelled students in order (use ↑ ↓; each button is keyboard operable).

  1. 1Choose k and place k initial centroids μ₁…μₖ (e.g. k random students)
  2. 2Assign each student to the nearest centroid: c(i) ← argminₖ ‖zᵢ − μₖ‖²
  3. 3Move each centroid to the mean of its students: μₖ ← mean{zᵢ : c(i) = k}
  4. 4Recompute the inertia J — it cannot have increased
  5. 5Stop if no assignment changed; otherwise return to the assignment step
08

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.

In plain wordsA model misses because it is too rigid, because it changes with every sample, or because the data are noisy — and only the first two are yours to fix. Basics: Intermediate tutorial, step 8.
Explain

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):

𝔼[(y − f̂)²] = (f − f̄)² + 𝔼[(f̂ − f̄)²] + σ² = bias² + variance + noise

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.

bias²variancenoise σ²test errorcapacity M →
Try it

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?

09

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.

In plain wordsWhen nobody can give the answers, try actions, keep a running average of what each one earned, and mostly pick the best so far. Basics: Intermediate tutorial, step 9.
Explain

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:

Q_{N+1}(a) = Q_N(a) + (1 ÷ (N + 1))·( r − Q_N(a) )

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.

Try it

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).

0.30
10

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 plain wordsReuse what another model already learned and retrain only the part that is specific to your problem. Basics: Intermediate tutorial, step 10.
Explain

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

Try it

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.

Input layer2 standardised features Hidden block 1general patterns · frozen? Hidden block 2general patterns · frozen? Hidden block 3source-specific patterns Output headsigmoid · P(pass) at the partner
11

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.

In plain wordsEach new feature multiplies the room the data must fill, so the same number of students becomes thinly spread and “nearby” stops meaning anything. Basics: Intermediate tutorial, step 11.
Explain

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

e_d(r) = r^(1/d)

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.

dedge for r = 10 %
110 %
232 %
346 %
5?
1079 %
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…
Try it

With d = 5 features, what share of each axis must a sub-cube span to hold 10 % of the students? (in %, ±1)

% of each axis
12

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.

In plain wordsGo from a raw record to a prediction, its cost, its gradient, and a judgement about the data — the whole pipeline once. Basics: Intermediate tutorial, step 12.
Explain

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
Try it

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).

nats

The gradient ∂ℓ/∂b on Ben.

The department proposes 18 more columns (d = 20) for the same 200 students. Best judgement?

✓

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
Score · solved without the answer
0 / 12

0 steps done