Step 1 of 11 · 0 done
Machine Learning · Week 1 · Lecture 1 · Introduction to Machine Learning · Guided tutorial · Advanced

Introduction to Machine Learning: learn it by doing it

By the end you will place any fruit-line job in Data Mining, ML or AI, formalise learning as T, P and E, classify, regress and cluster by hand, compute an RL return and a Q-update, count a fine-tuned head and quantify the curse of dimensionality.

11
steps
60 min
estimated time
✎
you need: pen and paper

Before you startKnow what a table of data with rows and columns is, how to compute a distance with Pythagoras, and the vocabulary of the Intermediate level (Intermediate tutorial). The full theory, with derivations, is on the Blueprint page.

Your route · one packing line, eleven steps
supervisedunsupervisedreinforcement
01

Assign each job on the packing line to its field

⏱ 4 minData Science
Explain

Our running example: one packing line where apples, bananas, oranges and mangoes arrive on a single belt. Data Science is the umbrella over 3 fields: it “uses Data Mining to discover hidden patterns, Machine Learning to build models, AI to make intelligent decisions”. Data Mining reads the records and returns a description, such as “Apples are usually red and smooth” or “Bananas are yellow and cylindrical”. Machine Learning returns a model: it learns from past sorting mistakes, so a mango wrongly identified as an apple is corrected next time. AI returns a decision: it sees, recognises and sorts the fruit, answering “Which fruit is this?”, like a robot picking apples and oranges.

mining: D ↦ patterns  ·  learning: D ↦ f ∈ 𝓗  ·  AI: s ↦ a = π(s), using f

In plain wordsOne clerk keeps the records, one learns the trade, one runs the belt (basics: Intermediate step 1).

The Data Science umbrella DATA SCIENCE Data Miningfinds patterns Machine Learningbuilds a model AImakes decisions a descriptionf: x ↦ ŷa = π(s) one fruit belt · three different outputs
Try it · match

For each job on the packing line, choose the field whose output it is.

aIn last year's records, find that “Bananas are yellow and cylindrical”.
bA mango was wrongly identified as an apple; the corrected example changes how the next mango is sorted.
cA robot arm sees a fruit, answers “Which fruit is this?” and drops it into the orange crate.
dChoose a function f that maps colour, shape, size and texture to a fruit type, with the fewest errors on 500 labelled fruit.
02

Name T, P and E for the learning sorter

⏱ 5 mindefinition
Explain

Machine learning “learns from data and improves without being explicitly programmed”. Arthur Samuel (IBM) popularised the term in 1959 with a checkers program that improved by playing itself; in 1957 Frank Rosenblatt had described the perceptron, whose weights are learned rather than typed in. Tom Mitchell's 1997 definition makes the idea testable: a program learns from experience E on tasks T, measured by performance P, if P improves with E.

An explicitly programmed sorter has thresholds a programmer typed in; they never change. A learned sorter chooses its parameters θ from data, so more or newer examples change θ* without anyone editing code. The learning algorithm is still a program; what is not hand-written is the decision rule.

explicit: ŷ = rule(x)  (fixed)
learned: θ* = argminθ (1/n) Σᵢ L(fθ(xᵢ), yᵢ),   ŷ = fθ*(x)

In plain wordsA printed map stays as printed; a navigator re-plans when the roads change (basics: Intermediate step 2).

Mitchell (1997) on the fruit line E · labelled fruit seen → P · share sorted correctly T = sort the belt intoapple · banana · orange · mango P improves with E
Try it · choose one

Suppose the sorter is retrained every week. In week 1 it has seen 200 labelled fruit and sorts 82% of a fixed test belt correctly; in week 3 it has seen 600 and sorts 91%. Its code never changed. Which line names T, P and E correctly?

03

Split the fruit table into features x and label y

⏱ 4 minsupervised
Explain

Supervised learning starts from labeled data, a set of pairs D = {(xᵢ, yᵢ)}, i = 1…n. Each row i is one fruit. Its inputs, the features, form the feature vector xᵢ = (color, shape, size, texture): the 4 features the lecture uses for data mining and clustering, so xᵢ ∈ ℝ⁴ once each is coded as a number. Its output, the label yᵢ, is the “Fruit Type” column. Learning finds f that maps inputs to outputs, f(xᵢ) ≈ yᵢ, so it can label a new fruit. The label is never an input: a new fruit arrives without it (feeding it in is called target leakage). Delete the “Fruit Type” column and the table becomes unlabeled data.

D = {(xᵢ, yᵢ)}i=1…n,   xᵢ ∈ ℝ⁴,   yᵢ ∈ 𝒴 = {apple, banana, orange, mango},   f: ℝ⁴ → 𝒴

In plain wordsFeatures are the measurements, the label is the answer you want (basics: Intermediate step 3).

Three rows of the fruit table
icolorshapesizetextureFruit Type
1redroundmediumsmoothapple
2yellowcylindricallongsmoothbanana
3orangeroundmediumdimpledorange
Try it · fill in the blanks

Complete the description of the table.

The columns color, shape, size and texture of row i form ; the “Fruit Type” column is ; so xᵢ ∈ ℝ. If the “Fruit Type” column is deleted, the same table is data for learning.

04

Classify the mango with the nearest centroid

⏱ 6 min · pen and papersupervised · classification
Explain

Classification predicts a discrete label. The simplest learned classifier stores one centroid per class, the mean of its labelled examples, and gives a new fruit the label of the nearest one, using the Euclidean distance. To work by hand we keep 2 of the 4 features: size (cm) and roundness (0 = long, 10 = round). Centroids learned from the history: apple μ = (8, 9), orange μ = (7, 10), banana μ = (18, 2). There is no mango class yet. Because cm and a 0–10 score have different scales, real systems standardise features first so that one feature does not dominate the distance.

μc = (1/nc) Σyᵢ=c xᵢ  ·  d(x, μ) = √( Σⱼ (xⱼ − μⱼ)² )  ·  ŷ = argminc d(x, μc)

In plain wordsCall the new fruit whatever it most resembles on average (basics: Intermediate step 4).

import numpy as np

def fit_centroids(X, y):
    # mu_c = mean of the rows of X labelled c
    return {c: X[y == c].mean(axis=0) for c in np.unique(y)}

def predict(x, mu):
    # y_hat = argmin_c ||x - mu_c||
    return min(mu, key=lambda c: np.linalg.norm(x - mu[c]))

mu = {"apple": np.array([8, 9]), "orange": np.array([7, 10]),
      "banana": np.array([18, 2])}
print(predict(np.array([11, 7]), mu))
Centroids and the new mango 05101520 0510 size (cm) roundness apple μ orange μ banana μ mango x = (11, 7) d = ?
Try it · type a number

A mango arrives with x = (11, 7). Compute its Euclidean distance to the apple centroid μ = (8, 9).

Give 2 decimals · accepted within ±0.01 · unit: feature units

feature units
05

Sort the questions into classification and regression

⏱ 4 minsupervised · 2 types
Explain

Supervised learning has 2 types, told apart by the output. Classification predicts discrete labels: Spam (1), Not Spam (0) in email spam detection, or Cat (1), Dog (2), Bird (3), Fish (4) in animal classification. Regression predicts continuous values: “how much” (a monthly electricity bill) or “how many” (products sold). The numbers in a class code are names, not quantities, so the losses differ: classification counts mistakes (0–1 loss, or cross-entropy on probabilities), regression measures a distance such as the squared error. With k neighbours, classification takes the mode, regression the mean. Averaging Cat (1) and Bird (3) into Dog (2) is the classic error.

classification: ŷ = mode{yᵢ : i ∈ Nk(x)},   L = 1[ŷ ≠ y]
regression: ŷ = (1/k) Σi∈Nk(x) yᵢ,   L = (y − ŷ)²

In plain wordsIf averaging two answers makes sense it is regression, otherwise classification (basics: Intermediate step 5).

Two outputs of supervised learning classification · discrete Cat (1) Dog (2) Bird (3) Fish (4) regression · continuous (how much / how many) ŷ = any value on the scale
Try it · classify each question

The packing house wants to answer six questions with supervised learning. Mark each one.

06

Run one clustering step without labels

⏱ 6 min · pen and paperunsupervised · clustering
Explain

Unsupervised learning receives the same fruit without the “Fruit Type” column. Clustering groups the fruit by their features (color, shape, size, texture); humans assign the labels later (“this group is mangoes”). The k-means method alternates two steps: assign each point to its nearest centre, then update each centre to the mean of its points. Each step can only lower the objective J, so k-means stops after finitely many steps, though possibly in a local minimum that depends on the starting centres.

assign: c(i) = argminj ‖xᵢ − μⱼ‖  ·  update: μⱼ = (1/|Cⱼ|) Σi∈Cⱼ xᵢ
J = Σᵢ ‖xᵢ − μc(i)‖²   (never increases)

In plain wordsPut each fruit with the nearest pile, then move each pile's marker to its middle (basics: Intermediate step 6).

Same fruit, no “Fruit Type” column
pointsizeroundness
P179
P298
P3127
P4163
P5192
P6144

Starting centres: μA = (8, 8), μB = (17, 3)

Try it · click the diagram

Do the assignment step: select every fruit that joins cluster A (nearest to μA).

Click a point, or Tab to it and press Enter or Space · selected points show ✓

05101520 0510 size (cm) roundness
07

Your turn: frame the robot picker as reinforcement learning

⏱ 8 min · pen and paperYour turn · 2 partsreinforcement
Explain

Reinforcement learning has no answer key. An agent acts in an environment, receives positive or negative rewards, and learns to maximise the long-term cumulative reward. Its 5 key components: State (S), what the agent observes; Action (A), what it does; Reward (R), the immediate feedback; Next State (S'), where the action leads; Policy (π), the rule from states to actions. Formally the agent maximises the expected return, with a discount 0 ≤ γ < 1 so later rewards count less and the sum stays finite. This is the framing of Sutton and Barto's 1998 textbook “Reinforcement Learning: An Introduction”. The lecture's worked example, a child learning to ride a bicycle, has 6 steps.

G₀ = R₁ + γR₂ + γ²R₃ + … = Σt≥0 γᵗ Rt+1  ·  goal: π* = argmaxπ 𝔼π[G₀]

In plain wordsLearn by trial and error which moves pay off over the whole ride, not just now (basics: Intermediate step 7).

The agent–environment loop AGENTpolicy π ENVIRONMENT action A reward R · next state S' state S
Try it · two parts

aPut the 6 steps of the bicycle example in order

Use ↑ and ↓ (keyboard: Tab to a button, Enter)

    bCompute the robot picker's return

    On our packing line a robot arm is the agent. In one short episode it gets R₁ = +1 (picks an apple cleanly), R₂ = −1 (bruises an orange) and R₃ = +10 (fills the crate). The discount is γ = 0.9. Compute G₀.

    Give 2 decimals · accepted within ±0.01 · unit: reward points

    reward points
    08

    Update the robot's Q-value after one try

    ⏱ 5 minreinforcement · policy
    Explain

    How does the policy π improve? The agent keeps a value Q(S, A): the return it expects after action A in state S. With probability ε it explores (tries a random action, such as a softer grip); otherwise it exploits, taking the action with the highest Q. After each step (S, A, R, S') it moves Q toward a one-step target. Rewriting the update shows why it works: the new Q is a weighted average of the old estimate and the new evidence, with the learning rate α as the weight. This is Q-learning.

    act: a = argmaxa Q(S, a) with prob. 1 − ε, random with prob. ε
    target = R + γ · maxa' Q(S', a')
    Q(S, A) ← Q(S, A) + α [target − Q(S, A)] = (1 − α) Q(S, A) + α · target

    In plain wordsMove your guess part of the way toward what just happened plus what you expect next (basics: Intermediate step 8).

    import random
    
    def act(Q, s, eps=0.1):
        if random.random() < eps:              # explore
            return random.choice(list(Q[s]))
        return max(Q[s], key=Q[s].get)          # exploit: argmax_a Q(s, a)
    
    def q_update(Q, s, a, r, s_next, alpha=0.5, gamma=0.9):
        target = r + gamma * max(Q[s_next].values())
        Q[s][a] += alpha * (target - Q[s][a])
        return Q[s][a]
    One update as a weighted average old Q target α of the gap new Q = ?
    Try it · predict with the slider

    The robot is in S = “orange at the edge of the belt” with Q(S, grip gently) = 2.0. It grips gently, gets R = +1 and reaches S', where the best value is maxa' Q(S', a') = 4.0. With α = 0.5 and γ = 0.9, set the slider to the new Q(S, grip gently).

    2.0 your prediction
    036
    09

    Count what you train when fine-tuning a pre-trained model

    ⏱ 5 mintransfer learning
    Explain

    Transfer learning reuses what a model learned on one task for a related task, the way someone who speaks Spanish learns Italian faster. You start from a pre-trained model: ResNet (He et al.), which won ImageNet in 2015, for images, or BERT (Devlin et al., Google), released in 2018, for language (NLP). To fine-tune, keep the pre-trained weights θ₀ and update only a few layers instead of training from scratch: usually a new output head and, optionally, the top block, with a small learning rate. A dense head from a d-value feature vector to K classes has d × K weights plus K biases. ResNet-50's final feature vector has 2,048 values; the whole network has about 25.6 million parameters.

    head parameters = d · K + K  ·  fine-tune: θ = θ₀ − η ∇L on the unfrozen layers only (small η)

    In plain wordsKeep the trained eyes, teach only the new names (basics: Intermediate step 9).

    ResNet-50 for the fruit line
    stem + stage 1edges, coloursfrozen
    stages 2–3textures, partsfrozen
    stage 4 + pool2,048-value feature vectorfrozen
    new head2,048 → 4 fruit typestrain
    Try it · choose one

    You freeze all of ResNet-50 and add a new dense head for the 4 fruit types (apple, banana, orange, mango). How many parameters does fine-tuning train?

    10

    Predict how empty the feature space becomes

    ⏱ 5 minlimits
    Explain

    Every added feature multiplies the space the data must fill. Richard Bellman introduced the term curse of dimensionality in 1957 (Dynamic Programming). Split each feature into just 2 ranges: d features give 2ᵈ cells, so the number of regions doubles with every added dimension, and 10 features give 2¹⁰ = 1,024. The lecture names 4 problems: (1) increased sparsity, as the same examples spread over far more cells; (2) higher computational cost, since each distance needs d terms and keeping the same density needs data growing like 2ᵈ; (3) overfitting risk, as few examples per region let a model fit noise; (4) distance-based issues: in k-NN and clustering “all points appear equally distant”.

    cells = 2ᵈ  ·  2⁴ = 16,  2¹⁰ = 1,024  ·  (dmax − dmin) / dmin → 0 as d grows

    In plain wordsThe same crowd in a much bigger building leaves most rooms empty (basics: Intermediate step 10).

    2 ranges per feature d = 12 cells d = 24 cells d = 38 cells d = 102¹⁰ = 1,024 × 2 with every added dimension
    Try it · predict with the slider

    The packing house has 64 labelled fruit. With the 4 features and 2 ranges each, the 2⁴ = 16 cells hold 4 fruit each on average. Engineers add 6 sensor readings, giving 10 features and 2¹⁰ = 1,024 cells. Predict the largest possible share of cells that contain at least one fruit.

    50.00 % your prediction
    0 %50 %100 %

    accepted within ±1 percentage point

    11

    Put it all together: plan the packing line's system

    ⏱ 8 mincapstone
    Explain

    A real project combines everything. Decide from the experience you have: labelled pairs (xᵢ, yᵢ) → supervised (a label → classification, a quantity → regression); points without a label column → unsupervised clustering; rewards for actions → reinforcement learning; a related pre-trained model plus little data → transfer learning. A description of past data is Data Mining; acting on a trained model is AI. Then check the cost: every added feature doubles the cells to fill.

    In plain wordsFirst ask what kind of data you have, then what kind of answer you need (basics: Intermediate step 11).

    Decide by the experience
    you haveuse
    (xᵢ, yᵢ), y a labelclassification
    (xᵢ, yᵢ), y a quantityregression
    xᵢ onlyclustering
    (S, A, R, S')reinforcement
    θ₀ + little datatransfer
    Try it · capstone

    Part A: choose the right approach for each job. Part B: name the problem.

    BThe team adds 6 sensor readings (10 features) and the nearest-centroid sorter now finds each fruit almost equally far from every centroid. Which problem of the curse of dimensionality is this?
    ✓

    What you can do now

    outcomes tick as their steps are done
      Score · solved without the worked answer
      0 / 11