Machine learning from 0 to 1000
Most machine learning is one idea repeated at larger and larger scale: write down a function with adjustable numbers in it, measure how wrong it is, and nudge the numbers so it is less wrong.
This article starts at that idea and goes all the way up, through classical models, neural networks, transformers, diffusion, reinforcement learning and running models in production. It follows the approach that 3Blue1Brown made famous: start with a picture, get the intuition, and only then write the formula, so the formula reads as a description of something already understood.
Every chart here was computed from a real run, and every code block was executed. Sections are numbered as levels from 0 to 1000, and each one depends on the ones before it.
Level 0: what machine learning is
A normal program is a set of rules written by a person:
input + rules -> output
Machine learning turns that around:
inputs + outputs -> rules
Nobody can write down the rules for recognising a cat in a photo, or for what a good reply to a sentence looks like. People can, however, collect a million examples. A learning algorithm searches for a function that reproduces those examples and also works on new ones.
That last clause carries all the difficulty. Memorising examples is trivial. A lookup table does it perfectly and learns nothing. The goal is generalisation: doing well on data the model has never seen.
Every machine learning system has four parts, and it is worth naming them, because the rest of this article only changes one or more of them:
| Part | Question it answers | Example |
|---|---|---|
| Data | What does it learn from? | Photos with labels |
| Model | What family of functions can it express? | A neural network |
| Loss | How is wrongness measured? | Cross-entropy |
| Optimiser | How are the numbers adjusted? | Gradient descent |
The types of learning
The types differ in what feedback the model gets.
| Type | Feedback | Typical task | Examples |
|---|---|---|---|
| Supervised | A correct answer for each example | Predict a label or number | Spam filter, price prediction |
| Unsupervised | None | Find structure | Clustering, compression |
| Semi-supervised | A few labels, many unlabelled | Stretch scarce labels | Labelling medical scans |
| Self-supervised | Labels made from the data itself | Learn representations | Predict the next word |
| Reinforcement | A reward after acting | Choose actions | Game playing, robotics |
Inside supervised learning there are two main shapes of task. Regression predicts a number. Classification predicts a category. Generative models, which produce new images and text, cut across the table: they are usually trained with self-supervised methods.
Level 50: the maths, as pictures
Four pieces of maths carry nearly everything. None needs to be deep to begin with, but each needs to be seen correctly.
Vectors are points, and data is vectors
A vector is a list of numbers, and it is also an arrow or a point in space. A house with 3 bedrooms and 120 square metres is the point . A 28 by 28 greyscale image is a point in 784-dimensional space. A sentence, after embedding, is a point in a few thousand dimensions.
This is the first big shift in view. A dataset is a cloud of points, and a classifier is a surface that cuts the cloud. High dimensions cannot be drawn, but the two-dimensional pictures in this article carry over surprisingly well.
The dot product measures agreement
It is large when two vectors point the same way, zero when they are perpendicular, and negative when they oppose. That one operation is how a linear model weighs features, how a neuron decides to fire, how attention decides what to look at, and how a search engine compares embeddings.
A matrix is a transformation of space
A matrix is usually introduced as a grid of numbers. A better description is that it moves space. Its columns say where the basis vectors land, and everything else follows along, with grid lines staying straight, parallel and evenly spaced.
Multiplying matrices means doing one movement after another. A neural network layer is one such movement followed by a bend, and a deep network is many in a row.
Two more words follow from this picture. An eigenvector is a direction that a transformation only stretches, without turning. The determinant is how much it scales area. Both come back in PCA and in the stability of training.
A derivative is a sensitivity
The derivative answers one question: if this input moves a tiny amount, how much does the output move? For a function of many inputs, the list of all those sensitivities is the gradient, written . It is a vector that points in the direction of steepest increase, so its negative points straight downhill.
The chain rule then says that sensitivities multiply along a pipeline. If depends on , and on :
If turning one dial moves a second dial by 3, and the second moves the output by 2, then the first moves the output by 6. Backpropagation, the algorithm behind all of deep learning, is that sentence applied a billion times.
Probability is bookkeeping for uncertainty
A model rarely knows the answer, so it outputs a distribution. A few facts recur constantly.
Bayes’ theorem says how to update a belief with evidence:
Expectation is a weighted average over outcomes, . Variance is the expected squared distance from that average.
Entropy measures surprise. A rare event carries more information than a common one, and information is defined as , so that independent events add. Entropy is the average surprise of a distribution:
Cross-entropy is the average surprise when reality follows but the model believes :
The gap between them, , is the KL divergence. It is zero only when the model’s belief matches reality. Training a classifier means shrinking exactly this gap.
Level 100: the first model
The simplest possible case is a line through some points.
Here and are the two adjustable numbers, called parameters. Different values give different lines, so the problem is choosing a good pair. That needs a definition of good.
The loss
For each point, the error is the vertical gap between prediction and truth. Square each gap and average them, and the result is the mean squared error:
Squaring has real reasons behind it. It makes the loss smooth, it punishes big mistakes much more than small ones, and it follows directly from assuming the noise is Gaussian, as covered later under maximum likelihood.
The loss is a landscape
Now change the view. Stop looking at data space and look at parameter space. Every pair is a point on a flat plane, and the loss at that point is a height. The result is a landscape, and for linear regression it is a smooth bowl.
Training is finding the bottom of that bowl. Linear regression actually has an exact answer, the normal equation, which comes from setting the gradient to zero:
This has a clean geometric meaning. The predictions can only reach a flat subspace, and usually sits outside it, so the best answer is the shadow of on that subspace. Least squares is an orthogonal projection.
Most models have no such formula, which is why the next idea matters so much.
Gradient descent
If you stand on a hillside in fog, you can still feel which way is downhill. Take a small step that way and repeat. That is the whole algorithm:
The symbol stands for all the parameters, and is the learning rate, the size of each step. Here it is on 200 points generated from plus noise:
import numpy as np
rng = np.random.default_rng(0)
x = rng.uniform(0, 10, 200)
y = 3 * x + 7 + rng.normal(0, 2, 200)
w, b = 0.0, 0.0
for step in range(5001):
error = (w * x + b) - y
w -= 0.01 * 2 * np.mean(error * x)
b -= 0.01 * 2 * np.mean(error)
if step in (0, 100, 1000, 5000):
print(step, round(np.mean(error ** 2), 3), round(w, 3), round(b, 3))
0 612.629 3.019 0.46
100 8.167 3.53 3.012
1000 4.169 2.958 7.033
5000 4.169 2.949 7.094
It recovers roughly 3 and 7 from data alone. The loss stops at about 4.17 and goes no lower, because the noise has variance 4. That is the part no model can ever predict, called the irreducible error.
The learning rate
This one number decides whether training works at all.
Classification: logistic regression
Now predict a yes or no. A line’s output can be anything from minus to plus infinity, but a probability has to live between 0 and 1. Pass the score through the sigmoid:
Then pick a loss. The right one is binary cross-entropy:
Geometrically, logistic regression is a flat cut through space. The set of points where the probability equals 0.5 is a straight line in two dimensions and a flat hyperplane in more.
For many classes, each class gets a score, and softmax turns the scores into a distribution:
The is a temperature. It is 1 by default, and it controls how sharp the distribution is. The same mechanism later controls how adventurous a language model’s output is.
Where the losses come from
Squared error and cross-entropy look like arbitrary choices, but both come from one principle, maximum likelihood: choose the parameters under which the observed data was most probable.
Assume is the model’s prediction plus Gaussian noise. Taking the log of the likelihood turns products into sums, the Gaussian’s exponent falls out, and maximising it is the same as minimising squared error. Assume is a coin flip with probability and the same steps give cross-entropy. So a loss function is a statement about how the noise in the data is believed to behave.
If a prior belief about the parameters is added as well, the result is maximum a posteriori estimation, and that prior turns out to be regularisation, covered next.
Level 200: why models fail
A model that scores 99% on its training data can be worthless. This level is about telling the difference, and it matters more in practice than any algorithm.
Overfitting
Here are 14 noisy points from a smooth curve, fitted with polynomials of increasing degree.
In this run the best validation error was about 0.069, at degree 5. At degree 13 the training error was 0.0017 and the validation error about 165,870. The model had enough freedom to memorise the noise, and away from the training points it swung off to enormous values.
This is why data is split into three sets:
| Set | Share, roughly | Used for |
|---|---|---|
| Training | 70 to 80% | Fitting parameters |
| Validation | 10 to 15% | Choosing settings and models |
| Test | 10 to 15% | One final, honest score |
The settings chosen by a person, like degree or learning rate, are called hyperparameters. Picking them on the validation set slowly fits that set too, which is why the test set stays untouched until the very end. When data is scarce, k-fold cross-validation rotates the validation role through k slices and averages the results.
Bias and variance
Test error splits into three parts:
Bias is the error from assumptions that are too rigid. Train the same model on many datasets and its average answer is still wrong. Variance is the error from sensitivity. Small changes in the data move the model a lot. is the irreducible noise.
Degree 1 above is high bias. Degree 13 is high variance. The classical view says that the art is finding the balance between them. Level 1000 shows where that story breaks.
| Symptom | Likely cause | What helps |
|---|---|---|
| High training error | Underfitting, high bias | A bigger model, better features, longer training |
| Low training error, high validation error | Overfitting, high variance | More data, regularisation, a simpler model |
| Both fine, then production fails | Data shift or leakage | Fix the data, see Level 1000 |
Regularisation
Regularisation deliberately makes a model simpler by adding a penalty on large parameters:
With this is L2, or ridge. With this is L1, or lasso. They behave differently, and the reason is a pretty piece of geometry.
Adding a penalty is equivalent to forcing the parameters to stay inside a shape. The solution is where the error contours first touch that shape.
On a diamond, the solution tends to land near or on a corner, and at a corner some weights are exactly zero. So L1 performs feature selection, and L2 only shrinks. In Bayesian terms, L2 is a Gaussian prior on the weights and L1 is a Laplace prior.
Measuring properly
Accuracy misleads as soon as classes are unbalanced. With 1% fraud, a model that always answers “not fraud” is 99% accurate and useless. The confusion matrix gives the real picture.
| Predicted positive | Predicted negative | |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
| Metric | Formula | Meaning |
|---|---|---|
| Precision | TP / (TP + FP) | Of those flagged, how many were right |
| Recall | TP / (TP + FN) | Of the real ones, how many were found |
| F1 | Harmonic mean of the two | Punishes a low score in either |
| Specificity | TN / (TN + FP) | Of the real negatives, how many were cleared |
A classifier outputs a score, and a threshold turns it into a decision. Moving the threshold trades precision against recall.
AUC, the area under that curve, has a concrete meaning: the probability that a random positive scores above a random negative. It was 0.92 here. For rare positives, the precision-recall curve is usually more informative.
For regression, the common measures are MSE, RMSE, which is in the original units, MAE, which is more robust to outliers, and R², the share of variance explained.
Data problems
Most real failures live here.
Leakage is information in the training data that will not be available at prediction time. A hospital model that learns that patients with a certain scan machine are sicker has learned nothing about disease. Random splits of time series leak the future.
Imbalance is handled by reweighting the loss, resampling, or choosing the threshold deliberately.
Feature scaling matters whenever features have very different ranges. It makes the loss bowl rounder, which makes descent faster, and it is required for distance-based methods.
Encoding turns categories into numbers, using one-hot vectors or learned embeddings.
No free lunch. Averaged over all possible problems, no model beats any other. Every model works because its assumptions match the kind of structure that real data has. Those assumptions are called inductive bias, and picking a model means picking a set of assumptions.
Level 300: the classical toolkit
These methods are not obsolete. On tables of business data they often beat deep learning, and they train in seconds.
Each model below has a different idea of what a sensible boundary looks like. This figure shows four of them on one dataset, two interleaved crescents.
K-nearest neighbours
To classify a point, find the k closest training points and take a vote. There is no training step at all. It assumes that nearby points behave alike. Small k gives a jagged, high-variance boundary, and large k a smooth one.
The weakness is the curse of dimensionality. As dimensions grow, volume explodes, data becomes sparse, and the nearest point ends up almost as far away as the furthest, so distance stops meaning much.
Naive Bayes
Apply Bayes’ theorem and assume all features are independent given the class:
The assumption is plainly false, since words in an email are not independent, but it often classifies well anyway, because getting the ranking of classes right is easier than getting the probabilities right. It is fast and a strong baseline for text.
Decision trees
A tree asks a chain of yes or no questions, such as whether a value is above a threshold. Each split cuts space along one axis, so the decision regions are boxes, visible in the figure above.
At each node, the algorithm tries every feature and threshold, and it keeps the split that makes the two sides purest. Purity is measured by Gini impurity, , or by entropy, in which case the reduction is called information gain.
Trees are readable and need no feature scaling, but one tree grown deep has very high variance. The cure is to use many.
Ensembles: bagging and random forests
If you average many noisy, independent estimates, the noise cancels. Bagging trains many models on random resamples of the data and averages them. A random forest does this with trees, and also lets each split consider only a random subset of features, so that the trees disagree more. Averaging mostly cuts variance, and the method is hard to misconfigure.
Gradient boosting
Boosting works in sequence rather than in parallel. Fit a small tree, look at what it got wrong, and fit the next tree to the errors. Each tree corrects the sum of those before it.
For squared error, those errors are exactly the negative gradient of the loss with respect to the predictions, which explains the name: this is gradient descent, carried out in the space of functions instead of the space of parameters. Boosting mostly cuts bias.
XGBoost, LightGBM and CatBoost are the standard implementations, and they remain the usual first choice for tabular data.
Support vector machines
Many lines may separate two classes. A support vector machine picks the one with the widest empty corridor around it.
The points on the edge are the support vectors. Maximising the margin means solving:
The hinge loss allows some points to violate the corridor at a cost, which handles data that cannot be perfectly separated.
The famous extra is the kernel trick. Data that no line can split in two dimensions may be easy to split after being lifted into more dimensions. The training algorithm only ever uses dot products between points, so the dot product can be replaced by a function that computes it in a lifted space, without ever visiting that space. The RBF kernel corresponds to an infinite-dimensional one.
Choosing
| Model | Boundary | Needs scaling | Good for |
|---|---|---|---|
| Logistic regression | Flat | Yes | Baselines, interpretability |
| k-NN | Any, local | Yes | Small, low-dimensional data |
| Naive Bayes | Depends on the features | No | Text, fast baselines |
| Random forest | Boxes, averaged | No | Solid default on tables |
| Gradient boosting | Boxes, additive | No | Best accuracy on tables |
| SVM with RBF kernel | Smooth, curved | Yes | Small to medium datasets |
| Neural network | Learned | Yes | Images, text, audio, huge data |
Level 400: learning without labels
With no answers to copy, the task is to find structure.
K-means
Pick k centres, then alternate two steps: assign each point to its closest centre, and move each centre to the mean of its points.
Each step can only lower the total squared distance, so the algorithm always settles, though possibly at a poor solution, which is why it is restarted from several starting points or seeded with k-means++. It assumes round clusters of similar size. The elbow method and the silhouette score help to choose k.
Gaussian mixtures and EM
K-means makes a hard assignment. A Gaussian mixture model says that each point came from one of several bell-shaped distributions, and gives each point a probability of belonging to each. It is fitted with expectation-maximisation: guess the memberships, then refit the Gaussians to them, and repeat. K-means is the hard, round special case of this.
The pattern of alternating between guessing hidden variables and improving parameters returns later in variational autoencoders.
Other clustering
Hierarchical clustering repeatedly merges the closest groups, producing a tree called a dendrogram, which can be cut at any level. DBSCAN defines clusters as dense regions, so it finds arbitrary shapes and marks sparse points as noise, and it needs no k.
PCA
Real data often has fewer true dimensions than features. Principal component analysis finds the directions along which the data spreads the most.
Formally, these directions are the eigenvectors of the data’s covariance matrix, and the eigenvalues are the variance along each. Everything from Level 50 pays off here: covariance is a matrix, a matrix is a transformation of space, and the eigenvectors are the axes of the ellipse the data forms. In practice it is computed with the singular value decomposition. Projecting on to the top directions is also, among all flat projections, the one with the lowest reconstruction error.
t-SNE and UMAP
PCA is linear, so it cannot unroll a curled sheet. t-SNE and UMAP build a low-dimensional map that keeps neighbours near each other. They are excellent for looking at embeddings. They should be read with care, though, because distances between clusters and cluster sizes on these maps often mean very little.
Anomaly detection
Fit what normal looks like, then flag whatever fits badly. Isolation forests use the fact that outliers take few random splits to isolate. One-class SVMs fit a boundary around normal data, and an autoencoder flags inputs it reconstructs poorly.
Association rules and recommendation
Apriori finds items that occur together in transactions. Collaborative filtering factorises a huge, sparse user-by-item matrix into a user vector and an item vector, whose dot product predicts a rating. This idea of learning embeddings, and using dot products to compare them, is one of the most reused in the field.
Level 500: neural networks
Logistic regression draws a flat cut. Stacking simple units gives a function that can draw nearly anything.
A neuron
A neuron is a dot product followed by a bend:
The dot product scores how well the input matches the neuron’s weights. The bend , the activation function, is essential. Without it, stacked layers collapse into one, because a composition of linear maps is just another linear map. Depth would add nothing.
| Activation | Formula | Notes |
|---|---|---|
| Sigmoid | Saturates, so gradients vanish in deep stacks | |
| Tanh | Centred on zero, still saturates | |
| ReLU | Simple and fast, the default for a decade | |
| GELU | Smooth ReLU | Common in transformers |
Two views of what a network does
The first view is about curves. A ReLU unit is a hinge, a flat line that bends upward at one point. Adding hinges together builds a curve from straight pieces.
This is the intuition for the universal approximation theorem: one hidden layer with enough units can approximate any continuous function on a bounded region as closely as wanted. The theorem says that such a network exists. It does not say how to find it, or that it would be small. In practice, depth gives far more than width, because each layer can fold what the previous one produced, so the number of linear regions grows exponentially with depth.
The second view is about space, and it is the deeper one. Each layer is a matrix, which moves space, followed by a bend, which warps it. A trained network keeps warping until the classes pull apart.
The final layer of a classifier is only logistic regression. All the rest of the network is a machine for finding a representation in which logistic regression works. That is why it is called representation learning, and it is the real reason deep learning displaced hand-built features.
Backpropagation
A network may have billions of parameters, and each step needs the gradient of the loss with respect to all of them. Nudging each parameter one by one would take billions of forward passes per step.
Backpropagation gets all of them in about the cost of two passes. Run the network forward, keeping each intermediate value. Then walk backward through the layers, using the chain rule at each one, and reuse the result from the layer after it. Each parameter’s gradient asks: how much would the final loss change if this number moved? It is a product of sensitivities along every path from that parameter to the loss.
This is a special case of reverse-mode automatic differentiation. PyTorch and JAX record the operations and do the backward walk themselves.
Here it is written out by hand, for the XOR problem, which no single flat cut can solve:
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], float)
y = np.array([[0], [1], [1], [0]], float)
rng = np.random.default_rng(1)
W1, b1 = rng.normal(0, 1, (2, 4)), np.zeros((1, 4))
W2, b2 = rng.normal(0, 1, (4, 1)), np.zeros((1, 1))
sigmoid = lambda z: 1 / (1 + np.exp(-z))
for step in range(2001):
# forward
h = np.tanh(X @ W1 + b1)
p = sigmoid(h @ W2 + b2)
loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
# backward: the chain rule, last layer first
e = (p - y) / len(X)
dW2, db2 = h.T @ e, e.sum(0, keepdims=True)
dh = (e @ W2.T) * (1 - h ** 2)
dW1, db1 = X.T @ dh, dh.sum(0, keepdims=True)
# update
for param, grad in ((W1, dW1), (b1, db1), (W2, dW2), (b2, db2)):
param -= 0.5 * grad
if step in (0, 200, 500, 2000):
print(step, round(loss, 4), p.ravel().round(3))
0 0.6712 [0.5 0.659 0.464 0.554]
200 0.0379 [0.011 0.962 0.958 0.057]
500 0.0114 [0.002 0.988 0.987 0.018]
2000 0.0024 [0. 0.997 0.997 0.004]
The four outputs move to 0, 1, 1, 0, which is XOR. With the random seed set to 0 instead, the same program stalled at a loss of 0.3487 and got two of the four cases stuck at 0.5. So the starting point matters. A landscape this small can trap a run, and that risk fades as networks grow.
Optimisers
The real gradient is computed over all the data, which is too expensive, so each step uses a random mini-batch of perhaps 32 to 1024 examples. This is stochastic gradient descent. The noise is not only tolerated, it often helps by jolting the model out of sharp valleys.
Loss landscapes are often long narrow valleys. Plain descent bounces between the walls and creeps along the floor. Momentum keeps a running velocity, so that the bouncing cancels out and the steady direction builds up:
Adam goes further. It tracks both a running mean of the gradient and a running mean of its square, and gives each parameter its own effective step size. It works well with little tuning and is the usual default. AdamW fixes how Adam applies weight decay.
The learning rate usually changes during training. Warmup raises it from near zero to avoid early instability, and cosine decay lowers it smoothly towards the end.
Keeping deep networks trainable
Depth creates a specific danger. Gradients are long products, and a long product of numbers below 1 shrinks to nothing, while numbers above 1 blow up. These are the vanishing and exploding gradient problems. Most of the tricks in deep learning exist to keep those products near 1.
| Technique | What it does |
|---|---|
| Initialisation (Xavier, He) | Sets random weights so that signal variance stays constant through layers |
| ReLU | Has a slope of exactly 1 when active |
| Residual connections | Add a direct path, , for gradients to flow through |
| Batch normalisation | Rescales activations across a batch |
| Layer normalisation | Rescales within one example, used in transformers |
| Gradient clipping | Caps the size of a gradient |
Residual connections deserve a moment. A layer that needs to do nothing can simply output zero and pass its input through. This made networks with hundreds of layers trainable, and nearly every modern architecture uses them.
For generalisation, the common tools are weight decay, early stopping, data augmentation and dropout, which randomly silences units during training so that no unit can rely too heavily on another. It behaves like an ensemble of many thinner networks.
Level 600: architectures
A plain fully connected network treats input as an unordered list. Real data has structure, and the great architectures build that structure into the model. Each is a set of assumptions about the world.
Convolutional networks
An image has two properties worth exploiting. Pixels matter mostly in relation to their neighbours, and a cat is still a cat if it moves left. A convolution slides one small set of weights across the whole image, computing a dot product at each position:
A filter that matches a vertical edge produces a map of where vertical edges are. Sharing one filter across all positions cuts parameters enormously, and means that a pattern learned in one place is known everywhere. Pooling then shrinks the map. Stacking these grows each unit’s receptive field, so that early layers see edges, middle layers see textures and parts, and late layers see objects.
The landmarks are LeNet (1998), AlexNet (2012), which started the deep learning boom, VGG, and ResNet (2015), which brought residual connections. The companion article on this site, Neural networks and CNNs, explained, goes through all of this in detail.
Recurrent networks
For sequences, a recurrent network keeps a hidden state and updates it at each step:
The same weights are shared across time. Training unrolls the loop, which makes it a very deep network, and gradients vanish over long sequences. LSTM and GRU add gates that control what to keep, forget and output, with an additive memory path that works much like a residual connection.
Their weaknesses are that they run one step at a time, which limits parallelism, and that everything must squeeze through one state vector.
Embeddings
Neural networks need numbers, and words are not numbers. An embedding gives each token a learned vector. word2vec trained these by predicting a word from its neighbours, based on the idea that words appearing in similar contexts have similar meanings. The result places words in a space where direction carries meaning, as in the well-known example where king minus man plus woman lands near queen.
The idea reaches far beyond words. Users, products, images, code and molecules can all be embedded, and then search means finding nearby vectors, which is the job of vector databases and of extensions such as pgvector for PostgreSQL.
Attention
Take the sentence “the cat sat because it was tired”. To understand “it”, a model has to look back at “cat”. Attention lets every token look at every other token and decide what is relevant.
Each token gets three learned vectors. A query is what it is looking for. A key is what it offers. A value is what it passes along. A token’s output is an average of all the values, weighted by how well its query matches each key:
That one line has everything from earlier levels in it: dot products measure agreement, softmax turns them into weights, and a matrix multiplication mixes the values. The division by stops the dot products growing with dimension, which would otherwise saturate the softmax.
Multi-head attention runs several of these in parallel, so that different heads can track different relationships.
Transformers
A transformer block is attention, followed by a small fully connected network applied to each token, with residual connections and layer normalisation around both. Stack dozens of these, and you have the architecture behind modern language models.
Attention has no sense of order, because it treats its input as a set. Positional encodings add order back. A causal mask stops each token looking at later tokens, which is what makes a transformer able to predict what comes next.
Compared with recurrent networks, a transformer processes all positions in parallel on a GPU and connects any two positions in a single step. The cost is that attention grows with the square of the sequence length, and a lot of data is needed, because it builds in fewer assumptions than a CNN. Vision Transformers split an image into patches and treat those as tokens.
Graph neural networks
Molecules, social networks and code do not fit into grids or sequences. A graph neural network has each node collect messages from its neighbours, combine them and update itself. After k rounds, each node knows about its k-hop neighbourhood. A CNN is a special case on a grid, and a transformer is close to the fully connected case.
Architectures as assumptions
| Architecture | Assumes | Shares weights across |
|---|---|---|
| Fully connected | Nothing | Nothing |
| CNN | Locality, translation | Space |
| RNN | Sequential order | Time |
| Transformer | Relevance can be computed by content | Positions |
| GNN | Relations are given by a graph | Nodes and edges |
Level 700: generative models
A classifier learns . A generative model learns , the distribution of the data itself, so it can sample new examples. The problem is that an image is one point in a space with millions of dimensions, and real images occupy a vanishingly small, thin part of it.
Autoencoders
An autoencoder squeezes input through a narrow bottleneck and tries to rebuild it. The bottleneck forces it to keep what matters. On its own it does not generate well, because the space of codes has gaps, and a random code decodes to junk.
Variational autoencoders
A VAE encodes each input as a small cloud rather than a point, and pushes all clouds towards one standard Gaussian. Its loss has two terms, which together are the evidence lower bound:
The first term rewards accurate reconstruction. The second keeps the code space smooth and filled, so that sampling from a Gaussian and decoding gives something sensible. The reparameterisation trick, writing , lets gradients pass through the random sampling.
GANs
A generative adversarial network sets two networks against each other. The generator turns noise into samples, and the discriminator tries to tell those samples from real data. Each one’s improvement forces the other’s. GANs give sharp images and fast sampling, but training is unstable, and they can suffer mode collapse, in which the generator produces only a few outputs.
Diffusion
Diffusion starts from an observation that sounds like a trick. Destroying an image with noise is easy, and if you know how to undo one tiny step of noise, you can undo all of them.
The forward process adds a little Gaussian noise over many steps. There is a closed form for jumping directly to any step , where falls from 1 to almost 0:
A network is trained on one very simple job: given a noisy input and , predict the noise that was added.
To generate, start from pure noise and subtract the predicted noise a bit at a time. Each small step is easy, so a hard problem has been broken into a thousand easy ones. The predicted noise also points towards higher data probability, which connects diffusion to score matching.
Text-to-image systems add a text embedding to the input, and classifier-free guidance exaggerates its effect. Latent diffusion runs the whole process in a VAE’s compressed space to save compute. Flow matching is a newer, closely related approach, which learns a direct path from noise to data.
Choosing
| Family | Training | Sampling | Sample quality | Likelihood |
|---|---|---|---|---|
| VAE | Stable | Fast | Often blurry | Lower bound |
| GAN | Unstable | Fast | Sharp | None |
| Normalising flow | Stable | Fast | Moderate | Exact |
| Diffusion | Stable | Slow without tricks | Excellent | Available |
Large language models
A language model is a transformer trained on one task: predict the next token. It is self-supervised, because the text supplies its own labels.
Tokenising. Text is split into pieces of roughly word size, which then become integers and embeddings.
Training. The model learns from the cross-entropy between its predicted next-token distribution and the real next token, across enormous amounts of text. A second stage, often reinforcement learning from human feedback, shapes it towards helpful behaviour.
Generating. The model produces a distribution, one token is sampled, it is appended, and the process repeats. Temperature, along with top-k and top-p sampling, controls how much risk that sampling takes. Each new token reuses earlier work through the KV cache, covered in the GPU track on this site.
Using them. Three main methods adapt a model to a task. Prompting gives instructions and examples at run time. Retrieval-augmented generation finds relevant documents using embeddings and places them in the prompt, which reduces invented answers. Fine-tuning retrains the weights on specific data, and LoRA does this cheaply by learning small low-rank updates.
Making them smaller. Quantisation stores weights in fewer bits, pruning removes small ones, and knowledge distillation trains a small model to imitate a large one.
Language models have clear weaknesses. They can state false things confidently, they have a limited view of their own uncertainty, and they follow instructions embedded in the data they read, which is the root of prompt injection.
Level 800: reinforcement learning
Here no one provides answers. An agent acts, sees what happens, and gets a reward, sometimes long after the action that earned it.
The framing
The setting is a Markov decision process. There are states, actions, transition probabilities and rewards, and the next state depends only on the current state and action. The agent follows a policy and wants to maximise the discounted return:
The discount , just below 1, makes near rewards worth more than distant ones, and keeps the sum finite.
Value and the Bellman equation
The value of a state is the return expected from it. The key insight is that value is recursive: the value here equals the immediate reward plus the discounted value of wherever you land next. This is the Bellman optimality equation:
When the rules are known, sweep this equation over all states repeatedly, and values spread outward from the rewards, like ink through water.
Q-learning
Usually the rules are unknown, so the agent learns from experience. Q-learning learns the value of each action in each state, moving its estimate towards what it just observed:
The bracket is the temporal difference error, the surprise between what was predicted and what happened. Here is a corridor of five squares, with a reward at the right end:
import numpy as np
rng = np.random.default_rng(0)
Q = np.zeros((5, 2)) # five squares in a line; actions: left, right
for episode in range(500):
s = 0
while s != 4:
a = rng.integers(2) if rng.random() < 0.2 else Q[s].argmax()
next_s = max(0, s - 1) if a == 0 else s + 1
reward = 1 if next_s == 4 else 0
Q[s, a] += 0.1 * (reward + 0.9 * Q[next_s].max() - Q[s, a])
s = next_s
print(Q.round(2))
[[0.65 0.73]
[0.66 0.81]
[0.73 0.9 ]
[0.81 1. ]
[0. 0. ]]
The right-hand column reads 0.73, 0.81, 0.9, 1.0. Those are powers of the discount, 0.9, learned from nothing but trial and error.
That code also shows the central tension. Exploitation uses the best action known so far, and exploration tries others in case something better exists. Here, 20% of moves are random, which is called epsilon-greedy. Multi-armed bandits are the simplest setting for this trade-off, with one state and several options. They are often used for testing product variants, with algorithms such as UCB and Thompson sampling.
Deep reinforcement learning
Chess and images have far too many states for a table. DQN replaced the table with a neural network, and learned Atari games from pixels. It needed two tricks to be stable: experience replay, which trains on shuffled memories rather than on correlated recent frames, and a slowly updated target network.
Policy gradient methods learn the policy directly, by raising the probability of actions in proportion to how well they turned out:
Actor-critic methods combine both, with an actor that chooses and a critic that estimates value to cut noise. PPO limits how far each update can move the policy, which makes it stable and widely used. AlphaGo and AlphaZero combined deep networks with Monte Carlo tree search, learning by self-play.
Level 900: other paradigms worth knowing
Transfer learning. Take a network trained on a large dataset, keep its layers, and retrain the top on a small one. Early features such as edges carry over. This is usually the first approach to try when data is limited.
Self-supervised learning. Contrastive methods such as SimCLR pull two augmented views of one image together in embedding space and push others apart, learning useful representations with no labels.
Semi-supervised learning. Pseudo-labelling lets a model label confident unlabelled data and train on it.
Active learning. The model asks for labels on the examples it is least sure about, which saves labelling cost.
Multi-task learning. One network with several outputs shares what it learns between related tasks.
Meta-learning. Learning how to learn, usually so that a model adapts from only a few examples.
Federated learning. Training happens on devices, and only updates are shared, so that raw data stays put.
Online learning. The model updates continuously from a stream of data.
Bayesian methods. Rather than one best set of parameters, these keep a distribution over them, giving honest uncertainty. A Gaussian process is a distribution over functions, and predictions come with error bars. They work well on small data, and they power Bayesian optimisation, which tunes hyperparameters efficiently.
Time series. ARIMA models trend and autocorrelation directly. Gradient boosting with lagged features is a strong practical choice, and transformers are used at scale. The golden rule is that validation must always run forward in time.
Causal inference. Correlation answers what happens when you see X. Causal questions ask what happens when you change X, and those require experiments, or methods such as propensity scores and instrumental variables. A model can predict perfectly and still mislead decisions.
Neural architecture search and AutoML. These automate model and hyperparameter choice.
Multimodal models. These combine text, images and audio, usually with embeddings placed in a shared space.
Agents. A language model calls tools in a loop, deciding what to do next from what it observes. Much of the engineering here concerns limiting what it can do.
Level 1000: production and the edges of understanding
What happens after training
A notebook model is perhaps a tenth of the work. Running it reliably is the rest, and the discipline is called MLOps.
| Stage | What it involves |
|---|---|
| Data | Versioned datasets, validation, feature stores |
| Training | Tracked experiments, reproducible runs |
| Evaluation | Slice-based tests, comparison with current production |
| Deployment | Shadow mode, canary rollout, A/B tests |
| Serving | Batching, caching, latency budgets |
| Monitoring | Input drift, output drift, delayed ground truth |
Drift. The world changes. Data drift means inputs have shifted. Concept drift means the relationship between inputs and answers has shifted, as when fraudsters adapt. Models go stale silently, without errors.
Calibration. A model is calibrated if, among predictions of 80%, about 80% come true. Modern networks are often overconfident. Temperature scaling on a validation set is a simple fix, and this matters wherever a probability feeds a decision.
Hardware. Training and inference are dominated by matrix multiplication, which is why they run on GPUs. Fast inference is limited as much by memory as by compute. The GPU track on this site covers this from silicon upward.
Interpretability
SHAP credits each feature for a prediction, based on Shapley values from game theory. LIME fits a small simple model around one prediction. Saliency maps show which pixels influenced an output, and partial dependence plots show the average effect of one feature. All of these explain a model, not the world, so correlated features can mislead.
Fairness
A model trained on biased history can reproduce it. Removing a sensitive attribute is not enough, since other features act as proxies. The common fairness definitions, such as equal error rates between groups and calibration within groups, are mathematically impossible to satisfy all at once when base rates differ. So fairness requires a choice, and that choice is not purely technical.
Security
Models are software with an unusually large attack surface.
| Attack | How it works |
|---|---|
| Adversarial examples | Tiny, targeted input changes flip a prediction |
| Data poisoning | Corrupted training data plants a backdoor |
| Model extraction | Repeated queries copy a model |
| Membership inference | Queries reveal whether a record was in training data |
| Prompt injection | Text in the input overrides a language model’s instructions |
| Malicious model files | Loading a pickle-based file can run code |
Adversarial examples follow directly from Level 50. The gradient that training uses to change weights can be used to change the input instead. One step in the direction of the sign of that gradient, known as FGSM, is often enough to flip a label while staying invisible to a person:
The last row of that table is what SynapseOS on this site is built to test.
Double descent
Level 200 said that too much capacity causes overfitting. Modern networks have far more parameters than data points, fit their training data perfectly, and still generalise. For decades that looked impossible.
The experiment below uses 100 training points with some label noise, and random-feature models of growing width, fitted with the minimum-norm solution.
At the peak, only one solution fits the data, and it has to contort itself to do it. Beyond that point, many solutions fit, and the fitting procedure picks a smooth one. So the implicit preference of the optimiser acts as a regulariser. The classical U-shaped curve is only the left part of a longer story.
What is still not understood
Several basic questions remain open or partly answered:
- Why does generalisation work so well? Classical theory gives bounds too loose to explain modern networks.
- Why are the landscapes so easy? Non-convex optimisation should be hard, yet simple descent succeeds. Partial explanations involve saddle points being more common than bad minima in high dimensions.
- What is the role of sharpness? Flat minima are thought to generalise better, but the picture is disputed.
- How much of intelligence is scale? Larger models have improved far beyond early expectations, and how long that continues is open.
- How can a model know what it does not know? Reliable uncertainty for large models remains hard.
- Why does a language model answer as it does? Mechanistic interpretability tries to read this directly from the weights, and it is still early work.
The map
The whole field, on one page:
| Problem | Start with |
|---|---|
| Table of business data | Gradient boosting |
| A small dataset | Logistic regression, then a random forest |
| Images | A pretrained CNN or Vision Transformer |
| Text classification | Embeddings and a simple model, or a pretrained transformer |
| Text generation | A language model with retrieval |
| Finding groups | K-means, then a density method |
| Visualising high dimensions | PCA, then UMAP |
| Choosing actions | Bandits first, then reinforcement learning |
| Forecasting | A seasonal baseline, then boosting |
| Anomalies | Isolation forest |
Every model in this article, from the first straight line to a language model, is the same four-part recipe from Level 0: data, a family of functions, a measure of wrongness, and a way of going downhill. The families grew richer, and the assumptions got cleverer, but the recipe did not change.