Skip to content
coden

Types of machine learning: supervised, unsupervised, semi-supervised and more

Supervised, unsupervised, semi-supervised, self-supervised and reinforcement learning — with precise definitions, plain-language explanations and animations of real algorithms.

15 minutes Matěj Žalmánek 2026-10-15

Series AI basics Part 42 of 52
  1. Map of artificial intelligence: what is what and how it all fits together
  2. A brief history of artificial intelligence: from Turing to language models
  3. Data, model, training, inference: the basic terms on a single example
  4. How to read mathematical notation: symbols, indices, sums and quantifiers
  5. Sets and relations: the building blocks of definitions in AI
  6. Functions and mappings: why every AI model is a function
  7. Logic and proofs: the rules AI reasons by
  8. Graphs and trees: the structure that both search and neural networks stand on
  9. Linear algebra for machine learning: vectors, matrices and why AI mostly multiplies
  10. Derivatives, the gradient and the chain rule: how a model finds out which way to learn
  11. Gradient descent: how a model learns
  12. What probability is: from rolling dice to the Kolmogorov axioms
  13. Conditional probability and Bayes’ theorem: how to update your estimate when you learn something new
  14. Random variables and the cumulative distribution function: one function that tells you everything about a distribution
  15. Probability density and probability mass functions: why a continuous variable has zero probability at a point
  16. Expected value, variance and covariance: where a distribution lies, how wide it is and what goes with what
  17. Overview of probability distributions: Bernoulli, binomial, Poisson, uniform, normal and exponential
  18. Law of large numbers and central limit theorem: why averages behave so predictably
  19. Statistics and parameter estimation: maximum likelihood, MAP and confidence intervals
  20. Information theory: entropy, cross-entropy and KL divergence — where loss functions come from
  21. State-space search: BFS, DFS, UCS and A* with animations
  22. Games and adversaries: minimax, alpha-beta pruning and Monte Carlo tree search
  23. Constraint satisfaction: backtracking, constraint propagation and AC-3 on sudoku and a map of Czech regions
  24. Logic and knowledge systems: forward and backward chaining, resolution and expert systems
  25. Planning: STRIPS, the blocks world, heuristics from relaxation and planning in AI agents
  26. Local search and simulated annealing: a travelling salesman through the Czech regional capitals
  27. Genetic algorithms: population, crossover, mutation and selection on a backpack for a hike
  28. Evolution strategies and genetic programming: from the one-fifth rule to Kepler’s law
  29. Ant colony optimization: how a pheromone trail finds a short path
  30. Particle swarm optimisation: inertia, personal experience and the swarm’s experience
  31. Neuroevolution: evolving the weights and shape of neural networks, and the NEAT algorithm
  32. Fuzzy sets and membership functions: how to write down “somewhat warm”
  33. Fuzzy logic and probability: why “somewhat warm” does not mean “probably warm”
  34. Fuzzy logic: t-norms, implications and IF–THEN rules
  35. Fuzzy control: Mamdani and Sugeno from a fan to a pole on a cart
  36. Fuzzy clustering: the fuzzy c-means algorithm and points between clusters
  37. Neuro-fuzzy systems (ANFIS): fuzzy rules that learn from data
  38. Markov chains: the transition matrix, the stationary distribution and PageRank
  39. Hidden Markov models: the Viterbi algorithm and the dishonest casino
  40. Bayesian networks: why the grass is wet and what it means for the sprinkler
  41. The Kalman filter: how to estimate where a car is and how fast it goes from imprecise measurements
  42. Types of machine learning: supervised, unsupervised, semi-supervised and more
  43. Prompts, context and RAG: how to give a model the right information
  44. Variational autoencoders (VAE): new images from a continuous latent space
  45. Generative adversarial networks (GAN): the forger versus the detective
  46. Diffusion models: how pure noise becomes an image
  47. Markov decision processes: states, actions, rewards and the Bellman equations
  48. Q-learning and DQN: learning the value of actions, from a table to a neural network
  49. Policy gradient and PPO: learning the policy directly
  50. How an AI agent works: a language model in a loop with tools
  51. Programming with AI agents: the task, tests and review
  52. Evaluating and securing AI systems: how to measure and how to keep watch

Full series syllabus 52 of 83 topics published

What you will take away
  • Five types of machine learning, by what kind of signal the model gets while learning.
  • Why a handful of labels and lots of unlabelled data can be enough — and how language models learn.
  • How an agent learns to act from rewards and penalties alone.

Useful to know first: Map of artificial intelligence: what is what and how it all fits together, How to read mathematical notation: symbols, indices, sums and quantifiers

“The model has learned it.” The sentence always sounds the same, but it means very different things. Sometimes the model learned from thousands of photos where someone wrote down what is in them. Other times it got only a pile of data without a single label and had to find order in it. And other times it learned like a dog at a training ground — it tried things, and got a reward for good moves.

That is why machine learning is divided by what signal the model receives while learning. We will go through the main types, from supervised learning all the way to reinforcement learning. For each one you will find a precise definition, a plain-language explanation and a chart that is the real output of the algorithm — nothing is drawn by hand.

1. What it means for a machine to learn

Definition — learning (T. Mitchell, 1997)

Let a computer program be given, together with these three objects:

  1. T — a class of tasks the program is to solve (e.g. “decide whether an e-mail is spam”);
  2. P — a performance measure: a rule that assigns a number to the program’s results on tasks from T, where a larger number means better performance (e.g. the fraction of e-mails sorted correctly);
  3. E — experience: the data or interactions the program receives while learning (e.g. e-mails that someone has already sorted).

The program learns from experience E with respect to the class of tasks T and the performance measure P if and only if its performance on tasks from T, as measured by P, improves with experience E — i.e. a program that has processed more experience from E achieves (on average) a higher value of P on T.

This is a conceptual definition, not a mathematical one: T, P and E still have to be chosen for each concrete task. The formal version for supervised learning is in the next part.

In plain words

Learning is whatever gets better with practice. The task T might be “recognise spam”, the measure P “how many e-mails it sorts correctly” and the experience E “a thousand e-mails that someone has already sorted”. The types of learning differ mainly in what that experience E looks like.

Definition — model and parameters

Let 𝒳 be a non-empty set (the input space), 𝒴 a non-empty set (the output space) and p ∈ ℕ, p ≥ 1. A model with parameters θ ∈ ℝp is a family of functions

fθ : 𝒳 → 𝒴,   x ↦ fθ(x),   θ ∈ ℝp,

i.e. every choice of the vector θ determines one function from inputs to outputs.

Let J : ℝp → ℝ be an objective function computed from data (the smaller J(θ), the better the model with parameters θ describes the data). Learning (training) is the search for parameters

θ* ∈ argminθ ∈ ℝp J(θ) = {θ ∈ ℝp : J(θ) ≤ J(θ′) for all θ′ ∈ ℝp}.

If J is differentiable, the search typically uses gradient descent: choose an initial θ0 ∈ ℝp and a learning rate η > 0, and for t = 0, 1, 2, … set

θt+1 = θt − η ∇J(θt),

as long as J keeps decreasing noticeably (or for a fixed number of steps). In general, gradient descent finds only a local minimum, not necessarily an element of the argmin.

In plain words

A model is a machine with lots of knobs — the parameters. Learning means turning the knobs until the machine does what we want. The objective function is a number that says how wrong it still is; gradient descent always turns the knobs in the direction where it is wrong the least.

θ ← θ − η ∇J(θ)

θ
all the model’s parameters at once (a vector); the arrow ← means “overwrite with the new value” — the step is repeated as long as J decreases
∇J(θ)
the gradient — the vector of partial derivatives ∂J/∂θj, j = 1, …, p; it points in the direction in which the error grows fastest, and for each parameter it says how much the error depends on it
−
we want to make the error smaller, so we go the opposite way from the gradient
η
the learning rate (a small positive number); the gradient holds only near the current point, so the steps must be short — too large an η jumps over the valley, too small learns slowly
One step of gradient descent: a little way downhill.

The main types of learning at a glance — they differ in what the data gives you:

Supervisedinput + correct answer

Learn to answer like the teacher.

Unsupervisedinputs only

Find structure in the data.

Semi-superviseda few answers + many inputs

Make use of unlabelled data too.

Self-supervisedanswers made from the data

How language models learn.

Reinforcementreward for actions

Learn to act.

2. Supervised learning

Definition — supervised learning

Let 𝒳 be the input space, 𝒴 the space of labels (correct answers) and P an unknown probability distribution of pairs (X, Y) on 𝒳 × 𝒴. Further, let

  1. n ∈ ℕ, n ≥ 1, and let the training set D = ((xi, yi))i=1n be a sequence of pairs (xi, yi) ∈ 𝒳 × 𝒴 drawn from P independently of each other;
  2. {fθ : 𝒳 → 𝒴 : θ ∈ ℝp} be a model (see the definition above);
  3. L : 𝒴 × 𝒴 → [0, ∞) be a loss function — L(ŷ, y) is the penalty for the answer ŷ when the correct answer is y.

Supervised learning is the search for parameters that minimise the empirical risk R̂ : ℝp → [0, ∞):

R̂(θ) = 1/n ∑i=1n L(fθ(xi), yi),   θ* ∈ argminθ ∈ ℝp R̂(θ).

The goal, however, is not the training set — the model should have a small true risk R(θ) = E(X, Y) ∼ P[L(fθ(X), Y)], i.e. work well on new data from the same distribution (generalisation). We do not know R, so it is estimated by the average loss on a held-out test set that was not used for learning.

In plain words

Like a child with a picture book: every picture says “dog” or “cat”. The model looks at examples with the correct answer and tunes itself until it gets them right. The loss function is a penalty for every mistake. And the exam is taken on pictures it has never seen before — answers learned by heart do not count.

θ* = argminθ 1/n ∑i=1n L(fθ(xi), yi)

fθ(xi)
the model’s answer to the i-th example — the only place where the parameters we are allowed to move appear
yi
the correct answer from the teacher; precisely this signal sets supervised learning apart from the other types
L
the loss turns the difference between the answer and the label into a single non-negative number so that it can be minimised — cross-entropy for classes, the squared difference for numbers
1/n ∑
the average over the training set; we do not know the true risk E[L] over the whole distribution P(X, Y), so we estimate it by the average over a sample (hence “empirical”)
θ* = argminθ
we are not interested in the smallest value of the loss but in the parameters at which it occurs — they are the learned model
Supervised learning as optimisation: find the parameters with the smallest average error on the labelled examples.

Depending on what the label y is, we distinguish two tasks.

Classification

Definition — classification

Classification is supervised learning in which the label space is a finite set of classes 𝒴 = {1, …, K}, K ∈ ℕ, K ≥ 2. For an input x ∈ 𝒳 the model returns an estimate of the distribution over the classes, i.e. numbers pθ(k | x) ≥ 0 for k = 1, …, K with ∑k=1K pθ(k | x) = 1.

A common loss is cross-entropy: for x ∈ 𝒳 with label y ∈ 𝒴

L = −∑k=1K [y = k] log pθ(k | x) = −log pθ(y | x),

where [y = k] is 1 if and only if y = k, and 0 otherwise.

Logistic regression for two classes 𝒴 = {0, 1}: let 𝒳 = ℝd, let the parameters be w ∈ ℝd and b ∈ ℝ, and let σ : ℝ → (0, 1) be the logistic function

σ(z) = 1/1 + e−z.

The model is p(y = 1 | x) = σ(w⊤x + b) and p(y = 0 | x) = 1 − σ(w⊤x + b). It assigns a point x to class 1 if and only if σ(w⊤x + b) ≥ 0.5, i.e. if and only if w⊤x + b ≥ 0. The decision boundary is the set

{x ∈ ℝd : w⊤x + b = 0}

— for w ≠ 0 a hyperplane, in the plane (d = 2) a straight line.

In plain words

Classification answers “which box does this belong in”: spam or not? Dog, cat or parrot? Logistic regression draws a line between the classes and says, for every point, how sure it is about which side it lies on.

The chart shows 60 points from two classes. The boundary deliberately starts out wrong, and gradient descent moves it epoch by epoch until it separates the classes:

feature x₁ (unitless) feature x₂ (unitless)
Logistic regression learns to separate two classes epochs: 60 accuracy on training data: 100 %

For two classes, cross-entropy is written as a single formula (class colours as in the chart, p = σ(w⊤x + b) is the estimated probability of class 1):

L(p, y) = −[ y log p + (1 − y) log(1 − p) ]

y log p
applies only to points of class 1 (y = 1, amber): it penalises the model when it gives their class a small probability p
(1 − y) log(1 − p)
the same for class 0 (y = 0, green), whose probability is 1 − p; the factors y and 1 − y act as a switch — only one of the two terms ever applies
−
the logarithm of a probability is negative; the minus turns it into a positive penalty. A confident correct answer costs −log 1 = 0, a confident wrong one → ∞ — a self-assured mistake is the most expensive
It is the negative logarithm of the probability the model assigned to the correct answer.
Algorithm — logistic regression by gradient descent

The derivative of the average cross-entropy J with respect to the weights comes out surprisingly simple (thanks to σ′ = σ(1 − σ), things cancel):

∂J/∂w = 1/n ∑i=1n (pi − yi) xi,   ∂J/∂b = 1/n ∑i=1n (pi − yi),

where pi = σ(w⊤xi + b).

w, b ← initial values
repeat E epochs:                      # epoch = one pass through all the data
    g_w, g_b ← 0, 0
    for each example (x, y):
        p ← σ(w·x + b)                # estimated probability of class 1
        g_w ← g_w + (p − y)·x         # estimation error times input
        g_b ← g_b + (p − y)
    w ← w − η·g_w / n                 # step against the gradient
    b ← b − η·g_b / n
class(x) = 1 if σ(w·x + b) ≥ 0.5, otherwise 0

Accuracy is the fraction of examples classified correctly: |{i ∈ {1, …, n} : class(xi) = yi}|/n.

Example — what happens in the chart

Start: w = (0.4, 1.2), b = −0.9, learning rate η = 2.5. The first point has coordinates (0.604, 0.673) and class 0:

z = 0.4 · 0.604 + 1.2 · 0.673 − 0.9 = 0.148,   p = σ(0.148) = 1/1 + e−0.148 = 0.537.

So the model assigns this class-0 point to class 1 with probability 0.537 — a mistake. The loss (y = 0, so only the second term of the cross-entropy formula above remains) is −ln(1 − 0.537) = 0.770 (colours as in the formula above), and its contribution to the gradient (p − y) x = 0.537 · (0.604, 0.673) pulls both weights down.

On the whole data: accuracy at the start 15%, after 5 epochs 95%, from epoch 16 on 100%. The average cross-entropy (natural logarithm) falls from 0.780 to 0.175 after 60 epochs; even once all the points are correct, the model keeps increasing the weights to become more confident.

Regression

Definition — regression

Regression is supervised learning in which the labels are real numbers: 𝒴 = ℝ. Let (xi, yi) ∈ 𝒳 × ℝ, i = 1, …, n, be the training pairs and f : 𝒳 → ℝ a model. A common loss is the mean squared error

MSE(f) = 1/n ∑i=1n (f(xi) − yi)2.

Linear regression with one input: let 𝒳 = ℝ, n ≥ 2, and let x1, …, xn not all be equal. The model is f(x) = ax + b with parameters a, b ∈ ℝ. Denote the means x̄ = 1/n ∑i=1n xi and ȳ = 1/n ∑i=1n yi. Then the MSE has a unique minimum (the method of least squares) at

a = ∑i=1n (xi − x̄)(yi − ȳ)/∑i=1n (xi − x̄)2,   b = ȳ − ax̄.

(The assumption that the xi are not all equal guarantees a non-zero denominator.)

In plain words

Regression answers “how much”: how much a flat will cost, what the temperature will be tomorrow. Linear regression fits a straight line through the points so that the sum of the squared vertical distances — dashed in the picture — is as small as possible.

floor area (scaled 0–1) price (scaled 0–1)
Linear regression: flat price by floor area
Derivation and example — why exactly this formula for the line

MSE(a, b) is a quadratic function of two variables, so the minimum is where both partial derivatives are zero:

∂/∂b: 2/n ∑ (axi + b − yi) = 0  ⇒  b = ȳ − ax̄ (the line passes through the centroid of the data),

∂/∂a: 2/n ∑ (axi + b − yi) xi = 0; substituting b gives the formula for a from the definition above.

For the 24 flats in the chart: a = 0.797, b = 0.083, MSE = 0.0046, so the typical vertical deviation (the dashed segments) is √MSE ≈ 0.068. We generated the data as y = 0.12 + 0.72 x + noise with standard deviation 0.06 — from 24 points the method hit the true slope and noise roughly, not exactly.

Supervised learning powers most practical applications: spam filters, face recognition, diagnosis from X-ray images, property price estimates. But it has one expensive condition — someone has to label the data. And that tends to be the most expensive part of the whole project.

3. Unsupervised learning

Definition — unsupervised learning

Let 𝒳 be the input space, PX an unknown distribution on 𝒳 and D = (xi)i=1n, xi ∈ 𝒳, inputs drawn from PX independently of each other — without labels. Unsupervised learning looks in D for the structure of the distribution PX. Typical tasks:

  1. clustering — a partition of the indices {1, …, n} into k non-empty, pairwise disjoint sets C1, …, Ck (clusters) such that points in one cluster are similar to each other;
  2. dimensionality reduction — for 𝒳 = ℝd, a mapping g : ℝd → ℝm, m < d, that preserves as much information about the data as possible;
  3. density estimation — a function p̂ : 𝒳 → [0, ∞) that approximates the density p(x) of the distribution PX.

What exactly “similar” or “as much information as possible” means is decided only by a concrete method through its objective function — like k-means below.

In plain words

You get a box of photos without captions and have to sort them. Nobody tells you by what — you notice on your own that some are from the seaside and others from the mountains. The model looks for similarities and patterns that are in the data, even though nobody has named them.

Clustering: k-means

Definition — k-means

Let x1, …, xn ∈ ℝd be points, k ∈ ℕ, 1 ≤ k ≤ n, and let ‖·‖ be the Euclidean norm. For a partition of the points into k pairwise disjoint clusters C1, …, Ck (each point belongs to exactly one) and centres μ1, …, μk ∈ ℝd, the within-cluster sum of squares is

J(C1, …, Ck, μ1, …, μk) = ∑j=1k ∑x ∈ Cj ‖x − μj‖2.

The k-means problem is to find clusters and centres for which J is minimal.

Lloyd’s algorithm (an approximate solution). Input: points x1, …, xn ∈ ℝd, the number of clusters k and initial centres μ1, …, μk ∈ ℝd. Output: clusters C1, …, Ck and centres μ1, …, μk. Repeat:

  1. assignment: put every point xi into the cluster Cj with j ∈ argminj′ ∈ {1, …, k} ‖xi − μj′‖2 (the nearest centre);
  2. moving the centres: for every j = 1, …, k with Cj ≠ ∅ set μj = 1/|Cj| ∑x ∈ Cj x (the mean of the cluster’s points).

Stopping: when no centre changes in step 2. No step increases J and there are finitely many possible partitions, so the algorithm terminates — but in general only in a local minimum of J.

In plain words

You put three flags in a room. Everyone goes and stands by the nearest one. Then you move each flag to the middle of its little crowd. People regroup, the flags move again — and after a few rounds nothing changes. The little crowds are the clusters.

feature x₁ (unitless) feature x₂ (unitless)
k-means finds three clusters (k = 3) iterations: 4

The centres (crosses) deliberately all start in the bottom-left corner. After the very first iteration they spread out towards their groups, and after four iterations they stop moving.

Algorithm — Lloyd’s algorithm (k-means)
μ₁, …, μ_k ← initial centres
repeat:
    for each point x:                    # step 1: assignment
        c(x) ← argmin_j ‖x − μ_j‖²
    for each j = 1, …, k:                # step 2: moving the centres
        μ_j ← mean of the points with c(x) = j
until the centres stop moving

Why J does not increase. Step 1 changes only the assignment, and every point moves to a closer centre, so its term ‖x − μj‖2 does not increase. Step 2 changes only the centres, and the mean is the point that minimises the sum of squared distances to a group of points (the derivative of ∑ ‖x − μ‖2 with respect to μ is −2 ∑ (x − μ), which is zero exactly for the mean). There are finitely many possible assignments, so the algorithm terminates.

In our chart (66 points), J takes the values 19.330 → 2.937 → 1.048 → 0.655 in the individual iterations — the biggest chunk of the work is done by the very first move of the centres away from the bad start.

Other unsupervised tasks: dimensionality reduction (for example, PCA projects the data onto the few directions in which it varies most — useful for both visualisation and compression), anomaly detection (whatever resembles nothing we already know — a fraudulent payment, a machine fault) and density estimation.

4. Semi-supervised learning

Definition — semi-supervised learning

Let 𝒳 be the input space, 𝒴 the label space, P an unknown distribution on 𝒳 × 𝒴 and l, u ∈ ℕ, l ≥ 1. We are given

  1. a small labelled set DL = ((xi, yi))i=1l, (xi, yi) ∈ 𝒳 × 𝒴, drawn independently from P;
  2. a large unlabelled set DU = (xj)j=l+1l+u, xj ∈ 𝒳, drawn independently from the distribution of the inputs X alone (the labels yj exist, but we do not know them), where u ≫ l.

Semi-supervised learning has the same goal as supervised learning — a model fθ : 𝒳 → 𝒴 with a small true risk — but uses both DL and DU to reach it.

Unlabelled data can help only if the distribution of the inputs says something about the labels. The following assumptions are used (every method rests on at least one of them):

  1. smoothness — if two inputs x, x′ ∈ 𝒳 are close to each other in a region with a lot of data, they have (with high probability) the same label;
  2. cluster — inputs from one cluster have (with high probability) the same label, so the class boundary runs through places with a low density of data;
  3. manifold — the data in 𝒳 = ℝd lies close to a surface (a manifold) of dimension m < d, and the distance between points should be measured along this surface, not along a straight line in ℝd.
In plain words

You have ten thousand photos, but you only managed to label ten. The unlabelled photos still help: they show what the data “looks like” — where the little crowds are and where the empty space between them runs. The labels then spread through the crowds on their own.

Label propagation on a graph

Input: points x1, …, xN ∈ ℝd, some of which have a label from 𝒴 = {0, 1}, and a number of neighbours k ∈ ℕ (here k = 4). Output: a label for every point that can be reached from the labelled points along the edges of the graph.

  1. Build an undirected graph: connect points xi and xj (i ≠ j) with an edge if and only if xj is among the k nearest neighbours of xi, or xi is among the k nearest neighbours of xj (by Euclidean distance).
  2. In one round, go through all the unlabelled points; each one that has at least one labelled neighbour gets the label held by the majority of its labelled neighbours (label 0 in case of a tie). Labels assigned in a round take effect only from the next round.
  3. Stopping: repeat step 2 while there are unlabelled points and at least one label was added in the last round.

The data is two “moons” of 40 points each. Only two points have a label — one in each moon, highlighted with an outline. The rest are grey:

feature x₁ (unitless) feature x₂ (unitless)
Label propagation from two labelled points rounds: 10 labelled correctly: 100 %

The labels spread along the moons like fire through dry grass, and after 10 rounds every point is labelled correctly. If we ignored the unlabelled data and assigned each point only by which of the two labelled points it is closer to, just 84% would be correct: the tips of the moons lie closer to the other moon’s labelled point than to their own. The difference is made precisely by the shape of the data, which we only know thanks to the unlabelled points.

Pseudo-labelling (self-training) works in a similar way: a model trained on the small labelled set labels the unlabelled data it is most confident about, and keeps learning from that too.

5. Self-supervised learning

Definition — self-supervised learning

Let D = (xi)i=1n, xi ∈ 𝒳, be unlabelled data and let g be a fixed (possibly random) rule that automatically, without human work, creates from every input x ∈ 𝒳 a pair

g(x) = (x̃, t),

where x̃ is a part or a corrupted version of the input x and t is what is missing from x̃. Self-supervised learning is supervised learning on the training set (g(xi))i=1n: the model gets x̃ and has to predict t. This artificially created task is called a pretext task.

Next-token prediction — this is how large language models are pre-trained. Let V be a finite vocabulary of tokens and let a text be a sequence x1, …, xT ∈ V, T ≥ 1. For each t = 1, …, T the model returns a distribution pθ(· | x1, …, xt−1) on V (for t = 1 without a condition), and the parameters θ are chosen so as to maximise

∑t=1T log pθ(xt | x1, …, xt−1).

Here x̃ = (x1, …, xt−1) and the t-th token is the label.

In plain words

There is a teacher here, but nobody had to pay for it: the answers are hidden right in the data. You cover a word in a sentence and the model guesses what it was. Text from the internet thus marks its own homework — and along the way the model has to pick up grammar, facts and a bit of reasoning, otherwise it would guess wrong.

Self-supervised learning is technically supervised learning, but the labels cost nothing — and that is why it can be applied to the entire internet. For images a similar trick is used: the model gets two different crops of the same photo and learns that they belong together (contrastive learning). The result, a so-called foundation model, is then fine-tuned for a specific task on a small amount of labelled data.

6. Reinforcement learning

Definition — Markov decision process

A Markov decision process (the environment) is a five-tuple (S, A, P, R, γ), where

  1. S is a non-empty set of states (finite in our case — the cells of a grid);
  2. A is a non-empty finite set of actions;
  3. P is the transition probability: for every s ∈ S and a ∈ A, P(· | s, a) is a probability distribution on S, i.e. P(s′ | s, a) ≥ 0 and ∑s′ ∈ S P(s′ | s, a) = 1 (P(s′ | s, a) is the probability that action a in state s leads to state s′);
  4. R : S × A × S → ℝ is the reward for the transition from s via action a to s′;
  5. γ ∈ [0, 1) is the discount factor.

The agent’s policy is a rule π that assigns to every state s ∈ S a distribution π(· | s) on A. The agent starts in state s0 and for t = 0, 1, 2, … chooses an action at according to π(· | st), the environment picks the next state st+1 according to P(· | st, at), and the agent receives the reward rt = R(st, at, st+1). The return is

G = ∑t=0∞ γt rt

(in a terminal state the episode ends and all further rewards are 0), and the goal is to find a policy that maximises its expected value E[G].

The action value Q(s, a) is the expected return when the agent performs action a in state s and plays optimally from then on. Q-learning estimates it with a table Q : S × A → ℝ (at the start e.g. all zeros): after every step (s, a, r, s′), with a learning rate α ∈ (0, 1], it performs

Q(s, a) ← Q(s, a) + α [r + γ maxa′ ∈ A Q(s′, a′) − Q(s, a)],

where, if s′ is a terminal state, maxa′ Q(s′, a′) = 0 is used.

In plain words

Nobody tells the agent what the right move is. It tries, and for every step the world gives it back a reward or a penalty. Gradually it remembers which moves pay off where — including the ones that only pay off ten steps later. The discount factor γ says how much it cares about future rewards compared with immediate ones.

Q(s, a) ← Q(s, a) + α [r + γ maxa′ Q(s′, a′) − Q(s, a)]

Q(s, a)
the current estimate of how much action a earns in state s; inside the bracket it is subtracted so that the bracket measures the surprise — the difference between what the agent expected and what it has just experienced
r
the reward the world returned right after the step (−1, +10 or −10) — the only real signal from outside
maxa′ Q(s′, a′)
an estimate of everything that comes afterwards if the agent plays optimally from state s′; thanks to this term, the value of the goal spreads back along the path step by step. The maximum (not the action actually chosen) makes it possible to learn the best policy even though the agent sometimes tries random moves. In a terminal state this term is 0
γ
future rewards weigh less than immediate ones; at the same time, thanks to γ < 1 the infinite sum G stays finite
α
the learning rate — how much of the surprise to take on; rewards and transitions can be random, so a new experience only shifts the old estimate, it does not overwrite it
The bracket is the temporal difference: (a better estimate from one real step) − (the old estimate).
Definition — ε-greedy action selection

Let A be a finite non-empty set of actions, Q : S × A → ℝ a table of action values and ε ∈ [0, 1]. For a state s ∈ S, choose a*(s) ∈ argmaxa ∈ A Q(s, a) (in case of a tie, any of the best). The ε-greedy policy chooses action a ∈ A in state s with probability

π(a | s) = ε/|A| + (1 − ε) · [a = a*(s)],

where [a = a*(s)] is 1 if and only if a = a*(s), and 0 otherwise. In other words: with probability ε it picks an action at random (uniformly from all of them), otherwise the action with the largest Q(s, a). In our case ε = 0.2.

In plain words

If you always go to your favourite restaurant, you will never find out that the one a street further cooks better. That is why the agent tries something random in a fifth of its steps — exploration — and otherwise does what it currently considers best — exploitation.

The agent (orange) moves around a grid. Every step costs −1, the goal gives +10 and the trap −10; walls cannot be entered. At the start it knows nothing. After 600 episodes of Q-learning (α = 0.5, γ = 0.95, with random exploration in 20% of steps) the arrows show the best learned action in each cell:

+10 −10
Learned policy and the agent's path from the start steps: 10 return: 1

The agent takes the shortest path to the goal and avoids the trap. You can see how it learned from the average return: in the first 50 episodes it was −11.1 (the agent wandered around and fell into the trap), in the last 50 already −1.8 — the gap to the optimum comes from random exploration, which the agent does not switch off during training.

Example — the first update and the value of the start

The first step. At the start the whole table Q is zero. The agent takes a step onto an ordinary cell: r = −1 and maxa′ Q(s′, a′) = 0, so

Q(s, a) ← 0 + 0.5 · [−1 + 0.95 · 0 − 0] = −0.5

(colours as in the Q-learning formula above). A step into the goal is terminal, so the term maxa′ Q(s′, a′) is 0: Q ← 0 + 0.5 · [10 − 0] = 5. On later visits the five moves towards 10 and spreads further back along the path, each time multiplied by 0.95 and reduced by the cost of a step.

The value of the start. The shortest path has 10 steps: nine ordinary ones at −1 and the last one into the goal at +10. The undiscounted return is 9 · (−1) + 10 = 1, the discounted one

G = −(1 + 0.95 + … + 0.958) + 0.959 · 10 = −1 − 0.959/1 − 0.95 + 10 · 0.959 = −7.395 + 6.302 = −1.093.

The learned table has maxa Q(start, a) = −1.093 at the start — Q-learning found the value of the optimal path exactly.

0 −20 episode (number) average return (reward points)
Learning curve — average return over the last 25 episodes

Reinforcement learning is behind the programs that beat world champions at go, behind robot control — and also behind the fine-tuning of language models: RLHF (reinforcement learning from human feedback) uses as its reward a model trained on which answers people rated better.

7. Other ways to classify learning

The kind of teacher is not the only point of view. A few others you will come across:

Definition — transfer learning

Let Jsource, Jtarget : ℝp → ℝ be the objective functions of a source task (usually with a lot of data) and a target task (usually with little data) for a model with the same parameters θ ∈ ℝp, and let θ0 be the parameters learned on the source task, i.e. (approximately) θ0 ∈ argminθ Jsource(θ). Transfer learning searches for

θ* ∈ argminθ Jtarget(θ)

by gradient descent that starts at θ0 (instead of random values). In fine-tuning, often only the parameters with indices from a small set I ⊂ {1, …, p} are changed; the others stay equal to their values in θ0.

In plain words

If you can ride a bicycle, you will learn to ride a motorbike faster. A model that has already “seen the world” only needs a few hundred examples from your task to catch up.

Definition — active learning

Let DL be a labelled and DU an unlabelled set (as in semi-supervised learning), 𝒴 = {1, …, K}, and pθ(· | x) a model trained on DL. Active learning repeats these steps:

  1. the model itself selects the input x* ∈ DU it is least sure about — for example the one with the highest entropy: x* ∈ argmaxx ∈ DU H(pθ(· | x));
  2. a human (the teacher) supplies its label y*; the pair (x*, y*) moves from DU to DL;
  3. the model is retrained on DL;

until the labelling budget runs out.

Let p be a distribution on {1, …, K}, i.e. p(k) ≥ 0 and ∑k=1K p(k) = 1. Its entropy (in bits) is

H(p) = −∑k=1K p(k) log2 p(k),   where 0 · log2 0 = 0 by convention.

For two classes: an estimate of 50 : 50 has H = −2 · 0.5 · log2 0.5 = 1 bit (the most possible), an estimate of 90 : 10 has H = −0.9 log2 0.9 − 0.1 log2 0.1 ≈ 0.137 + 0.332 = 0.469 bits, an estimate of 99 : 1 only 0.081 bits. The first to be labelled will be an example where the model hesitates 50 : 50.

In plain words

Instead of a human labelling everything, the model only asks about what it does not understand. The same result for a fraction of the work.

Definition — generative and discriminative models

Let 𝒳 be the input space and 𝒴 the label space.

  1. A discriminative model learns the conditional distribution pθ(y | x) for x ∈ 𝒳, y ∈ 𝒴 directly, or straight away a decision function fθ : 𝒳 → 𝒴 (and hence a decision boundary). It says nothing about how the inputs x themselves are distributed.
  2. A generative model learns the data distribution pθ(x) on 𝒳, or the joint distribution pθ(x, y) on 𝒳 × 𝒴, and can sample new data from it. From the joint distribution the conditional one can be computed as well (for finite 𝒴): pθ(y | x) = pθ(x, y)/∑y′ ∈ 𝒴 pθ(x, y′).
In plain words

A discriminative model can tell a dog from a cat. A generative model knows what a dog looks like so well that it can draw one. Language models and image generators are generative.

And there is also batch vs. online learning (the model is trained once on all the data, or keeps learning from every new example) and parametric vs. non-parametric models (a fixed number of parameters, like logistic regression, or a model that grows with the data, like k nearest neighbours).

8. Comparison

Type of learningDataSignalTypical tasksExample algorithms
Supervised(x, y)correct answerclassification, regressionlogistic regression, decision trees, neural networks
Unsupervisedxnoneclustering, dimensionality reduction, anomaliesk-means, PCA, autoencoders
Semi-supervisedfew (x, y) + many xa few answersclassification with expensive labelslabel propagation, pseudo-labelling
Self-supervisedxmade from the datapre-training foundation modelstoken prediction, masking, contrastive learning
Reinforcementinteraction with an environmentrewardgames, robots, control, RLHFQ-learning, policy gradient, PPO

9. Summary

  • The types of learning differ in what experience E the model gets: correct answers, only data, a bit of both, answers made from the data, or rewards for actions.
  • Supervised learning is the most straightforward, but it needs expensive labels.
  • Unsupervised learning looks for structure; in semi-supervised learning, unlabelled data helps spread a few labels to everything.
  • Self-supervised learning makes labels from the data itself — today’s language models are built on it.
  • Reinforcement learning teaches how to act: try things, collect rewards and think ahead.

In practice the types are combined. A large language model is pre-trained with self-supervised learning, fine-tuned with supervision on example answers and finally with reinforcement learning based on human ratings. Three types of learning in a single model — one you may be chatting with right now.

Do you see it differently? Write to support@coden-app.com.

An Agent on your computer, driven from your phone