Machine Learning · Week 1 · Lecture 1 · Introduction to Machine Learning · Interactive sheet · Advanced

The Introduction to Machine Learning Blueprint

A machine learns when its performance P on a task T improves with experience E, without anyone writing the rule by hand. Whether that experience comes as labels, as raw unlabelled data, as rewards, or as a model pre-trained on another task decides which kind of learning you are doing, and the number of features decides how much data you need.

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

Before you startWhat a table of data with rows and columns is, how to compute a distance between two points with Pythagoras, and the basic vocabulary of the field from the Intermediate page of this material (Intermediate level). Optional: Linear Regression for the regression ideas in section 05.

3
fields under Data Science
4
fruit features
5
RL components
2¹⁰ = 1,024
cells for 10 features
1959
'machine learning' named
01

Sorting fruit: the challenge that introduces machine learning

A packing line receives apples, bananas, oranges and mangoes on one belt; the lecture uses this single scenario to separate Data Science into its 3 fields. Click a field to see what it contributes.
Data Science umbrella · click a field100%
field

Pick one of the 3 fields on the left.

The headline

Data Science “uses Data Mining to discover hidden patterns, Machine Learning to build models, AI to make intelligent decisions”. Formally, mining describes a dataset D, learning chooses a function f ∈ 𝓗 from D, and AI turns f into an action a = π(s).

Timeline of the ideas on this page · click a chip

1957 1959 1997 1998 2015 2018
02

Walk one fruit through Data Mining, Machine Learning and AI

One mango travels through seven stages; the live state is its feature vector x ∈ ℝ⁴, the class centroids and the decision. Drag the scrubber, press play, or click a stage bead (arrow keys work).
Data Mining Machine Learning AI
stage100%
stage scrubber1
Model: nearest centroid, ŷ = argmin_c ‖x − μ_c‖.
stage
examples E
0
errors
0
nearest d
–
Quick check
The nearest-centroid model called the mango an apple at distance 0.26. After one labelled mango is added, a second mango x′ with ‖x′ − x_mango‖ = 0.05 arrives. Why is it now classified correctly?
The correction creates class “mango” with μ_mango = x_mango. The apple centroid did not move. For x′, ‖x′ − μ_mango‖ = 0.05 while ‖x′ − μ_apple‖ ≈ 0.26 ± 0.05, so argmin picks mango.
03

The ideas that make it work: features, labels, patterns and experience

Three ideas carry the whole lecture: a dataset of features with or without labels, patterns that separate the classes, and experience that improves performance.

1 Features and labels

2 Patterns (data mining)

x-axis
y-axis

3 Experience E improves P

labelled examples per class (E)3

Mitchell (1997). “A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E.” Card 3 is that sentence as a curve: T = sort fruit, P = test accuracy on 120 held-out fruit, E = labelled examples.

Quick check
Samuel's checkers program improved by playing thousands of games against itself. In Mitchell's terms, what is E?
T is playing checkers, P is the share of games won, and E is the self-play games. The rules are given, not learned, so they are not E.
04

The defining rule: learn from data, not from explicit programs

Machine learning “learns from data and improves without being explicitly programmed”. Compare a sorter whose thresholds a programmer typed in with one whose centroids are re-estimated from recent fruit, while the season shifts what an apple looks like.
season shift s (green apple varieties)0.0
recent labelled examples per class n10
measurement noise σ0.06
explicit: ŷ = rule(x)
learned: μ_c = (1/n_c) Σ_{yᵢ=c} xᵢ, θ* = argmin_θ (1/n) Σ L(f_θ(xᵢ), yᵢ)
explicitly programmed rule
–
test accuracy
if round < .50: banana
elif tex > .45: orange
elif color < .15: apple
else: unknown
learned from data
–
test accuracy
accuracy as the season shifts (0 → 1) · current s marked
Quick check
At s = 1 the hand-written rule falls far below the learned model. Which change to the rule fixes it permanently?
Editing the threshold fixes this season and breaks at the next one; the maintenance never ends. A learned model's parameters are a function of the data, so retraining on recent examples tracks the drift without new code.
05

Classify, regress or cluster: decide it by hand and by eye

One distance drives all three tasks: classification votes among the nearest labels, regression averages their values, and clustering groups points with no labels at all.

Worked example by hand: classify one fruit with k = 3 nearest neighbours

query fruit Q = (size 7 cm, texture 2) · 4 labelled fruit
Press Next step to compute the first distance.

For each labelled fruit: subtract feature by feature, square, add, take the square root. Then sort the distances and let the k = 3 nearest vote.

d(x, x′) = √( (x₁ − x′₁)² + (x₂ − x′₂)² ) · classify: ŷ = mode{yᵢ : i ∈ N_k(x)} · regress: ŷ = (1/k) Σ_{i∈N_k(x)} yᵢ · cluster: c(x) = argmin_j ‖x − μ_j‖
prediction
–
neighbours of the query100%
Quick check
With labels Spam (1), Not Spam (0) and k = 4, the four nearest emails split 2 vs 2. What is the standard remedy?
With two classes an odd k cannot tie. Distance-weighted voting (weight 1/dᵢ) also breaks ties in favour of the closer neighbours. Predicting 0.5 treats a class code as a quantity, which is the regression mistake above.
06

Where the rewards add up: State, Action, Reward and the cumulative reward

In reinforcement learning an agent acts in an environment and maximises the long-term cumulative reward, the return G₀ = Σ γᵗ Rₜ₊₁. Each bar is one step's discounted contribution; click it for the arithmetic.
100%
positive rewardnegative rewardterminal reward
discount factor γ0.90
click a bar

The (S, A, R, S') tuple and its discounted arithmetic appear here.

Return G₀

Shares of |contribution|

Worked example from the lecture: a child learning to ride a bicycle, in 6 steps

State (S): what the agent observes now
S = (speed slow, leaning left 10°, path straight)
Action (A): what the child chooses to do
A ∈ {pedal, steer left, steer right, brake}; chosen A = steer left into the lean
Reward (R): the environment's immediate feedback
R = +1 stayed balanced · falling would give R = −10
Next State (S'): where the action leads
S' = (speed slow, upright, path straight)
Policy (π): the rule mapping states to actions
π(leaning left) = steer left; π(upright) = pedal · π(a | s) may be a probability
Learning Process: exploration and exploitation
explore with probability ε (try braking, try looking ahead), exploit with 1 − ε: a = argmax_a Q(s, a)

The 5 components are S, A, R, S' and π; the sixth step is how π improves.

One Q-learning update

Q(S,A) ← Q(S,A) + α[R + γ·maxa'Q(S',a') − Q(S,A)]
learning rate α0.5
Quick check
Rewards R₁ = +1, R₂ = 0, R₃ = +10 with γ = 0.9. What is G₀ = R₁ + γR₂ + γ²R₃?
G₀ = 1 + 0.9·0 + 0.81·10 = 1 + 8.1 = 9.1. The undiscounted sum is 11; γ < 1 makes later rewards count less.
07

The family: supervised, unsupervised, reinforcement and transfer learning

The families differ in what the experience looks like: labelled pairs, unlabelled points, rewards for actions, or a model pre-trained on a related task. Click a row for its objective; load the first two into the walker.
family

Click a row above.

Transfer learning up close · click a block to freeze or fine-tune

trainable parameters
share of the whole model
Quick check
A ResNet-50 has a 2,048-value feature vector before its head. You freeze everything and add a new head for 5 fruit classes. How many parameters are trained?
A dense head has 2,048 × 5 weights + 5 biases = 10,245. Forget the biases and you get 10,240. Everything else stays frozen: about 0.04 % of the model is trained.
08

The cost and the limits: the curse of dimensionality

Every added feature multiplies the space the data must cover. The curse of dimensionality (Bellman, 1957) brings 4 problems: increased sparsity, higher computational cost, overfitting risk and distance-based issues. Move the drivers and watch all four.
features (dimensions) d10
ranges per feature r2
training examples n5,000
cells = rᵈ
P(cell empty) = (1 − r⁻ᵈ)ⁿ
edge for 10 % of data = 0.1^(1/d)
k-NN cost per query = O(n·d)
1 · increased sparsity
2 · higher computational cost
3 · overfitting risk
4 · distance-based issues
relative contrast (D_max − D_min) / D_min vs d · 300 random points100%
Quick check
10 features split into 2 ranges give 2¹⁰ = 1,024 cells and you have 5,000 examples. You add an 11th feature (also 2 ranges). How many examples keep the same average examples per cell?
2¹¹ = 2,048 cells, twice as many, so you need 2 × 5,000 = 10,000 examples for the same ≈ 4.9 per cell. The data needed grows exponentially with d, not linearly.
09

Apply it yourself: choose the right learning type and set up Anaconda

Answer four questions about a new problem and the decider names the family; then install Anaconda for the tutorial and run the reference implementation of the three supervised and unsupervised tasks.

The decider

lecture examples

Procedure for a new problem · tick as you go

  1. Write T, P and E (Mitchell): the task, the measure, the data that counts as experience.
  2. Check the data: is there a label column? Discrete (classes) or continuous (how much / how many)?
  3. Count features d against examples n; if rᵈ ≫ n, select or reduce features first (section 08).
  4. Standardise numeric features so no unit (cm vs 0–1) dominates the distance.
  5. Hold out a test set before any fitting; report P only on it.
  6. Start with a simple baseline (k-NN, linear regression, k-means), then consider a pre-trained model.

Tutorial preparation: install Anaconda

Download the installer for your system from docs.anaconda.com/anaconda/install/, install it, then open Anaconda Prompt (Windows) or a terminal (macOS / Linux):

shell
# one environment for the course
conda create -n cds6354 python=3.11 -y
conda activate cds6354
conda install scikit-learn pandas matplotlib jupyter -y
jupyter notebook   # opens in the browser

Reference implementation (scikit-learn)

python
import numpy as np
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# classification: links, "free" words -> Spam (1), Not Spam (0)
X = np.array([[8,7],[6,9],[9,5],[1,0],[2,1],[0,2]])
y = np.array([1, 1, 1, 0, 0, 0])
clf = KNeighborsClassifier(n_neighbors=3).fit(X, y)
print(clf.predict([[5, 4]]))          # -> [1]

# regression: air-con hours, people -> monthly bill (how much)
Xr = np.array([[2,2],[4,3],[6,4],[8,4],[3,1]])
yr = np.array([80, 130, 190, 240, 70])
reg = KNeighborsRegressor(n_neighbors=3).fit(Xr, yr)
print(reg.predict([[6, 3]]))          # mean of 3 neighbours

# clustering: no labels; humans name the clusters later
F = StandardScaler().fit_transform(
      np.array([[8,1],[7,2],[8,7],[9,8],[19,2],[20,1]]))
km = KMeans(n_clusters=3, n_init="auto", random_state=0).fit(F)
print(km.labels_)                      # cluster ids, not names
Quick check
A shop wants to predict how many units of each product it will sell next month from two years of monthly sales. Which family and task?
Past months come with the true sales figure (labelled), and the target is a count on a numeric scale, “how many”, so it is regression.
10

From Samuel's checkers to BERT: a short history of machine learning

Each lane is one idea from the lecture; red points are the dates the lecture's concepts rest on. Click a point for the story: the field moved from hand-written rules to learned models, then to reusing learned models.
machine learning milestones, 1957–2018100%
click a point

Before → after · tap a card to flip

Quick check
What did Mitchell's 1997 definition add to Samuel's 1959 description of learning “without being explicitly programmed”?
Samuel's phrase says what is absent (hand-written rules). Mitchell's definition says what must be measured: a task, a performance measure and an amount of experience, so “does it learn?” becomes an experiment.
11

Where machine learning is used today

From the lecture's fruit-picking robot to self-driving cars, each application combines families. Click a row for the family, the data and what came next.
Families: supervised (classify ripe vs unripe from images), AI decision and control (where to grip), often transfer learning from an ImageNet model such as ResNet. Next: grippers trained with reinforcement learning in simulation, then fine-tuned on real orchards.
Family: supervised classification with labels Spam (1), Not Spam (0); every “report spam” click is a new labelled example (experience E). Next: pre-trained language models fine-tuned to spot phishing wording that keyword rules miss.
Families: supervised perception (label every pedestrian and lane in millions of frames), reinforcement learning for planning in simulators, transfer learning to new cities. Limit: camera, lidar and radar give thousands of features per frame; the curse of dimensionality is why perception relies on huge labelled datasets and pre-trained backbones.
Family: unsupervised clustering of purchase histories; analysts name the clusters afterwards (“bargain hunters”), just as humans name fruit clusters. Next: learned embeddings that place similar customers and products close together.
Family: transfer learning: BERT (2018) is pre-trained on unlabelled text, then fine-tuned with a few thousand labelled examples for sentiment, question answering or search ranking. Next: much larger pre-trained models, adapted with reinforcement learning from human feedback.
Family: reinforcement learning, the direct descendant of Samuel's 1959 checkers player: states, actions, rewards and a policy improved by self-play. Next: the same ideas schedule data-centre cooling and robot locomotion.
Quick check
A car maker's pedestrian detector, trained on 2 million labelled frames from Europe, must work in Kuala Lumpur with only 5,000 labelled local frames. What is the sensible plan?
Same task, related data, few labels: transfer learning. The lower layers (edges, shapes, people) transfer; fine-tuning a few layers adapts to local streets without overfitting 5,000 frames.
12

Key takeaways

Eight lines to remember from Week 1. Click each for the evidence on this page.
One fruit, three outputs: a description (“apples are usually red and smooth”), a model (nearest centroid), an action (put it in the mango bin). Sections 01–02.
Mitchell (1997): P on T improves with E. The learning algorithm is code; the decision rule is fitted from data and re-fitted when the data drifts. Sections 03–04.
Spam (1), Not Spam (0) and Cat (1), Dog (2), Bird (3), Fish (4) are class codes, not quantities; a monthly bill is a quantity. Section 05.
k-means minimises Σ‖xᵢ − μ_c(i)‖² over assignments and centroids; the cluster ids carry no names. Sections 02, 05.
G₀ = Σ γᵗ Rₜ₊₁; Q-learning nudges Q(S,A) toward R + γ max Q(S',·); exploration vs exploitation balances trying and using. Section 06.
A frozen ResNet-50 plus a 5-class head trains 10,245 parameters instead of about 25.6 M. Section 07.
Sparsity, computational cost, overfitting risk, distance-based issues; 2¹⁰ = 1,024 cells for 10 binary-split features, and nearest and farthest neighbours converge. Section 08.
Labels? Discrete or continuous? Rewards? A related pre-trained model? Section 09.
13

Check your understanding

Five calculation and what-if questions with instant feedback. Score 4 or more for the stamp. Click a dot to jump to a question.
0 / 5
■ STAMPED · INTRO TO ML BLUEPRINT · ADVANCED
14

Glossary

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