Study from the inside out
The inner region begins with familiar objects. Outer stars introduce more advanced connections. These are approximate study levels, not exact prerequisites; active research exists at every level.
THE MATH OF AI / LAYER TWO
The layer above taught you to translate an equation into a sentence. This one builds the subject underneath it, in the order the ideas actually depend on each other — starting from what a number is and ending at the questions nobody has answered yet.
Explore 265 ideas across 16 constellations, from numbers and logic to geometry, dynamics and learning theory. Select a star to see its meaning, connections and available lessons.
The brighter stars have an AI connection listed here. Follow a guided path, search for a topic, or explore a branch. This is a curated atlas with an emphasis on AI foundations; its proportions do not measure how much of all mathematics AI uses.
265 of 265 matching ideas
Skip to the selected idea ↓Select a star to explore. Zoom in, then drag to travel. Arrow keys move between matching stars. Rings mark study level; narrow the filters to name every matching star, or read them all in the topic index below.
Distance suggests a study level, not a difficulty score or a count of prerequisites. Stars in the background are decorative; the selectable stars are catalogue entries.
All the partial derivatives collected into a vector pointing steepest uphill.
In AI · ∇L(θ). The direction training walks away from.
In the world · A ball on a hillside rolls along the negative gradient.
Study this idea in this guide →The inner region begins with familiar objects. Outer stars introduce more advanced connections. These are approximate study levels, not exact prerequisites; active research exists at every level.
A branch gives an idea a home on the map. Connections cross those boundaries: eigenvalues appear in linear algebra, probability, physics and optimization. Select a star to distinguish what it builds on from what it leads to.
The AI filter highlights the applications recorded in this atlas. An unmarked star may still have applications elsewhere. A ring around a star means there is a lesson you can open from its detail card.
There is one more thing worth noticing before you scroll on. Trace any glowing dot back through what it is built on and you will land, within a few steps, in the middle of the circle — at counting, at sets, at the idea of a variable. There is no separate advanced mathematics that AI runs on. It is the ordinary material, composed further than usual.
It is tempting to skip this. Do not. Every rounding error, every NaN in a training run, and every choice between float32 and bfloat16 is a consequence of the gap between the numbers mathematics describes and the numbers a machine can hold.
Do not learn these as a list of definitions. Learn them as a sequence of failures: at each rung somebody asked a reasonable question, found the numbers they had could not answer it, and invented the ones that could.
RUNG 01 · NATURAL NUMBERS
A weight is a real number in the mathematics and a floating-point approximation in the machine — a fixed budget of bits, so only finitely many values exist and everything else is rounded to the nearest one.
A tenth cannot be written exactly in binary, just as a third cannot be written exactly in decimal. Relative error at bfloat16: 0.391%.
This is not a bug in JavaScript; every language using IEEE 754 agrees. It is why loss curves are compared with tolerances rather than equality, why the order of a summation can change its result, and why mixed-precision training needs care about which numbers stay wide.
Calculus is built on limits, and a limit is the value a sequence is heading towards. If the line had holes in it, a sequence could head straight at a hole and have nowhere to land — the limit would not exist. Completeness is the property that guarantees the destination is always there.
That is the whole reason the reals are the setting for derivatives, and therefore for training. The floating-point numbers below are full of holes, which is why the machine can only ever approximate the thing the mathematics describes.
Exponents and logarithms carry more weight in this field than anything else at this level, and they are usually rushed. An exponent is repeated multiplication; a logarithm answers the reverse question, what power produces this number? Four rules follow, and each one earns its place later on this page.
| Rule | What it does | Why AI needs it |
|---|---|---|
log(ab) = log a + log b | Turns multiplying into adding. | Why the likelihood of a whole dataset becomes a sum you can differentiate. |
log(a/b) = log a − log b | Turns dividing into subtracting. | KL divergence is an average of log(p/q), which is why it reads as a difference of surprises. |
log(aⁿ) = n log a | Pulls an exponent down to the front. | How a product over n tokens becomes an average, and how perplexity is defined. |
log is monotonic | Bigger in, bigger out — always. | Maximising the log-likelihood and maximising the likelihood give the same answer, so you may always take the log. |
The first rule is the one that matters most. The probability of a whole dataset is a product of millions of small numbers, which underflows to zero in any real arithmetic and has a useless derivative besides. Take the log and the product becomes a sum: numerically stable, and differentiable term by term. Almost every loss function you will meet is a log for that reason alone.
Everything symbolic begins here. The moment you can write x instead of a particular number, you can state a rule that holds for every number at once — and that generality is the whole reason mathematics is worth the notation.
Three letters, three different jobs. Move each slider and watch which part of the picture responds.
Because of when they change. Within one prediction, x varies from example to example while w and b sit still — so the line is fixed and the input moves along it. During training it reverses: the data is held fixed and w and b are the things being adjusted. Same symbols, two different roles depending on which loop you are inside. Getting that straight removes most of the confusion in reading an ML paper.
The equation in that lab is y = wx + b, which is the same equation the layer above translated as “take the input, multiply it by its importance, add an adjustment.” It is also, exactly, one neuron. Everything from here is that expression scaled up and composed with itself.
Sets tell us what belongs. Logic tells us which statements follow. These ideas sit underneath array masks, probability events, graph structures and mathematical proofs.
Universe U = {1, 2, 3, 4, 5, 6}. Let A contain the even numbers and B contain the numbers greater than 3. A complement is always relative to a stated universe.
Intersection requires both conditions, giving {4, 6}. Union requires at least one, giving {2, 4, 5, 6}. Logical OR includes the case where both conditions hold.
“For every input x, there exists a suitable model θ” permits a different model for each input. “There exists one model θ that works for every input x” asks for a single shared model. Switching ∀ and ∃ changes the problem.
A proof establishes a claim from stated assumptions. One counterexample defeats a universal claim: x = −2 refutes “x² ≥ x implies x ≥ 0.” Checking many examples is useful evidence, but does not prove a statement about all real numbers.
Prove a base case, then show that truth at n implies truth at n + 1. For example, 1 + … + n = n(n + 1)/2 extends by adding n + 1 to both sides. This is a proof method, distinct from statistical induction from observations.
A graph G = (V, E) has vertices V and edges E. A directed computational graph records which operations depend on which earlier values. A connected undirected graph without cycles is a tree; choosing a root gives it a hierarchy. A graph adjacency matrix and a neural weight matrix are both arrays, but their entries have different meanings.
Further study: MIT Mathematics for Computer Science ↗It is a very short list of moves you are permitted to make, plus the judgement of which one gets you closer. Most people who believe they are bad at algebra were taught the tricks without the list.
Start from 3x + 4 = 19. Do the same thing to both sides and the scales stay level, whatever that thing is. Your goal is to reach the one arrangement that reads x = something.
Legal and useful are different tests. Any operation applied to both sides preserves the truth of the equation, so × 2 is perfectly valid — it just leaves you no closer to x on its own. Solving is a search through legal moves toward one particular shape: x alone on one side. That distinction reappears everywhere in this field. A gradient step is always legal; whether it helps depends on the step size. A model is always allowed to fit the training set; whether that helps depends on what you were trying to do.
| Move | Why it is allowed | What it is for |
|---|---|---|
| Add the same thing to both sides | The two sides were equal; adding equally to each keeps them equal. | Move a term across the equals sign. |
| Subtract the same thing from both sides | Same reason, running backwards. | Strip away a bias term to isolate what multiplies x. |
| Multiply both sides by the same non-zero number | Scaling both sides by the same factor preserves equality. Zero is excluded because it destroys information: 0 = 0 is true of everything. | Clear a fraction. |
| Divide both sides by the same non-zero number | The inverse of the move above. | Turn 3x into x. |
| Replace anything with something equal to it | Substitution. If u = 2x + 1, then anywhere you see 2x + 1 you may write u. | This one move is what makes the chain rule readable. |
That is the entire definition, and the “one” is the load-bearing word: feed in the same input twice and you must get the same answer. A neural network, all hundred billion parameters of it, is one function.
√x refuses negatives over the reals; log x refuses zero and below; division refuses a zero denominator. Most NaN losses are a function being handed something outside its domain.
A sigmoid can only emit values in (0, 1), which is exactly why it can stand for a probability. Matching a range to a meaning is most of the reason to choose one activation over another.
f(g(x)) means do g, then f. A deep network is composition repeated dozens of times, and the chain rule is how you differentiate through it.
Composition is the idea that makes depth mean something — and it comes with a warning. Compose two affine layers and you get another affine layer: W₂(W₁x + b₁) + b₂ = (W₂W₁)x + (W₂b₁ + b₂), which is one affine layer with different weights and bias. A hundred stacked linear layers are worth exactly one. Putting a nonlinear function between them is what buys you depth, and it is the only reason activation functions exist.
| Family | Shape | Where it shows up in AI |
|---|---|---|
| Linear | A straight line through the space | Every layer's matrix multiply |
| Polynomial | Curves with turning points | Squared-error loss; Taylor approximations of everything else |
| Exponential | Doubling, then doubling again | softmax, decay schedules, likelihoods |
| Logarithm | The exponential run backwards | Cross-entropy, log-likelihood, perplexity |
| Sigmoid / tanh | An S, squashed into a fixed range | Gates, binary probabilities, older hidden layers |
| Piecewise linear | Straight segments joined at corners | ReLU — cheap, and non-linear enough to work |
People are told that calculus is the mathematics of machine learning. Linear algebra is the one you will read on day one — it is what every shape in your code means, and what a forward pass is written in. Calculus explains how training works; linear algebra explains what is being trained.
A vector is an ordered list of numbers — and also an arrow. Both readings matter: the list is what the machine stores, the arrow is what lets you reason about it.
Nearly aligned: the dot product is close to its largest possible value.
Two neurons, three inputs. Each neuron has its own row of weights, and each output is one dot product plus a bias. Writing the rows as a matrix W turns both neurons into the single expression Wx + b.
0.5×1.0 + -1×2.0 + 2×0.5 + 0.1= -0.4001.5×1.0 + 0.25×2.0 + -0.5×0.5 + -0.2= 1.550Three multiplications and two additions per neuron. A real layer does the identical thing with matrices of millions of entries, which is the entire reason GPUs matter: not because the mathematics is hard, but because there is so much of it and all of it can run at once.
Because it is the cheapest honest answer to “how much of this is in that?”. It collapses two lists into a single number measuring alignment, it is linear in each argument, and on modern hardware thousands of them run at once. Attention scores are dot products. Cosine similarity is a dot product with the lengths divided out. A neuron is a dot product plus a bias. A matrix product is a grid of dot products. Learn this one operation properly and a surprising share of the notation in a paper stops being notation.
These are the words a paper will use without explaining. None is difficult; each is a small fact about what a matrix does.
| Term | What it is | Where it shows up |
|---|---|---|
| Transpose · Aᵀ | Flip the grid across its diagonal; rows become columns. | For a linear operation, its backward pass multiplies by the transpose of the forward matrix. That is not a coincidence — it is what the chain rule requires. |
| Identity · I | Ones down the diagonal, zeros elsewhere. It changes nothing. | A residual block x + F(x) has Jacobian I + JF, giving an additional gradient route without guaranteeing stable gradients. |
| Inverse · A⁻¹ | For a square matrix, the inverse exists exactly when its columns are linearly independent. | Solving least squares in closed form; whitening a covariance. |
| Rank | How many genuinely independent directions the matrix has. | LoRA freezes the big weight matrix and learns a low-rank update instead — fine-tuning gets cheap because the update turns out not to need full rank. |
| Determinant · det A | The factor by which volume is scaled. Zero means space gets flattened. | The change-of-variables term in a normalising flow. |
| Span & basis | Everything reachable by combining a set, and a smallest set that reaches it all. | What a layer can represent at all; the axes PCA selects. |
| Trace · tr A | Sum of the diagonal, which also equals the sum of the eigenvalues. | Appears throughout matrix calculus identities. |
“How big is this vector” has several answers, and the choice is not cosmetic — it decides what a penalty does to your model.
| Norm | Its unit ball | What it does in AI |
|---|---|---|
| L1 · Σ|vᵢ| | A diamond | An L1 penalty can favor exact zeros at an optimum. Sparsity depends on the objective, penalty strength and solver. |
| L2 · √Σvᵢ² | A circle | Ordinary length. Weight decay, gradient clipping, the distance behind cosine similarity. |
| L∞ · max|vᵢ| | A square | Worst-case bounds; the radius used in adversarial robustness. |
| Frobenius · √ΣAᵢⱼ² | L2, applied to a matrix | How far two weight matrices are apart; the size of an update. |
The singular value decomposition writes any matrix as a sum of simple rank-one pieces, ordered by how much they matter. Keep the first few and you keep most of the content. This gives an optimal low-rank approximation in Frobenius norm. PCA applies related geometry to centered data; LoRA learns low-rank weight updates rather than computing a truncated SVD.
The first singular value alone carries 53% of the content. Note what happens past rank 8: you are storing more numbers than the original had, so compression stops being a saving. Low rank saves storage only when k is small enough relative to the matrix dimensions; whether the approximation is useful depends on the singular-value spectrum and task.
LoRA starts from an observation: the change a fine-tune makes to a big weight matrix is close to low-rank. So instead of learning all d×d numbers, you learn two thin matrices whose product has rank r, and add it on. With d = 4096 and r = 8 that is 65 thousand numbers instead of 17 million — the same trade you are making with the slider, applied to a weight update rather than a picture. It only works because real matrices, like the letter above, carry most of their content in their first few singular directions.
Choose w to minimize ‖Xw − y‖². The residual at an optimum is orthogonal to the column space: Xᵀ(Xw − y) = 0. A unique coefficient solution requires full column rank; the pseudoinverse selects a minimum-norm solution otherwise. In code, use a solver instead of forming an explicit inverse.
Center the feature columns, write X = UΣVᵀ, and project onto the first k columns of V. Their squared singular values, divided by n − 1, are sample covariance eigenvalues. PCA preserves maximal variance among rank-k orthogonal projections; large variance need not be useful predictive signal.
It has a reputation for difficulty that comes almost entirely from how it is taught: rules first, meaning later, if ever. There is really one question — when this changes a little, how much does that change? — and everything else is technique for answering it without doing arithmetic by hand every time.
Drive 120 km in 2 hours and your average speed is 60 km/h. You divided a change in position by a change in time. Every derivative you will ever meet is that same division.
What is your speed at one instant? In an instant, no time passes and you travel no distance, so the division becomes 0 ÷ 0 — which is not a number. The question is good; the arithmetic is not ready for it.
Measure over an interval of width h, which is a perfectly ordinary division. Then ask what the answer approaches as h gets smaller. Not what it is at h = 0 — what it is heading towards.
For f(x) = x², the quotient works out to exactly 2x + h. There is no mystery about where it is going: as h shrinks, it heads to 2x. That limit is the slope of the curve at that point.
f′(x) = 2x says: nudge the input near x, and the output moves about 2x times as much. At x = 3 the output moves six times as fast as the input. That is the reading that matters for AI.
A loss depends on millions of weights. Ask about one at a time: nudge w₇ and hold everything else fixed. That is a partial derivative. Collect one per weight and you have the gradient.
The gradient vector aims in the direction of steepest increase, and its length says how steep. To reduce the loss, step the other way. That single sentence is gradient descent, and the whole of training.
Average speed is easy: distance ÷ time. Speed at an instant looks impossible, because in an instant nothing happens — you get 0 ÷ 0, which is not a number. The move that rescues it is to refuse the impossible division and watch where the possible ones are heading.
A wide gap measures the average slope across a whole stretch of curve, which is not yet the slope at a point. Shrink h.
For x² the quotient simplifies to exactly 2x + h — no limit language needed to see where it is going. As h shrinks, the h on the end shrinks with it and 2x is what remains. That is the derivative, and every rule you will memorise later is this same calculation done once, in general, so you never have to repeat it.
f′(x) is a sensitivity. It says: nudge the input a little near x, and the output moves about f′(x) times as much. At x = 3 on the curve x², the output moves six times as fast as the input. Training asks exactly this question about a loss and a weight — if I nudge this number, how much does the error move, and in which direction? — a few hundred billion times per step.
Because two different things are happening at once. Mathematically, smaller h means a better estimate, all the way down. Numerically, f(x+h) and f(x) are two nearly identical floating-point numbers, and subtracting them throws away almost every significant digit you had — then you divide that wreckage by a tiny number, which magnifies it.
Watch the error fall to roughly 1e-8 and then climb again. The best h is a compromise between the two effects, near the square root of machine precision. This is why real frameworks do not estimate gradients this way: backpropagation applies the chain rule with floating-point arithmetic, and finite differences are kept for checking that the exact code is right.
Every differentiation rule is the limit above, worked out once in general so nobody has to repeat it. Knowing that they are derived rather than decreed is worth more than knowing the list.
| Rule | Statement | Read it as |
|---|---|---|
| Power | d/dx (xⁿ) = n·xⁿ⁻¹ | The one you will use constantly. |
| Sum | (f + g)′ = f′ + g′ | Sensitivities add. This is why a loss summed over a batch has a gradient summed over the batch. |
| Product | (fg)′ = f′g + fg′ | Vary one factor at a time, then add the two effects. |
| Chain | (f∘g)′ = f′(g(x))·g′(x) | The important one. Sensitivities multiply along a chain. |
| Exponential | d/dx (eˣ) = eˣ | A function that is its own rate of change — which is what makes e the natural base. |
| Logarithm | d/dx (ln x) = 1/x | Why log-losses are pleasant to differentiate. |
Three stages in a row. Push a nudge of size δ into the front and measure what arrives at each stage. Nothing here is more advanced than multiplication — the point is what gets multiplied.
du/dx ≈ 2.0000 · exactly 2.0000
dv/du ≈ 6.0200 · exactly 6.0000
dy/dv ≈ 3.0000 · exactly 3.0000
The overall sensitivity is the product of the local sensitivities. That is the entire chain rule, and it is why deep networks have the failure modes they do: multiply many numbers below one and the gradient vanishes before it reaches the early layers; multiply many above one and it explodes. Careful initialisation, normalisation layers and residual connections are all, at bottom, attempts to keep this product near one.
A network has one loss and millions of weights. Going forwards, you would trace a separate chain from every weight to the loss — millions of passes. Going backwards, you compute how the loss responds to the last layer, then reuse that to get the layer before it, and so on: every weight's gradient falls out of a single sweep. That reuse is the whole algorithm. Backpropagation is not a different rule from the chain rule; it is the chain rule evaluated in the order that shares the most work.
Pick a function and add terms one at a time. The polynomial grips the curve at zero first, then bends to match its slope, then its curvature, then creeps outward.
Converges everywhere, but you need more terms the further out you look.
Everything, and it is usually left unsaid. Gradient descent replaces the loss near your current weights with its first-order Taylor approximation — a flat plane — and steps along it; the learning rate exists because that plane is only trustworthy nearby. Newton's method keeps the second-order term as well, so it models the curve as a bowl and can jump straight to its bottom, which is why it needs far fewer steps and why each one costs a Hessian. Every optimiser you will meet is a choice about how many Taylor terms you can afford.
Three words get used constantly and are rarely distinguished. They are the same derivative, arranged differently as the number of inputs and outputs grows.
| Object | Shape | Answers | In AI |
|---|---|---|---|
| Gradient ∇f | A vector, one entry per input | How one output responds to every input | What an optimiser steps along. |
| Jacobian J | A matrix, outputs × inputs | How every output responds to every input | Reverse-mode backpropagation propagates a vector–Jacobian product (equivalently Jᵀv in column notation), without building the full Jacobian. |
| Hessian H | A matrix, inputs × inputs | How the gradient responds to every input — curvature | Describes local curvature. For a positive-definite quadratic, its largest eigenvalue sets the plain-gradient-descent stability bound. Large models often use Hessian–vector products. |
Curvature is worth dwelling on, because it explains a daily frustration. If the loss curves sharply in one direction and gently in another, a single learning rate cannot suit both: large enough to make progress along the flat direction, it oscillates along the sharp one. For a positive-definite quadratic, the ratio of the largest to smallest Hessian eigenvalue measures this conditioning. Neural losses need not have a positive-definite Hessian, and adaptive updates do not directly compute this curvature.
Not by hand, not symbolically, and not by finite differences. A framework records every operation you perform into a computational graph, then applies the chain rule backwards through it — reverse-mode automatic differentiation. The results are exact to floating-point precision, and one backward sweep produces the gradient for every parameter at once.
Exact, and the expressions explode in size for anything deep. Fine for a textbook, hopeless for a network.
What the lab above does. Simple, approximate, and needs one forward pass per parameter — useless at a billion of them, but still the standard way to check that a gradient is right.
Exact, and one sweep covers every parameter. This is what PyTorch and JAX do, and why .backward() is a single line.
The derivative breaks a total into rates. The integral puts rates back into a total, and the fundamental theorem of calculus says the two operations undo each other — which is genuinely surprising, because “slope of a curve” and “area under a curve” have no obvious reason to be related.
You need far less of it than of differentiation. It matters where it defines something: an expectation E[X] = ∫ x p(x) dx is an integral, a continuous probability is an area under a density, and the evidence term in Bayes' rule is an integral that is usually impossible to compute — which is precisely why variational methods and sampling exist. You will need to recognise integrals constantly and evaluate them almost never.
A probabilistic classifier can output a distribution over possible labels, and training grades how surprised that distribution was by the truth. Probability is what makes both halves of that sentence precise.
A network's last layer emits raw scores, which can be any real numbers. Two steps turn them into a claim you can grade: softmax makes them a probability distribution, then cross-entropy measures how surprised that distribution is by the truth.
Now say which answer was actually correct. The loss looks only at the probability given to that one.
Roughly right but unconvinced. There is a real gradient here, which is where learning happens.
Read the loss in bits and it has a plain meaning: the number of yes/no questions' worth of surprise the model felt on seeing the right answer. Zero bits means it already knew.
Three reasons, and they all matter. First, a model that assigns probability 0.001 to the truth is far worse than one assigning 0.3, but 1 − p barely distinguishes them (0.999 against 0.7); −log p rates them 6.9 against 1.2. Confident and wrong is the failure worth punishing hardest, and only the log punishes it without limit.
Second, independent probabilities multiply, and logs turn multiplication into addition — so the loss over a whole dataset becomes a sum, which is what makes it differentiable and cheap to work with. Third, minimising −log p is exactly maximising likelihood, so the training objective inherits a century of statistics rather than being invented for the occasion.
A random variable maps outcomes to values. Before observing the outcome we describe its distribution; after observing it we have a realization.
E[X] weights every possible value by its probability. Nearly every loss you will meet is an expectation estimated from a sample — which is exactly what a mini-batch is.
P(A|B) = P(B|A)P(A) / P(B). New evidence reweights what you already believed; it does not replace it.
Two ideas from information theory follow immediately and are worth meeting by name. Entropy is the average surprise of a distribution — how uncertain it is. Cross-entropy is the average surprise your predicted distribution feels when reality is drawn from the true one. Minimising it is the same as maximising likelihood, which is why the standard classification loss is not an arbitrary choice but the statistically principled one.
The mean says where a distribution sits. Variance says how widely it spreads, and its square root, the standard deviation, puts that back in the original units. Covariance measures how two centered quantities vary together. Collect the pairwise covariances into a matrix: PCA diagonalizes it, and whitening transforms it toward identity when the required directions are nondegenerate. A multivariate Gaussian requires both a mean vector and a covariance matrix.
Draw n numbers uniformly between 0 and 1 and average them. At n = 1 the histogram is flat, because that is what uniform means. Watch what happens as n grows — nothing about the underlying distribution has changed.
Two things are happening, and they are worth separating. The spread narrows like 1/√n — that is the law of large numbers, and it is why a bigger mini-batch gives a steadier gradient. The shape becomes Gaussian regardless of what you started from — that is the central limit theorem, and it is why the bell curve describes measurement error, heights, and the sum of many small effects in almost any system you look at. Nobody chose the Gaussian for its convenience. It is what averaging does.
A neuron sums n terms, each roughly independent. Variances of independent things add, so the sum's variance is about n times one term's — meaning the signal grows by √n at every layer, and after thirty layers it has exploded or vanished. Scaling weight standard deviation proportionally to 1/√n controls this factor under the independence and activation assumptions; it does not guarantee preserved variance throughout training. Xavier and He initialisation are this argument with the activation function accounted for. It is one of the highest-value things on this page: a two-line variance calculation that decides whether a deep network trains at all.
A distribution is a shape of uncertainty. You do not need many.
| Name | Set by | What it describes | Where it appears in AI |
|---|---|---|---|
| Bernoulli | p | One flip of a biased coin. | Binary classification; a dropout mask on one unit. |
| Categorical | p₁…p_k | One choice among k options. | Exactly what softmax emits, and what next-token sampling draws from. |
| Uniform | a, b | Every value in a range equally likely. | Shuffling, random initialisation, the raw material of every sampler. |
| Gaussian | μ, σ² | The bell curve, fixed entirely by its mean and variance. | Weight initialisation, VAE latents, and the noise a diffusion model adds and then learns to remove. |
| Poisson | λ | Counts of rare events in a fixed window. | Modelling arrival counts; some token-frequency models. |
| Exponential | λ | Waiting time to the next event, with no memory of how long you have waited. | Survival and time-to-event models. |
| Beta / Dirichlet | α | Distributions over probabilities themselves. | Bayesian priors; topic models; Dirichlet routing in some mixtures of experts. |
Given data and a family of distributions, which member produced it? Maximum likelihood answers: pick the parameters maximizing the observed data's probability mass or density. Take the log — by that first rule from chapter one — and for independent observations the product over examples becomes a sum, and maximising it becomes minimising its negative. That negative log-likelihood is cross-entropy. The standard loss was not invented for neural networks; it is a century-old statistical principle arriving under a different name.
Add a prior belief about the parameters and you get MAP estimation instead — and a Gaussian prior on the weights turns out to be exactly an L2 penalty. This equivalence is between particular penalty terms and log priors; not every regularization method is simply MAP estimation.
Reality is fixed at P. Move the model's scores to change Q and watch three quantities that are usually taught as separate things turn out to be one equation.
This is the payoff of the previous lab. Cross-entropy — the loss you actually minimise — splits cleanly into the entropy of the data, which no model can do anything about, and the KL divergence, which is entirely the model's fault. Training can only ever drive the second term down. When a loss curve flattens above zero, that floor is H(P): the data was ambiguous and no parameters will fix it.
Because it asks a one-sided question: how much extra surprise do you suffer by using Q when reality is P. Swapping the roles asks a different question, so it gets a different number — try the swap button and watch them diverge. It is not a metric, and calling it a distance is a convenient lie.
The asymmetry has teeth. Minimising KL(P‖Q) over the data punishes Q for assigning near-zero probability to anything that really happens, so Q spreads out to cover everything — that is maximum likelihood, and it is why generative models produce blurry averages. Minimising KL(Q‖P) instead punishes Q for putting mass where P has none, so Q collapses onto one mode and ignores the rest. Same two distributions, opposite failure modes, chosen by which way round you write it.
Probability starts with a model and asks what observations it produces. Statistics uses observations to estimate quantities, compare explanations and assess uncertainty under assumptions.
The population is the group or distribution you want to describe. A sample is what you observed. Its mean x̄ = Σxᵢ/n summarizes its center; a median is a middle ordered value and is less sensitive to extreme observations. Neither summary repairs selection bias.
An estimator is a rule applied to a sample. Its bias is E[θ̂] − θ; its variance describes changes across repeated samples. For squared error, MSE(θ̂) = bias² + variance. These expectations are over the sampling process.
Assume IID normal observations with mean μ = 10 and known standard deviation σ = 2. Each line is an illustrative interval x̄ ± 1.96σ/√n from a simulated sample mean. We reuse 40 fixed standardized draws as n changes to isolate the effect of sample size.
Four times as many observations halves the standard error under these assumptions. With unknown σ, estimate it from the sample and use an appropriate method, such as a t interval for IID normal data. Dependence or a biased sample needs additional care.
In this frequentist model, the mean is fixed and the interval varies with the sample. The procedure covers the true mean in 95% of repeated independent samples under the model. A realized interval either covers it or does not.
The first is measured on particular rows. The second is an expectation under the target distribution. Fitting the first does not automatically minimize the second. A representative held-out sample estimates future performance; distribution shift can break that connection.
| Tool | What it answers | Important condition |
|---|---|---|
| Confidence interval | Uncertainty from a specified repeated-sampling procedure | Sampling and model assumptions determine coverage. |
| Hypothesis test | How unusual a statistic is under a specified null model | A p-value is not the probability that the null is true. Many comparisons require error control. |
| Cross-validation | Development performance across held-out folds | Fit preprocessing inside each training fold. Use group or time splits when observations require them. |
| Final test set | An evaluation after selecting the procedure | Do not use its outcomes to select parameters or stopping times. |
Learning theory formalizes when empirical performance transfers to population performance. PAC learning specifies error and confidence; VC dimension measures the capacity of binary hypothesis classes. These are useful next destinations in the map, with assumptions that deserve as much attention as the formulas.
Further study: Understanding Machine Learning, chapters 2–6 ↗Optimisation is where the previous chapters stop being separate subjects. A function built from matrix operations, differentiated by the chain rule, against a loss defined using probability — and then stepped downhill, over and over.
The loss is L(w) = (w − 3)² + 1, its slope is L′(w) = 2(w − 3), and the rule is w ← w − α·L′(w). Everything in this chapter and the last two now runs at once: a function, its derivative, and a step size.
Converging, approaching from one side.
For this loss the arithmetic is transparent: each step multiplies the distance from the minimum by exactly 1 − 2α. Below 0.5 you approach steadily; at 0.5 you arrive in one step; between 0.5 and 1 you overshoot but still shrink; at 1 you bounce forever; above 1 you leave. A learning rate is not a vague dial for how fast you learn — it is a concrete multiplier on your remaining error, and in a real network it is one of these per direction of curvature at once.
For this parabola you can: set the derivative to zero, get w = 3, done. That works because the function is simple and convex. A neural network's loss has hundreds of billions of parameters, no closed-form solution, and a landscape that is not bowl-shaped, so there is no equation to solve — only a direction to follow. Descent asks the cheap local question, which way is down from here?, and accepts that it will never prove it found the best point. That it works as well as it does is genuinely not fully explained, which is why it appears in the open-questions chapter below.
For a convex objective on a convex domain, every local minimum is global. Least-squares linear regression and standard logistic negative log-likelihood are convex in their coefficients. Step sizes and regularity still matter for convergence.
A landscape of valleys, ridges and saddles. Typical neural-network objectives are non-convex. A local improvement does not certify global optimality; guarantees depend on specific assumptions about the objective and algorithm.
The full empirical gradient averages the whole dataset. Uniform minibatch sampling estimates it at lower cost per update; sampling noise can help or hinder, depending on the problem. That is the S in SGD.
Each rule turns a gradient into an update. Plain SGD has no optimizer memory; momentum and adaptive methods keep state across steps.
| Optimiser | Update | The idea |
|---|---|---|
| SGD | θ ← θ − α·g | The plain step. g is the gradient from one mini-batch. |
| Momentum | v ← βv + g; θ ← θ − α·v | Accumulate an exponentially weighted sum of past gradients. Consistent directions reinforce one another; β controls how fast history decays. |
| RMSProp | s ← βs + (1−β)g²; θ ← θ − α·g/(√s + ε) | Divide by the recent size of each parameter's gradient, so every parameter gets a step scaled to its own terrain. |
| Adam | both, plus bias correction | Momentum on the gradient and RMSProp on its square, with a correction because both averages start at zero and are biased low early on. |
Second-order methods use curvature as well as slope. A Newton step solves HΔ = −g. Fast local convergence requires conditions on smoothness, curvature and the starting point; an indefinite Hessian may not produce a descent direction. Quasi-Newton and matrix-free methods reduce the cost. Adam instead tracks gradient moments: it is not a Hessian approximation.
Two weights. The ellipses are the loss, lowest at the dot in the middle. The shaded shape is your budget: the weights must stay inside it. The answer is wherever the smallest reachable ellipse touches the shape — and the shape of the budget decides where that touch happens.
The diamond has corners on the axes, and a corner is where a shrinking ellipse touches first. w₂ is not small — it is zero, and that feature has been removed from the model entirely.
L1 can select: the constraint has corners on the axes, which can favor sparse optima. L2 constrains overall length: it usually gives a dense solution. Effects on generalization require evaluation; neither shape guarantees that the resulting model will improve.
For plain SGD without momentum, adding (λ/2)‖w‖² gives w ← (1 − αλ)w − αg. This equals decoupled shrinkage with the matching coefficient and learning rate. For Adam they come apart, because Adam divides by the recent gradient magnitude and that division also rescales the penalty term, so the effective decay differs per parameter. AdamW exists precisely to fix this: it applies the shrinkage separately, outside the adaptive scaling. That is the entire content of a paper people cite constantly, and it is a consequence of the algebra rather than a new idea.
Equivalent formulas can behave differently with finite precision. Separate the sensitivity of the mathematical problem from the numerical behavior of the method used to solve it.
An ill-conditioned problem can amplify small input perturbations even when solved carefully. For an invertible matrix, κ₂(A) = σmax(A)/σmin(A). A nearly zero smallest singular value means some information is almost lost.
A numerically stable method controls the effect of rounding. Subtracting nearly equal quantities can lose relative accuracy; exponentiating a large number can overflow. A stable algorithm cannot remove a problem's inherent ill-conditioning.
Start with scores [1, 2, 3]. Adding the same constant to all scores cannot change their softmax probabilities mathematically. Direct exponentiation can overflow in the browser's floating-point arithmetic.
| Class | Logit | Direct softmax | Shifted softmax |
|---|---|---|---|
| 1 | 1 | 0.090031 | 0.090031 |
| 2 | 2 | 0.244728 | 0.244728 |
| 3 | 3 | 0.665241 | 0.665241 |
Every numerator and the denominator are multiplied by the same positive factor e⁻ᵐ, so the ratio is unchanged in exact arithmetic. The shifted exponents are at most zero, avoiding exponential overflow. Very small probabilities can still underflow; log-sum-exp lets us compute log losses directly.
This is the chapter the rest of the guide exists for. No component of an AI system is built from one branch of mathematics; each one is a specific recipe, and seeing the recipes is what turns a pile of topics into a subject.
Look up a part of a system to see what it is made of, or look up a concept to see everywhere it turns up. The second direction is the more useful one once you start learning: it tells you what a week of study actually buys.
Turns several inputs into one number.
w₁x₁ + w₂x₂ + … + b is arithmetic with named quantities. Nothing more advanced is happening at this level.
Linear algebra, without much doubt. It appears in more rows of this map than anything else, it is what the shapes in your code actually mean, and it is the language the forward pass is written in — you meet it on the first day and never stop. Calculus is second because it explains training rather than architecture, and probability third because it explains the loss and what a prediction claims. Optimisation is last because it is where the other three combine, and it is hard to appreciate before you have them.
| Part | What it does | Mathematics it combines |
|---|---|---|
| One neuron | Turns several inputs into one number. | Variables · Multiplication · Addition · Functions |
| A layer | Runs thousands of neurons at once. | Linear algebra · Functions |
| A nonlinearity | Lets depth actually buy you something. | Functions · Composition |
| A loss | Turns “how wrong” into one number. | Probability · Information theory · Logarithms |
| Training | Improves the parameters. | Calculus · Chain rule · Linear algebra · Optimization · Probability |
| Attention | Lets a position read from other positions. | Linear algebra · Dot products · Probability · Exponentials |
| Embeddings and retrieval | Makes meaning comparable. | Vectors · Inner products · Norms · Geometry |
| Convolution | Recognises a pattern anywhere in an image. | Linear algebra · Symmetry · Signal processing |
| Diffusion models | Generates an image from noise. | Probability · Stochastic processes · Differential equations · Calculus |
| Numerical stability | Stops the arithmetic from ruining the model. | Real analysis · Floating-point arithmetic · Logarithms |
Every tool in this guide predates the field, most of them by centuries, and was built to answer a question about the physical world. That is not trivia — it is the strongest evidence that you are learning something durable rather than the notation of one passing technology.
In AI: How much the loss moves when a weight moves.
In the world: Velocity is the derivative of position; acceleration is the derivative of velocity. Marginal cost in economics, reaction rate in chemistry, the slope of an epidemic curve — all the same operation.
In AI: Step downhill on the loss surface until the model stops improving.
In the world: Water finds the valley. A soap film pulls itself to minimal area. Light takes the fastest path. Physics is full of systems that settle into a minimum, and the mathematics is the same mathematics.
In AI: Principal components, spectral norms, whether a recurrent network explodes or forgets.
In the world: The frequencies a bridge will resonate at, the stable modes of a vibrating drum, the ranking behind PageRank, the long-run state of a Markov chain.
In AI: Softmax, cross-entropy, log-likelihood, learning-rate decay.
In the world: Compound interest, radioactive half-life, bacterial growth, the decibel scale, the Richter scale. Wherever a quantity's rate of change is proportional to itself, e shows up.
In AI: The model outputs a distribution; the loss is its surprise at the truth.
In the world: Statistical mechanics describes a gas by a distribution over states rather than by tracking every molecule. Insurance, polling, quality control and quantum mechanics all take that same step.
In AI: The core operation of a vision network.
In the world: A camera blurring an image, a room adding echo to a sound, a moving average smoothing a noisy time series. All one operation: slide, multiply, add.
In AI: Wasserstein distances between distributions; the transport view of diffusion models.
In the world: Its original question, posed in 1781, was how to move a pile of earth into a new shape with the least total effort. The logistics problem and the generative-model problem are the same problem.
There is a genuine puzzle underneath this, and it is worth sitting with rather than resolving too quickly. Mathematics developed for one purpose keeps turning out to describe something else entirely — the physicist Eugene Wigner called it the unreasonable effectiveness of mathematics in the natural sciences. Complex numbers were a bookkeeping device for solving cubics before they were the language of quantum mechanics. Non-Euclidean geometry was a curiosity before it was general relativity. Whatever you learn here has a strong track record of being useful somewhere you did not expect.
Deep learning works considerably better than the theory explains. The gap between what practitioners can build and what mathematicians can prove is the honest state of the field, and it is wider than most introductions admit. Each area below lists the level it asks of you, because “open problem” is not the same as “inaccessible”.
Reviewed on . These are directions of sustained work rather than a snapshot of this month, and each links the paper that framed the question rather than the latest result — deliberately, because the framing outlives the leaderboard.
A network with far more parameters than training examples can fit random labels perfectly — so classical capacity bounds cannot explain why the same network generalises on real labels. Test error can even fall again after the interpolation point, which the classical bias–variance picture does not predict.
Level: Entry: undergraduate probability and statistics. Frontier: high-dimensional probability, concentration inequalities, PAC-Bayes.
Zhang et al., Rethinking generalization ↗There is no theorem promising that SGD finds a good minimum of a deep network's loss, yet it reliably does. Training also tends to drift to the boundary of stability rather than settling somewhere comfortable, which ordinary optimisation theory does not predict.
Level: Entry: multivariable calculus. Frontier: dynamical systems, stochastic differential equations, random matrix theory.
Cohen et al., Edge of Stability ↗As width goes to infinity, training behaves like a fixed kernel method — the Neural Tangent Kernel — which is exactly solvable. It is also the wrong regime for explaining feature learning, so the open work is finding limits that stay tractable while keeping what matters.
Level: Entry: linear algebra and calculus. Frontier: kernel methods, functional analysis, tensor programs.
Jacot et al., Neural Tangent Kernel ↗Loss falls as a power law in parameters, data and compute across many orders of magnitude, and those curves are accurate enough to plan training runs against. What mechanism produces a power law, and what determines its exponent, is not settled.
Level: Entry: logarithms and curve fitting. Frontier: statistical physics, approximation theory, information theory.
Hoffmann et al., Training compute-optimal LLMs ↗Universal approximation says a large enough network can represent almost anything, which is nearly useless as engineering guidance — it says nothing about what training will find. Sharper work asks what attention can compute at a given depth and width, and why examples in a prompt change behaviour without changing a single weight.
Level: Entry: linear algebra and probability. Frontier: approximation theory, circuit complexity, learning theory.
von Oswald et al., Transformers learn in-context by gradient descent ↗Diffusion and flow-matching models are increasingly described as learning to move one probability distribution onto another along a path. That framing has produced faster samplers and cleaner objectives, and connects image generation to a problem first posed about moving piles of earth.
Level: Entry: probability and calculus. Frontier: optimal transport, measure theory, SDEs.
Song et al., Score-based generative modeling through SDEs ↗Convolution works because a cat is a cat wherever it appears in the frame. Geometric deep learning takes that observation seriously and derives architectures from the symmetries of the data — grids, graphs, groups, manifolds — rather than discovering them by trial.
Level: Entry: linear algebra. Frontier: group and representation theory, differential geometry.
Bronstein et al., Geometric Deep Learning ↗Interpretability work increasingly treats a network's internal state as a sparse combination of directions, with more features packed in than there are dimensions to hold them. Recovering those directions is a dictionary-learning problem, and how far the linear picture holds is open.
Level: Entry: linear algebra. Frontier: sparse coding, compressed sensing, high-dimensional geometry.
Elhage et al., Toy Models of Superposition ↗The most common mistake is starting with calculus because that is what the field is said to require. The second is trying to be rigorous before anything means anything. Here is the order that works, with a test for each stage so you are not guessing.
Before anything else: move terms across an equals sign without hesitating, handle fractions, and read powers and logs as operations rather than decoration. This is the layer everything else silently assumes.
You are ready to move on when: You can rearrange y = wx + b to solve for w without thinking about it.
This is the order people get wrong. The forward pass of every network is a matrix product; you will read shapes and dot products on day one and derivatives on day thirty. Vectors, dot products, matrix multiplication, and what a matrix does to space.
You are ready to move on when: Given shapes (32, 784) and (784, 128), you can say what comes out and why.
One idea, approached properly: the derivative as sensitivity of output to input. Then the chain rule, then partial derivatives, then the gradient. Do not detour into integration techniques — they are beautiful and you do not need them yet.
You are ready to move on when: You can explain why backpropagation is the chain rule, out loud, to someone else.
Random variables, distributions, expectation, independence, conditional probability and Bayes' rule, then likelihood and log-likelihood. This is what turns a score into a loss and a prediction into a claim about uncertainty.
You are ready to move on when: You can say why cross-entropy loss is −log(p) and why the log belongs there.
Gradient descent, learning rates, momentum, why convexity matters and why deep learning does not have it. At this point the four earlier layers combine and the training loop stops being a black box.
You are ready to move on when: You can explain what a learning rate that is too large actually does to the update.
Only once the machinery makes sense is it worth the formal treatment: proofs, epsilon–delta limits, measure-theoretic probability, convex analysis. Doing it in this order means the abstractions land on something you already understand.
You are ready to move on when: You want the proof, rather than being told you need it.
Deisenroth, Faisal and Ong. Built in exactly the order above, and free as a PDF.
3Blue1Brown. The geometric intuition first, which is the part textbooks skip.
3Blue1Brown. Derives the ideas rather than presenting them finished.
Gilbert Strang's lectures, problem sets and exams, all open.
A complete first calculus course with worked solutions.
Blitzstein's probability course. Strong on building intuition for distributions.
For filling specific gaps with exercises rather than lectures.
Boyd and Vandenberghe. The reference once optimisation becomes the thing you care about.