Level 3 In-Depth AI · Classical Machine Learning
Supervised Learning
Learning from examples that come with the right answers. You show the computer inputs paired with the answers you want, it finds a rule that maps one to the other, and then it applies that rule to inputs it has never seen.
- Level
- ●●●●● Beginner
- Reading
- 13 min
- To learn it well
- 40 minutes to read, an hour to practise
- Builds on
- 3 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 3 concepts before this one
Read them roughly in this order. See it on the concept map →
Why it matters
Most of the AI that earns money today is supervised learning: learning a rule from examples that come with the correct answer attached. A bank shows a model a million past card payments, each marked "fraud" or "fine", and the model learns to flag new payments. A hospital shows a model thousands of X-rays, each with a radiologist's diagnosis, and the model learns to spot the same patterns. An email provider learns spam filtering from messages that users marked as spam. A house-price website learns prices from past sales.
Even large language models start this way. During Pretraining Large Language Models, a model like GPT reads text and tries to predict the next word, and the "correct answer" is simply the word that actually came next. Nobody labelled it by hand, but the setup is the same: input, wanted output, adjust the model until it gets them right. That is why this chapter matters so much. Its vocabulary (features, labels, model, loss, training, prediction) and its recipe are reused in almost every chapter that follows, from Linear Regression to Neural Networks and transformers.
The intuition
Think of how a child learns to tell cats from dogs. Nobody gives the child a rulebook ("cats have retractable claws and a vertical pupil…"). Instead, an adult points: "cat", "dog", "dog", "cat". After enough examples the child has formed their own internal rule, and can name an animal they have never seen before.
Supervised learning works the same way. You collect examples, and each one has two parts:
- Features: the information you have about the example. These are the inputs, usually written . For a house: its floor area, number of bedrooms, postcode, year built.
- The label: the answer you want the model to give, usually written . For a house: the price it sold for. Some people call it the target.
The word "supervised" comes from the labels. They act like a teacher who checks each answer. The algorithm makes guesses, compares them with the labels, and adjusts itself to make better guesses. Once it is trained, you give it only the features of a new example and it produces a prediction, written ("y-hat"). The hat means "estimated".
There are two big families of supervised task, and the difference is just what kind of thing the label is:
- Regression: the label is a number on a continuous scale. House price, tomorrow's temperature, how many minutes a delivery will take.
- Classification: the label is one of a fixed set of categories. Spam or not spam, which of 1,000 objects is in a photo, which digit someone wrote.
Key idea Supervised learning = learn a function from examples of inputs paired with correct outputs, so that it gives correct outputs for new inputs. Regression predicts a number. Classification predicts a category.
The last part of that definition is the important one. A model that only reproduces the answers it was shown is useless: you already know those answers. The whole goal is generalisation: doing well on examples the model has never seen. Most of the craft of machine learning, and several chapters of this guide (Training, Validation and Test Sets, Overfitting and the Bias–Variance Tradeoff, Regularization: L1 and L2, Cross-Validation), is about getting and measuring generalisation.
How it works
The data as a table
Supervised data is almost always arranged as a table. Each row is one example. Each column but the last is one feature. The last column is the label.
| Floor area (m²) | Bedrooms | Distance to station (km) | Price (£1000s) |
|---|---|---|---|
| 54 | 1 | 0.4 | 210 |
| 88 | 3 | 2.1 | 265 |
| 120 | 4 | 5.0 | 310 |
In maths, the features of example form a vector , where is the number of features (here 3). Stacking all rows gives a matrix with rows and columns. The labels form a vector of length . When you see X (capital) and y (lower case) in code, that is what they mean. Images, sound and text fit this picture too: an image's features are its pixel values, and text is turned into numbers by Tokenization and embeddings.
The model is a function with knobs
A model is a function that takes features and returns a prediction. Classical textbooks call the function a hypothesis, written , because it is the algorithm's current guess about how depends on . Every model has parameters, adjustable numbers that change what the function does, collected as ("theta"). We write the model as:
Read it as: the prediction is the model applied to the features, using parameters θ. The semicolon separates the input (which changes from example to example) from the parameters (which are the same for every example and are what training adjusts).
The simplest useful model is a straight line with one feature:
It has two parameters: the weight (the slope: how much rises when goes up by 1) and the bias (the intercept: the prediction when ). A neural network is the same idea with millions or billions of parameters and a far more flexible shape.
Before training you also choose the kind of function: a line, a decision tree, a neural network. That choice is part of the design and is fixed. Training only searches within that family for the best parameters.
Measuring wrongness: the loss
To improve the parameters you need a single number that says how wrong the model currently is. That number is the loss (see Loss Functions). For regression the classic choice is the mean squared error: for each example, take the error , square it so that misses in either direction count as bad, and average over all examples:
For classification the usual loss is cross-entropy, which punishes the model for being confident and wrong.
Training is fitting
Training (also called fitting) means finding parameter values that make the loss on the training examples small. For a line there is a formula (Linear Regression). For most models you use Gradient Descent: compute how the loss changes as you nudge each parameter, step downhill, repeat.
A worked example by hand
Four students practised for 1, 2, 3 and 4 hours and scored 3, 5, 7 and 8 out of 10 on a test. Feature = hours, label = score. We will try two hypotheses and let the loss decide which is better.
Hypothesis A: (so , ).
| error | error² | |||
|---|---|---|---|---|
| 1 | 3 | 3 | 0 | 0 |
| 2 | 5 | 4 | −1 | 1 |
| 3 | 7 | 5 | −2 | 4 |
| 4 | 8 | 6 | −2 | 4 |
Mean squared error: .
Hypothesis B: (so , ).
| error | error² | |||
|---|---|---|---|---|
| 1 | 3 | 3.2 | +0.2 | 0.04 |
| 2 | 5 | 4.9 | −0.1 | 0.01 |
| 3 | 7 | 6.6 | −0.4 | 0.16 |
| 4 | 8 | 8.3 | +0.3 | 0.09 |
Mean squared error: .
B's loss is 30 times smaller, so B fits the data far better. In fact is the best possible line for these four points: no other line has a lower mean squared error. Training is the process that finds it automatically. Now the model is useful: a student who practises for 4.5 hours is predicted to score .
The recipe every chapter follows
Every supervised method in this guide is a variation on the same loop.
- Collect labelled data and turn it into a feature matrix and label vector (Data Cleaning and Preparation, Feature Engineering).
- Hold some of it back so you can later test on examples the model never saw (Training, Validation and Test Sets).
- Choose a model family: line, tree, forest, neural network.
- Choose a loss that measures what you care about (Loss Functions).
- Fit: adjust the parameters to lower the loss on the training data, usually with Gradient Descent.
- Evaluate on the held-back data with a metric that matches the real goal (Evaluation Metrics).
- Iterate: try other features, models and settings (Hyperparameter Tuning), and when you are happy, deploy the model (Deploying Models).
Using a trained model on new data is called inference or prediction. Training can take hours or months. Inference is usually fast: milliseconds for a small model.
In code
First, from scratch. We "train" by trying every line on a grid of slopes and intercepts and keeping the one with the lowest loss. Real algorithms are smarter, but the idea (search for parameters that minimise the loss) is exactly the same.
import numpy as np
# Four training examples: hours of practice -> test score (out of 10)
x = np.array([1.0, 2.0, 3.0, 4.0]) # feature
y = np.array([3.0, 5.0, 7.0, 8.0]) # label
def mse(w, b):
pred = w * x + b # hypothesis h(x) = w*x + b
return np.mean((pred - y) ** 2)
# "Training" as brute-force search over candidate parameters
best = None
for w in np.arange(0, 4.01, 0.1):
for b in np.arange(-2, 4.01, 0.1):
loss = mse(w, b)
if best is None or loss < best[0]:
best = (loss, w, b)
loss, w, b = best
print(f"best w={w:.1f} b={b:.1f} loss={loss:.3f}")
print("prediction for 5 hours:", round(w * 5 + b, 2))
# best w=1.7 b=1.5 loss=0.075
# prediction for 5 hours: 10.0
In practice you use scikit-learn. Every model in that library has the same two methods: fit(X, y) to train and predict(X) to use. Here are a regression and a classification problem on two small medical datasets that ship with the library:
from sklearn.datasets import load_diabetes, load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# Regression: predict disease progression (a number) from 10 measurements
X, y = load_diabetes(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
reg = LinearRegression().fit(X_tr, y_tr) # training = fitting
print(X.shape, "->", reg.predict(X_te[:3]).round(1))
print("R^2 on unseen data:", round(reg.score(X_te, y_te), 3))
# Classification: predict malignant (0) or benign (1) from 30 measurements
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
clf = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
print(X.shape, "->", clf.predict(X_te[:10]))
print("accuracy on unseen data:", round(clf.score(X_te, y_te), 3))
# (442, 10) -> [241.8 250.1 165. ]
# R^2 on unseen data: 0.359
# (569, 30) -> [0 1 1 1 1 1 1 1 1 1]
# accuracy on unseen data: 0.958
The shapes tell the story: 442 patients with 10 features each, and 569 tumours with 30 features each. Both models are judged on a quarter of the data that was hidden during training. The classifier is right on 95.8% of the unseen tumours. The regression's of 0.36 means it explains about a third of the variation in disease progression: useful, but far from perfect. Evaluation Metrics explains both scores.
Common pitfalls
- Testing on the training data. A model can score perfectly on examples it has memorised and fail on new ones. Always evaluate on held-out data. See Training, Validation and Test Sets and Overfitting and the Bias–Variance Tradeoff.
- Labels that are wrong or inconsistent. The model learns whatever the labels say, including the mistakes. If two doctors would disagree on 10% of the X-rays, no model trained on their labels will reliably beat that.
- Features that won't exist at prediction time. If a feature is only known after the event you are predicting (say, "was the loan written off?" used to predict default), the model looks brilliant in testing and fails in use. This is called leakage. See Training, Validation and Test Sets.
- Extrapolating beyond the data. Our line predicts 10.0 for 5 hours of practice and would predict 11.7 for 6 hours, on a test marked out of 10. A model only knows the range it was trained on.
- The training data doesn't look like the real world. A model trained on photos from one hospital's scanner can stumble on another hospital's. The examples must represent the cases you will actually meet. When the world drifts after deployment, see Monitoring and Data Drift.
Watch out The model learns the patterns in the labels, not the truth you wished they captured. If past hiring decisions were biased, a model trained to predict them will be biased too. See Bias and Fairness.
Where it leads
The chapters that follow fill in each step of the recipe:
- Models: Linear Regression and Logistic Regression are the simplest and most important. Then come k-Nearest Neighbours, Naive Bayes, Decision Trees, Random Forests and Bagging, Gradient Boosting: XGBoost and LightGBM and support vector machines. Neural Networks power deep learning.
- Losses and metrics: Loss Functions and Evaluation Metrics.
- Honest testing: Training, Validation and Test Sets, Overfitting and the Bias–Variance Tradeoff, Regularization: L1 and L2, Cross-Validation, Hyperparameter Tuning.
- Inputs: Data Cleaning and Preparation and Feature Engineering.
Supervised learning has siblings. Unsupervised Learning finds structure in data without labels. Self-Supervised Learning creates labels from the data itself, as language models do when they predict the next token. Reinforcement learning learns from rewards rather than correct answers. See Supervised, Unsupervised and Reinforcement Learning for the map.
A bit of history
Fitting a function to labelled data is older than computers. Adrien-Marie Legendre (1805) and Carl Friedrich Gauss (who said he had used it since 1795) invented least-squares fitting to predict the orbits of comets and planets from observations. Ronald Fisher introduced linear discriminant analysis, an early classifier, in 1936, using measurements of iris flowers that are still a standard teaching dataset.
The idea of a machine that learns from labelled examples arrived with Frank Rosenblatt's The Perceptron in 1958. Arthur Samuel coined the phrase "machine learning" around 1959. The theory of when learning from examples generalises was put on firm footing by Vladimir Vapnik and Alexey Chervonenkis from the 1960s onwards, and by Leslie Valiant's PAC-learning framework in 1984. The big practical shift came in the 2000s and 2010s, when large labelled datasets such as ImageNet (about 14 million labelled images) met fast hardware. That combination produced the deep-learning breakthroughs described in A Short History of AI.
Try it
- Compute by hand the mean squared error of the hypothesis on the four students. Is it better or worse than hypothesis B?
- Change the grid in the from-scratch code to steps of 0.05. Does the best line change? Why not?
- For each of these, say whether it is regression or classification, and name two plausible features: predicting a flight's delay in minutes; predicting whether a customer will cancel their subscription; predicting which language a sentence is written in.
Hint for 1: the predictions are 3, 5, 7, 9, so only the last example has an error.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Machine Learning Specialization
The best-known first course in ML. Covers regression, classification, neural nets, trees, clustering, recommenders and RL with Python labs.
scikit-learn User Guide
Excellent documentation that doubles as a textbook, with explanations and examples for every algorithm.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
Hands-On Machine Learning (code notebooks)
A very practical bestselling book that covers scikit-learn through deep learning. All of its notebooks are free on GitHub.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/supervised-learning.md