Level 2 · BeginnerLesson 2.2 30 min read 10 question quiz 11 marks of written practice

How Machines Learn: Supervised, Unsupervised and Reinforcement

What it means for a machine to learn

In 1997 the computer scientist Tom Mitchell gave the definition still used in textbooks:

Mitchell's definition

A program learns from experience E with respect to a task T and a performance measure P if its performance at T, as measured by P, improves with experience E.

Spam filterChess programWeather model
Task TSort emails into spam and not spamWin gamesPredict tomorrow's rainfall
Performance PPercentage sorted correctlyPercentage of games wonAverage error in millimetres
Experience EEmails people have labelledGames playedYears of weather records

Model, parameters, training and inference

A model is a function with adjustable numbers inside it, called parameters or weights. Training means adjusting those numbers until the model's outputs match the examples well. Inference means using the trained model on new inputs.

Training compared with inferenceTwo rows. Training: labelled examples go into a model whose parameters are shown as sliders being adjusted; the model makes a prediction, the prediction is compared with the label to give an error, and a dashed arrow takes the error back to nudge the parameters, repeatedly. Training is slow and costly and done once or now and then. Inference: a new input goes into the trained model, whose parameters are fixed, and a prediction such as spam, 97 percent, comes out. Inference is fast and cheap and happens every time someone uses the model.Training sets the numbers. Inference uses them.TRAININGslow, costly, done once or now and thenlabelledexamplesmodelparameters (weights) being adjustedpredictionerrorcompare with the label, nudge the parameters, repeatINFERENCEfast, cheap, every time someone uses itnew inputtrained modelparameters fixedpredictione.g. 'spam, 97%'
A model is learned once, then used millions of times.

Training is slow and expensive and happens once, or now and then. Inference is quick and cheap and happens every time someone uses the model. A large language model may take months to train and then answer millions of questions a day.

Supervised learning: learning from labelled examples

In supervised learning, every training example has an input and the correct output, called the label. The model learns to map inputs to labels.

Supervised, unsupervised and reinforcement learningThree panels. Supervised learning, examples with answers: pink circles labelled cat and blue squares labelled dog, separated by a dashed boundary line the model learns. Unsupervised learning, find the structure yourself: grey points with no labels, which the algorithm groups into three circled clusters. Reinforcement learning, try things and collect rewards: a four by four grid with walls, where agent A learns a route to a star worth a reward of plus one.Three ways to learnSupervisedexamples with answersUnsupervisedfind the structure yourselfReinforcementtry things, collect rewardscatdogno labels: groups foundA+1 rewardagent A learns the route
Answers, no answers, or only a score: the three kinds of learning differ in what feedback they get.

The inputs are described by features: the measurable properties the model can use.

ProblemFeatures (input)Label (output)Type
Is this email spam?The words in it, the senderspam or not spamClassification
Which digit is this?784 pixel brightnesses0 to 9Classification
What will this house sell for?Size, bedrooms, locationA price in poundsRegression
How long will this delivery take?Distance, time of day, weatherMinutesRegression
  • Classification predicts a category.
  • Regression predicts a number.

Supervised learning is the workhorse of industry, but labels are expensive: someone has to mark every example. ImageNet's 14 million labels took tens of thousands of crowd workers years to produce.

Unsupervised learning: finding structure without answers

In unsupervised learning there are no labels. The algorithm looks for structure in the inputs alone.

TechniqueWhat it findsExample
ClusteringGroups of similar examplesCustomer segments for a shop: bargain hunters, weekend browsers, loyal regulars
Dimensionality reductionA few numbers that capture most of manySquashing 1,000 survey answers down to 3 personality scores to plot them
Anomaly detectionExamples unlike the restA card payment that does not fit your usual pattern
AssociationThings that happen togetherPeople who buy pasta often buy parmesan

The catch: nobody tells the algorithm what a good answer is, so a person has to decide whether the structure it found is meaningful. Clustering will always find clusters, even in random noise.

Reinforcement learning: learning from rewards

In reinforcement learning (RL) an agent takes actions in an environment and receives rewards. Nobody tells it the right action. It learns by trial and error which actions lead to the most reward over time.

ExampleActionsReward
Learning to play an arcade gameJoystick movesThe game score
A robot learning to walkMotor movementsDistance travelled without falling
AlphaGoPlacing stones+1 for a win, -1 for a loss, only at the end
Tuning a chatbot's styleChoosing how to replyA score from a model of what people preferred

Two things make RL hard. The reward is often delayed: a Go game lasts about 200 moves and the reward comes only at the end, so which moves deserved the credit? And the agent must balance exploring new actions against exploiting the ones it already knows work. Level 13 builds a reinforcement learner from scratch.

Self-supervised learning: the trick behind modern AI

Labels are expensive. Rewards are slow. So how did language models learn from trillions of words?

Self-supervised learning creates labels from the data itself. Hide part of the input and train the model to predict the hidden part. The hidden part is the label, and it costs nothing.

Self-supervised learningThe words The cat sat on the are shown, followed by a hidden word marked with a question mark. They go into a model, which outputs probabilities for the hidden word: mat 46 percent, floor 21 percent, sofa 14 percent, bed 9 percent and dog 1 percent. The real word was mat, which is the free label. Training nudges the parameters so the real word gets a higher probability next time, repeated for every word in trillions of words of text, with no person labelling anything.The data labels itself: hide a word, then predict itThecatsatonthe?modelmat46%floor21%sofa14%bed9%dog1%real word: mat(the free label)Training signalThe model gave the real word 46%. Training nudges its parameters so that next time the real wordgets a little more. Repeat for every word in trillions of words of text, and no person ever labels anything.
Next-word prediction: the training method behind GPT-style models.
  • Next-word prediction: "The cat sat on the ..." The label is the word that really came next. This is how GPT-style models are trained.
  • Masked words: "The cat [MASK] on the mat." Predict the missing word. This is how BERT was trained.
  • Images: hide patches of a photo and predict them, or predict whether two crops come from the same photo.

To predict the next word well across all of the internet, a model has to pick up grammar, facts, styles of writing and some reasoning. Prediction turns out to be a remarkably powerful teacher.

Two more terms you will meet

  • Transfer learning: start from a model trained on a huge general task, then train it a little more on your small specific task. Almost all practical AI works this way now.
  • Semi-supervised learning: a few labelled examples plus many unlabelled ones.

Hands-on: your first learning program

Learning a threshold

Twelve students recorded their hours of revision and whether they passed. The program tries every possible threshold and learns the one that best separates pass from fail. That search is training, in miniature.

Python
# (hours of revision, passed: 1 = yes, 0 = no)
data = [(1, 0), (2, 0), (2.5, 0), (3, 0), (3.5, 0), (3, 1),
        (4, 1), (4.5, 1), (5, 1), (6, 1), (7, 1), (8, 1)]

def accuracy(threshold):
    correct = 0
    for hours, passed in data:
        prediction = 1 if hours >= threshold else 0
        correct += prediction == passed
    return correct / len(data)

candidates = [t / 2 for t in range(0, 21)]      # 0, 0.5, 1, ... 10
for t in candidates[2:11]:
    print(f"threshold {t:>4}: accuracy {accuracy(t):.0%}")

best = max(candidates, key=accuracy)
print("Learned rule: predict a pass if hours >=", best)
print("Prediction for 3.8 hours:", "pass" if 3.8 >= best else "fail")

The learned threshold is one parameter. A large language model has billions of them, but the principle is the same: search for the parameter values that make the fewest mistakes on the examples.

Learning by nearest neighbour

Another way to learn is simply to remember the examples and, for a new input, copy the label of the most similar one.

Python
import math

# (weight in grams, skin smoothness 1 to 10), label
fruit = [((150, 9), "apple"), ((170, 8), "apple"), ((140, 9), "apple"),
         ((130, 3), "orange"), ((160, 2), "orange"), ((145, 4), "orange")]

def nearest(item):
    best = min(fruit, key=lambda f: math.dist(f[0], item))
    return best[1]

for mystery in [(155, 8), (150, 3), (138, 7)]:
    print(mystery, "is probably an", nearest(mystery))

This is the nearest neighbour classifier. Level 4 improves it by letting several neighbours vote, and shows why the features need to be on similar scales.

Activity: which kind of learning?

Decide whether each is supervised, unsupervised, reinforcement or self-supervised learning, and say what the labels or rewards are: predicting exam grades from past records; grouping songs by sound; a drone learning to hover; predicting the next frame of a video; sorting X-rays labelled by doctors; finding unusual network traffic; training a model to fill in missing words.

Level check

  • State Mitchell's definition of learning and apply it to a new example
  • Explain the difference between a model, its parameters, training and inference
  • Describe supervised learning and the difference between classification and regression
  • Describe unsupervised learning, with two techniques and examples
  • Describe reinforcement learning and explain why delayed rewards make it hard
  • Explain how self-supervised learning creates its own labels

Key terms you must be able to define

Training
Adjusting a model's parameters until its outputs match the training examples well.
Inference
Using a trained model to produce outputs for new inputs.
Parameter (weight)
One of the adjustable numbers inside a model that training sets.
Feature
A measurable property of an example that the model uses as input.
Label
The correct output for a training example in supervised learning.
Supervised learning
Learning from examples that include the correct answers.
Classification
Predicting which category an input belongs to.
Regression
Predicting a number.
Unsupervised learning
Finding structure, such as clusters, in data that has no labels.
Reinforcement learning
An agent learning which actions earn the most reward by trial and error.
Self-supervised learning
Learning by hiding part of the data and predicting it, so the data provides its own labels.
Transfer learning
Starting from a model trained on a large general task and adapting it to a specific one.

Flashcards

DefineTraining
AnswerAdjusting a model's parameters until its outputs match the training examples well.
DefineInference
AnswerUsing a trained model to produce outputs for new inputs.
DefineParameter (weight)
AnswerOne of the adjustable numbers inside a model that training sets.
DefineFeature
AnswerA measurable property of an example that the model uses as input.
DefineLabel
AnswerThe correct output for a training example in supervised learning.
DefineSupervised learning
AnswerLearning from examples that include the correct answers.
DefineClassification
AnswerPredicting which category an input belongs to.
DefineRegression
AnswerPredicting a number.

Go further: notes for future AI engineers

Inductive bias: why every learner makes assumptions

No learner can generalise without assumptions. The threshold learner assumes one cut-off separates the classes. Nearest neighbour assumes similar inputs have similar labels. A convolutional network assumes nearby pixels matter together. These built-in assumptions are called inductive bias, and choosing a model is choosing its assumptions.

The no free lunch theorem (Wolpert, 1996) makes this precise: averaged over every possible problem, no learning algorithm beats any other. A method wins only because its assumptions fit the problems we actually have. That is why engineers try several models, and why understanding the assumptions matters more than memorising algorithm names.

Misconceptions to avoid

Avoid these
  • Confusing classification and regression. If the answer is a category it is classification, even when the categories are numbered.
  • Thinking unsupervised learning finds the 'right' groups. It finds groups, and a person must judge whether they mean anything.
  • Mixing up training and inference. Training sets the parameters; inference uses them and changes nothing.
  • Thinking reinforcement learning is told the right answer. It only receives rewards, often long after the action that earned them.
  • Believing language models were trained on labelled data. Their labels come free from the text itself.
Fun fact

The labels for modern language models cost nothing: the label for every word is simply the word that comes next in the text. That is why they can learn from trillions of words that nobody ever labelled.

Knowledge check

0 of 10 answered
1In Mitchell's definition, what is P for a spam filter?
2What is inference?
3Predicting the price of a house from its size and location is an example of:
4Which is unsupervised learning?
5Why are delayed rewards a problem in reinforcement learning?
6How does self-supervised learning get its labels?
7In machine learning, what is a feature?
8What is transfer learning?
9A model learns to predict whether a photo shows a cat or a dog from 50,000 labelled photos. Which kind of learning is this?
10What does a nearest neighbour classifier do with a new input?
Score 0 / 10

Check you could explain this

11 marks
1Apply Mitchell's definition of learning to a program that learns to recommend films.3 marks
Apply

Mark scheme0 / 3
  • LTask: recommending films a person will like
  • LPerformance: e.g. percentage of recommendations watched or rated highly
  • LExperience: records of what people watched or rated
Model answer

The task T is recommending films that a person will enjoy. The performance measure P could be the percentage of recommended films that people go on to watch, or rate highly. The experience E is the record of what people have watched, finished, skipped and rated. The program learns if its recommendations are watched more often as that record grows.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2Compare supervised and unsupervised learning.4 marks
Compare

Mark scheme0 / 4
  • LSupervised learning uses labelled examples / correct answers
  • LUnsupervised learning has no labels
  • LSupervised predicts a known output, such as a class or number
  • LUnsupervised finds structure such as clusters or anomalies
Model answer

Supervised learning trains on examples that include the correct answer, the label, so the model learns to predict a known kind of output, either a category in classification or a number in regression. Unsupervised learning has no labels, so instead of predicting answers it looks for structure in the inputs, such as clusters of similar examples or unusual anomalies. Supervised learning needs costly labelling, while unsupervised results need a person to judge whether the structure found is meaningful.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Explain why self-supervised learning made large language models possible.4 marks
Explain

Mark scheme0 / 4
  • LLabelling trillions of words by hand would be impossible / too costly
  • LSelf-supervised learning hides part of the text and predicts it
  • LSo the labels come free from the text itself
  • LPredicting text well requires learning grammar, facts or patterns
Model answer

Large language models learn from trillions of words, and paying people to label that much text would be impossible. Self-supervised learning avoids labelling altogether: the model is shown text with the next word hidden and learns to predict it, so every word in the text is a free label. To predict the next word well across so much varied text, the model has to pick up grammar, facts and patterns of reasoning, which is what makes it useful.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 11