◆ AI All-in-One

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
↗ Plan a path here

Read first

Supervised, Unsupervised and Reinforcement Learning

This leads to

The PerceptronDecision TreesFeature Engineeringk-Nearest NeighboursLinear RegressionNaive BayesRecommender SystemsTraining, Validation and Test SetsThe ML Project Lifecyclescikit-learnBias and Fairness
The full path from zero — 3 concepts before this one
  1. What Is AI?
  2. How Machines Learn
  3. Supervised, Unsupervised and Reinforcement Learning
  4. Supervised Learning

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 xx. For a house: its floor area, number of bedrooms, postcode, year built.
  • The label: the answer you want the model to give, usually written yy. 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{y} ("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.
1 2 3 4 2 4 6 8 10 hours of practice x score y new x = 4.5 → ŷ ≈ 9.2 Regression label is a number fitted line ŷ = 1.7x + 1.5 feature x₁ feature x₂ Classification label is a category ● class A ■ class B decision boundary predict how much predict which one
Fig. 1 The two kinds of supervised learning. Left, regression: a line fitted through four (hours, score) examples predicts a number for a new input. Right, classification: a boundary separates two classes, and a new point is classified by the side it falls on.

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 ii form a vector xi=(xi1,xi2,…,xid)\mathbf{x}_i = (x_{i1}, x_{i2}, \dots, x_{id}), where dd is the number of features (here 3). Stacking all NN rows gives a matrix X\mathbf{X} with NN rows and dd columns. The labels form a vector y\mathbf{y} of length NN. 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 hh, because it is the algorithm's current guess about how yy depends on xx. Every model has parameters, adjustable numbers that change what the function does, collected as θ\theta ("theta"). We write the model as:

y^=h(x;θ)\hat{y} = h(\mathbf{x}; \theta)

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:

h(x;w,b)=wx+bh(x; w, b) = w x + b

It has two parameters: the weight ww (the slope: how much y^\hat{y} rises when xx goes up by 1) and the bias bb (the intercept: the prediction when x=0x = 0). 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 y^i−yi\hat{y}_i - y_i, square it so that misses in either direction count as bad, and average over all NN examples:

L(θ)=1N∑i=1N(h(xi;θ)−yi)2L(\theta) = \frac{1}{N} \sum_{i=1}^{N} \left( h(\mathbf{x}_i; \theta) - y_i \right)^2

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 xx = hours, label yy = score. We will try two hypotheses and let the loss decide which is better.

Hypothesis A: y^=x+2\hat{y} = x + 2 (so w=1w = 1, b=2b = 2).

xx yy y^=x+2\hat{y} = x + 2 error y^−y\hat{y} - y error²
1 3 3 0 0
2 5 4 −1 1
3 7 5 −2 4
4 8 6 −2 4

Mean squared error: (0+1+4+4)/4=2.25(0 + 1 + 4 + 4)/4 = 2.25.

Hypothesis B: y^=1.7x+1.5\hat{y} = 1.7x + 1.5 (so w=1.7w = 1.7, b=1.5b = 1.5).

xx yy y^=1.7x+1.5\hat{y} = 1.7x + 1.5 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: (0.04+0.01+0.16+0.09)/4=0.075(0.04 + 0.01 + 0.16 + 0.09)/4 = 0.075.

B's loss is 30 times smaller, so B fits the data far better. In fact w=1.7,b=1.5w = 1.7, b = 1.5 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 1.7×4.5+1.5=9.151.7 \times 4.5 + 1.5 = 9.15.

The recipe every chapter follows

Every supervised method in this guide is a variation on the same loop.

1 Training: repeat until the loss stops falling Training data features X labels y Model h(x; θ) parameters θ Predictions ŷ Loss L(ŷ, y) how wrong? Optimizer nudge θ to lower the loss X loss new θ the true labels y go straight to the loss 2 Using the model: the parameters are now fixed New example features only Trained model Prediction ŷ no label needed: that is the point
Fig. 2 The supervised learning recipe. During training, the model turns features into predictions, the loss compares them with the true labels, and the optimizer nudges the parameters to reduce the loss. After training, the parameters are frozen and the model maps new features to predictions.
  1. Collect labelled data and turn it into a feature matrix X\mathbf{X} and label vector y\mathbf{y} (Data Cleaning and Preparation, Feature Engineering).
  2. Hold some of it back so you can later test on examples the model never saw (Training, Validation and Test Sets).
  3. Choose a model family: line, tree, forest, neural network.
  4. Choose a loss that measures what you care about (Loss Functions).
  5. Fit: adjust the parameters to lower the loss on the training data, usually with Gradient Descent.
  6. Evaluate on the held-back data with a metric that matches the real goal (Evaluation Metrics).
  7. 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 R2R^2 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:

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

  1. Compute by hand the mean squared error of the hypothesis y^=2x+1\hat{y} = 2x + 1 on the four students. Is it better or worse than hypothesis B?
  2. Change the grid in the from-scratch code to steps of 0.05. Does the best line change? Why not?
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your manager wants a model that predicts how many minutes each delivery will take. What kind of supervised task is this?

  2. Two candidate lines are tried on the same four training examples. Line A has a mean squared error of 2.25 and line B has 0.075. What does that tell you?

  3. A colleague builds a loan-default model that includes the feature "was the loan written off?" and it scores almost perfectly in testing. What is the problem?

  4. In the model ŷ = h(x; θ), what does training actually change?

  5. A line fitted on students who practised 1 to 4 hours predicts a score of 11.7 out of 10 for 6 hours. What pitfall does this show?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Course

Machine Learning Specialization

Andrew Ng (DeepLearning.AI & Stanford) · Beginner · free to audit

The best-known first course in ML. Covers regression, classification, neural nets, trees, clustering, recommenders and RL with Python labs.

Docs

scikit-learn User Guide

scikit-learn · Intermediate · Free

Excellent documentation that doubles as a textbook, with explanations and examples for every algorithm.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Book

Hands-On Machine Learning (code notebooks)

Aurélien Géron · Beginner · notebooks free, book paid

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