Lesson 3.1 · Stage 03: The maths behind machine learning
The maths roadmap for AI: scratch to expert
Every maths topic AI uses, organised into pillars and five levels from prerequisites to expert, with what each one is used for.
How to use this roadmap
Study the pillars in the order below and, inside each pillar, go L1 → L4. Practitioner level needs L0–L2; expert level adds L3 everywhere and L4 in one specialisation.
| Level | What it lets you do | Typical concepts | |
|---|---|---|---|
| L0 Prerequisites | Read the notation | Algebra, functions, logs, Σ notation, proofs | |
| L1 Core | Use ML libraries with understanding | Vectors, matrices, derivatives, basic probability and statistics | |
| L2 Intermediate | Derive and debug standard models | Matrix calculus, SVD, MLE/MAP, cross-entropy, KL, Adam | |
| L3 Advanced | Read papers and implement them from scratch | Duality and KKT, variational inference, MCMC, learning theory | |
| L4 Expert | Do research in one specialisation | Measure theory, SDEs, optimal transport, differential geometry |
Learning order
- Level 0 prerequisites.
- Linear algebra L1 and Calculus L1, side by side.
- Probability L1, then Statistics L1.
- Calculus L2 (multivariable and matrix calculus) and Linear algebra L2.
- Probability and Statistics L2, Optimization L2, Information theory L2.
- Numerical methods, Signal processing and Discrete math to L2, as your ML topics need them.
- L3 across pillars: optimization theory, inference, learning theory, RL.
- L4 in one specialisation track (see the expert section).
Each concept below is a checkbox: tick it when you can explain it and implement it in NumPy or PyTorch. “AI:” marks where the concept is used in practice.
Concepts and formulas are standard textbook mathematics. Level placement and learning order are my recommendations.
Level 0 — Prerequisites
Everything later assumes these school-level skills, so refresh them first; gaps here slow every other pillar.
- Number systems — integers, rationals, reals; complex numbers a + bi. AI: complex numbers return in Fourier analysis and RoPE.
- Algebraic manipulation — expanding, factoring, solving linear and quadratic equations, inequalities, absolute value.
- Functions — domain, range, composition f(g(x)), inverse and piecewise functions. AI: a network is a composition of functions; ReLU is piecewise linear.
- Graphs of functions — linear, polynomial, exponential, logarithmic and S-shaped curves; slopes and asymptotes.
- Exponents and logarithms — eˣ, ln x, log(ab) = log a + log b, log(aᵇ) = b·log a. AI: log-likelihoods turn products into sums; softmax uses eˣ.
- Summation and product notation — Σ and Π, indices, double sums. AI: a loss is a Σ over examples; a likelihood is a Π.
- Sequences and series — arithmetic and geometric series; Σ rᵗ (t = 0 to ∞) = 1/(1 − r) for |r| < 1. AI: discounted returns in RL.
- Trigonometry — radians, unit circle, sin, cos, basic identities. AI: sinusoidal position encodings, rotations, Fourier analysis.
- Coordinate geometry — distance formula, lines, planes, hyperplanes. AI: a linear classifier is the hyperplane w·x + b = 0.
- Sets and logic — ∈, ⊂, ∪, ∩, Cartesian product; and, or, not, implication, ∀, ∃. AI: reading paper notation.
- Basic counting — factorials, permutations, combinations.
- Proof basics — direct proof, contradiction, induction; spotting a theorem’s assumptions.
- Notation literacy — θ̂ (an estimate), arg min / arg max, ∝ (proportional to), x ~ p (x sampled from p), E[·], ‖·‖.
Linear algebra
Linear algebra is the language of AI: data, weights, embeddings and activations are all vectors, matrices and tensors. A dense neural-network layer is y = Wx + b followed by a nonlinearity.
L1 · Core
- Scalars, vectors, matrices, tensors — shapes and dimensions; a tensor is an n-dimensional array. AI: an image batch is a 4-D tensor (batch × channels × height × width in PyTorch).
- Vector operations — addition, scalar multiplication, linear combinations.
- Dot product — a·b = Σ aᵢbᵢ = ‖a‖‖b‖cos θ. AI: neuron pre-activations, attention scores, similarity.
- Vector norms — L1 = Σ|xᵢ|, L2 = √(Σxᵢ²), L∞ = max|xᵢ|. AI: L1/L2 regularisation, gradient clipping.
- Distance and similarity — Euclidean, Manhattan, cosine similarity a·b / (‖a‖‖b‖). AI: k-NN, clustering, embedding search.
- Matrix operations — addition, multiplication (inner dimensions must match), transpose, element-wise (Hadamard) product ⊙.
- Broadcasting — how NumPy and PyTorch stretch shapes in element-wise operations. AI: adding a bias vector to a whole batch.
- Matrix as a linear transformation — the columns of A show where the basis vectors land. AI: every dense layer.
- Special matrices — identity, diagonal, symmetric, triangular, orthogonal (QᵀQ = I), sparse.
- Systems of linear equations — Ax = b, Gaussian elimination, row echelon form.
- Inverse and determinant — A⁻¹ exists iff det A ≠ 0; det A is the volume scaling factor. AI: Gaussian densities, normalizing flows.
- Span, linear independence, basis, dimension.
- Rank and the four fundamental subspaces — column space, null space, row space, left null space. AI: low-rank structure, LoRA.
L2 · Intermediate
- Vector spaces and linear maps — formal definitions, change of basis.
- Orthogonality and projections — projection onto the column space of X is X(XᵀX)⁻¹Xᵀ. AI: least squares is an orthogonal projection.
- Gram–Schmidt and QR decomposition — A = QR with orthonormal Q. AI: stable least squares, orthogonal initialisation.
- Eigenvalues and eigenvectors — Av = λv, det(A − λI) = 0, diagonalisation A = PDP⁻¹. AI: PCA, PageRank, RNN stability.
- Spectral theorem — a real symmetric matrix is A = QΛQᵀ with real eigenvalues and orthonormal eigenvectors. AI: covariance matrices, Hessians.
- Quadratic forms and positive (semi)definite matrices — xᵀAx > 0 (≥ 0) for all x ≠ 0. AI: covariance and kernel matrices are PSD; a PSD Hessian means convexity.
- Singular value decomposition (SVD) — any matrix A = UΣVᵀ. AI: PCA, recommender systems, latent semantic analysis, compression.
- Low-rank approximation (Eckart–Young) — truncated SVD is the best rank-k approximation. AI: LoRA intuition, model compression, denoising.
- PCA, the math — eigenvectors of the covariance matrix (or SVD of centred data); variance explained = λᵢ / Σλ.
- LU and Cholesky decompositions — A = LU; A = LLᵀ for positive definite A. AI: sampling multivariate Gaussians, Gaussian processes.
- Moore–Penrose pseudo-inverse — A⁺ = VΣ⁺Uᵀ, the least-squares solution for any A.
- Trace — tr(A) = Σaᵢᵢ = Σλᵢ; cyclic: tr(ABC) = tr(CAB). AI: matrix-calculus derivations.
- Matrix norms — Frobenius, spectral (largest singular value), nuclear (sum of singular values). AI: spectral normalisation in GANs, low-rank regularisation.
- Condition number — κ(A) = σ_max / σ_min. AI: why ill-conditioned problems train slowly and lose precision.
L3 · Advanced
- Kronecker product and vec operator — vec(AXB) = (Bᵀ ⊗ A) vec(X). AI: matrix calculus, K-FAC and Shampoo optimisers.
- Einstein summation (einsum) — index notation for tensor contractions. AI: writing attention and custom layers.
- Tensor decompositions — CP, Tucker, tensor-train. AI: compressing layers and embedding tables.
- Non-negative matrix factorisation (NMF) — V ≈ WH with W, H ≥ 0. AI: topic modelling, parts-based features.
- CUR decomposition and leverage scores — approximate A using actual columns and rows. AI: interpretable low-rank features, attribute and row importance.
- Rayleigh quotient and Courant–Fischer theorem — xᵀAx / xᵀx is maximised by the top eigenvector. AI: why PCA works, spectral clustering.
- Generalised eigenproblems — Av = λBv. AI: Fisher’s linear discriminant, canonical correlation analysis.
- Schur complement, Woodbury identity, Sherman–Morrison — cheap inverses of block or updated matrices. AI: Gaussian conditioning, Gaussian processes, Kalman filters.
- Matrix exponential — e^A = Σ Aᵏ / k!. AI: continuous-time models, state space models (S4, Mamba).
- Perron–Frobenius theorem — a positive matrix has a unique largest eigenvalue with a positive eigenvector. AI: Markov chains, PageRank.
- Johnson–Lindenstrauss lemma — n points fit in O(log n / ε²) dimensions with distances kept within 1 ± ε. AI: random projections, approximate nearest-neighbour search.
L4 · Expert
- Krylov methods — power iteration, Lanczos, Arnoldi, conjugate gradient. AI: top Hessian eigenvalues of a network, large-scale PCA.
- Randomised numerical linear algebra — sketching, randomised SVD. AI: factorising matrices too large for exact SVD.
- Matrix perturbation theory — Weyl’s inequality, Davis–Kahan sin θ theorem. AI: stability of PCA and spectral methods.
- Random matrix theory — Marchenko–Pastur and Wigner semicircle laws. AI: weight-spectrum analysis, initialisation theory.
- Matrix Lie groups — SO(3), SE(3) and their Lie algebras. AI: equivariant networks for 3-D data, molecules, robotics.
- Multilinear and exterior algebra — tensors as multilinear maps, wedge products, determinants as oriented volumes.
Calculus
Calculus is how models learn: training computes the gradient of a loss and steps against it. Backpropagation is the chain rule applied across a computation graph.
L1 · Core (single variable)
- Limits and continuity — what f(x) approaches; where a function is smooth or breaks.
- Derivative — f′(x) = lim (h → 0) [f(x + h) − f(x)] / h: slope and rate of change.
- Differentiation rules — power, sum, product, quotient, chain rule (f∘g)′(x) = f′(g(x))·g′(x). AI: the chain rule is backpropagation.
- Derivatives of AI functions — eˣ, ln x, sigmoid σ′ = σ(1 − σ), tanh′ = 1 − tanh², ReLU (0 or 1; undefined at 0, a subgradient is used), softplus.
- Stationary points — maxima, minima, saddle points; the second-derivative test.
- Integrals — antiderivatives, definite integrals as area, Fundamental Theorem of Calculus. AI: probabilities and expectations of continuous variables.
- Integration techniques — substitution, integration by parts.
- Taylor series — f(x) ≈ f(a) + f′(a)(x − a) + ½ f″(a)(x − a)². AI: why gradient descent and Newton’s method work.
- Asymptotic behaviour — limits at infinity; growth rates of exponentials, polynomials and logs.
L2 · Intermediate (multivariable and matrix calculus)
- Functions of many variables — level sets and contour plots. AI: picturing loss landscapes.
- Partial derivatives — ∂f/∂xᵢ with the other variables held fixed.
- Gradient — ∇f = (∂f/∂x₁, …, ∂f/∂xₙ), the direction of steepest ascent. AI: gradient descent θ ← θ − η∇L(θ).
- Directional derivative — ∇f·u for a unit vector u.
- Multivariable chain rule — derivatives through nested functions of many variables. AI: backprop through any architecture.
- Jacobian matrix — J = ∂f/∂x for vector-valued f. AI: layer-by-layer backprop; log|det J| in normalizing flows.
- Hessian matrix — H = matrix of second partials ∂²f/∂xᵢ∂xⱼ. AI: curvature, Newton’s method, sharp vs flat minima.
- Second-order Taylor expansion — f(x + Δ) ≈ f(x) + ∇fᵀΔ + ½ ΔᵀHΔ. AI: Newton’s method, XGBoost’s split objective.
- Multiple integrals and change of variables — the Jacobian determinant rescales volume. AI: transforming densities, normalizing flows.
- Gaussian integral — ∫ e^(−x²) dx = √π over the real line. AI: Gaussian normalising constants.
- Matrix-calculus identities — ∂(aᵀx)/∂x = a, ∂(xᵀAx)/∂x = (A + Aᵀ)x, ∂tr(AX)/∂X = Aᵀ, ∂ log det X/∂X = X⁻ᵀ.
- Layout conventions — numerator vs denominator layout; check shapes on every derivation.
- Hand-derived gradients — linear regression, logistic regression, softmax with cross-entropy (∂L/∂z = p − y), a two-layer MLP.
- Automatic differentiation — forward mode (Jacobian-vector products) vs reverse mode (vector-Jacobian products). AI: how PyTorch autograd and JAX work.
L3 · Advanced
- Hessian-vector products — Hv without forming H (Pearlmutter’s trick). AI: second-order optimisers, curvature analysis.
- Vector calculus — divergence, curl, Laplacian. AI: continuous normalizing flows, score matching, graph Laplacians.
- Lagrange multipliers — optimise f subject to g(x) = 0 by solving ∇f = λ∇g. AI: SVM derivation, maximum-entropy distributions.
- Implicit function theorem — differentiate y defined implicitly by F(x, y) = 0. AI: deep equilibrium models, bilevel optimisation, meta-learning.
- Ordinary differential equations — linear systems; Euler and Runge–Kutta solvers. AI: Neural ODEs, ResNets as Euler steps, state space models, flow-matching samplers.
- Fixed points and contraction mappings (Banach) — iterating a contraction converges to a unique fixed point. AI: why value iteration converges.
- Calculus of variations — functionals and the Euler–Lagrange equation. AI: deriving variational inference and maximum-entropy solutions.
- Partial differential equations (basics) — heat/diffusion equation, Fokker–Planck equation. AI: diffusion models, physics-informed neural networks.
L4 · Expert
- Real analysis — sequences, uniform convergence, compactness, Lipschitz continuity, L-smoothness. AI: convergence proofs, the universal approximation theorem.
- Measure theory and Lebesgue integration — one integral for discrete and continuous distributions alike. AI: rigorous probability (Probability L4).
- Functional analysis — normed, Banach and Hilbert spaces; linear operators. AI: kernels and RKHS, neural operators, neural tangent kernel theory.
- Stochastic calculus — Brownian motion, Itô integral, Itô’s lemma, stochastic differential equations. AI: score-based diffusion models, Langevin dynamics.
- Differential geometry — manifolds, tangent spaces, Riemannian metrics, geodesics. AI: the manifold hypothesis, natural gradient, hyperbolic embeddings.
- Complex analysis and transforms — analytic functions, Laplace and z-transforms. AI: theory behind state space models and filters.
Probability
Probability lets models represent uncertainty: classifiers output probabilities, and generative models such as LLMs learn whole distributions. Training usually means making the observed data as probable as possible.
Bayes’ theorem, the rule for updating beliefs with data:
L1 · Core
- Sample spaces, events and Kolmogorov’s axioms.
- Conditional probability — P(A | B) = P(A ∩ B) / P(B).
- Independence and conditional independence. AI: Naive Bayes, graphical models.
- Law of total probability — P(A) = Σ P(A | Bᵢ) P(Bᵢ).
- Bayes’ theorem — prior × likelihood, normalised, gives the posterior. AI: Bayesian inference, Naive Bayes, spam filters.
- Random variables — discrete vs continuous; PMF, PDF, CDF.
- Expectation and variance — linearity of expectation; Var(X) = E[X²] − (E[X])².
- Covariance and correlation — Cov(X, Y) = E[XY] − E[X]E[Y]; ρ = Cov(X, Y) / (σₓσᵧ).
- Discrete distributions — Bernoulli, binomial, categorical, multinomial, geometric, Poisson. AI: the categorical distribution is next-token prediction.
- Continuous distributions — uniform, normal (Gaussian), exponential.
L2 · Intermediate
- Joint, marginal and conditional distributions — marginalise by summing or integrating out: p(x) = ∫ p(x, y) dy.
- Multivariate Gaussian — N(μ, Σ) with closed-form marginals and conditionals. AI: Gaussian processes, VAEs, Kalman filters, diffusion noise.
- Transformations of random variables — pᵧ(y) = pₓ(x) |dx/dy| for invertible maps. AI: normalizing flows.
- Moment-generating and characteristic functions.
- More distributions — beta, gamma, Dirichlet, Student-t, Laplace, chi-squared, log-normal, Gumbel. AI: Dirichlet priors in topic models; Gumbel-softmax.
- Exponential family — p(x | η) = h(x) exp(ηᵀT(x) − A(η)). AI: GLMs, conjugate priors, softmax.
- Law of large numbers — sample averages converge to the expectation. AI: why training loss estimates true loss; Monte Carlo.
- Central limit theorem — sums of many independent variables become approximately Gaussian.
- Conditional expectation — E[X] = E[E[X | Y]]; the law of total variance.
- Monte Carlo estimation — approximate E[f(X)] by averaging f over samples.
- Sampling methods — inverse-transform, rejection and importance sampling. AI: off-policy RL, sampling from models.
- Reparameterisation trick — z = μ + σ ⊙ ε with ε ~ N(0, I). AI: VAEs; gradients through random sampling.
- Log-derivative (score-function) trick — ∇θ E[f(x)] = E[f(x) ∇θ log pθ(x)]. AI: REINFORCE and policy gradients.
L3 · Advanced
- Probabilistic graphical models — Bayesian networks, Markov random fields, factor graphs, d-separation.
- Exact inference — variable elimination, belief propagation (sum-product). AI: HMMs, conditional random fields.
- Hidden Markov models — forward–backward, Viterbi, Baum–Welch. AI: classic speech recognition, sequence labelling.
- Markov chains — transition matrices, stationary distribution, ergodicity, mixing time. AI: MCMC, PageRank.
- MCMC — Metropolis–Hastings, Gibbs sampling, Hamiltonian Monte Carlo, Langevin dynamics. AI: Bayesian inference, energy-based models.
- Latent-variable models and EM — E-step computes posteriors over hidden variables; M-step maximises expected log-likelihood. AI: Gaussian mixtures, HMM training.
- Variational inference — maximise the ELBO, E_q[log p(x, z) − log q(z)], a lower bound on log p(x). AI: VAEs, Bayesian deep learning.
- Gaussian processes — a distribution over functions defined by a kernel. AI: Bayesian optimisation for hyperparameter tuning.
- Concentration inequalities — Markov, Chebyshev, Hoeffding, Chernoff, McDiarmid. AI: generalisation bounds, bandit algorithms.
- Stochastic processes (introduction) — random walks, Poisson process, Brownian motion.
- Score function — ∇ₓ log p(x), the gradient of the log-density. AI: score matching, diffusion models.
L4 · Expert
- Measure-theoretic probability — σ-algebras, measurable functions, Radon–Nikodym derivatives, modes of convergence. AI: densities, importance weights and KL defined rigorously.
- Martingales — fair-game sequences and their concentration (Azuma’s inequality). AI: bandit and RL theory.
- High-dimensional probability — sub-Gaussian variables, concentration of measure, covering numbers. AI: why high-dimensional geometry defies intuition.
- SDEs and the Fokker–Planck equation — Ornstein–Uhlenbeck process, reverse-time SDEs. AI: diffusion models.
- Optimal transport — Wasserstein distances, Kantorovich duality, Sinkhorn algorithm. AI: WGANs, flow matching, domain adaptation.
- Bayesian nonparametrics — Dirichlet processes, Gaussian-process theory. AI: models whose capacity grows with the data.
- Exchangeability and de Finetti’s theorem. AI: Bayesian interpretations of in-context learning.
Statistics
Statistics turns data into estimates and decisions: most loss functions are maximum-likelihood estimators, and every model evaluation is a statistical claim.
L1 · Core
- Descriptive statistics — mean, median, mode, variance, standard deviation, quantiles, IQR, skewness, kurtosis.
- Visual summaries — histograms, box plots, scatter plots, Q–Q plots.
- Population vs sample; sampling methods — simple random and stratified sampling. AI: stratified train/test splits.
- Correlation vs causation — Pearson (linear) and Spearman (rank) correlation.
- Feature scaling — z-score standardisation (x − μ)/σ, min–max normalisation. AI: faster, more stable training.
- Outliers and robust statistics — median, median absolute deviation, trimmed means.
L2 · Intermediate
- Estimators — bias, variance, consistency; MSE = bias² + variance.
- Maximum likelihood estimation (MLE) — θ̂ = arg max Σ log p(xᵢ | θ). AI: MSE is Gaussian MLE; cross-entropy is categorical MLE.
- Maximum a posteriori (MAP) — MLE plus a log-prior term. AI: L2 regularisation = Gaussian prior; L1 = Laplace prior.
- Bayesian inference — prior, likelihood, posterior, conjugate priors (beta–Bernoulli, Dirichlet–multinomial), posterior predictive.
- Sampling distributions and standard error.
- Confidence intervals.
- Hypothesis testing — p-values, Type I and II errors, power; t-test, chi-squared test, ANOVA. AI: A/B tests, comparing models fairly.
- Multiple-testing correction — Bonferroni, Benjamini–Hochberg (false discovery rate).
- Resampling — bootstrap, k-fold cross-validation, permutation tests. AI: model evaluation and selection.
- Linear regression, statistical view — OLS assumptions, residual analysis, R², multicollinearity.
- Generalised linear models — link functions; logistic and Poisson regression.
- Bias–variance trade-off — underfitting vs overfitting.
- Regularised regression — ridge, lasso, elastic net.
- Evaluation metrics — confusion matrix, precision, recall, F1, ROC-AUC, PR-AUC, log loss, calibration (expected calibration error).
L3 · Advanced
- Fisher information and the Cramér–Rao bound — Var(θ̂) ≥ 1/I(θ) for unbiased estimators. AI: natural gradient, continual learning (EWC).
- Sufficient statistics.
- Nonparametric methods — kernel density estimation, rank-based tests.
- Time series — stationarity, ACF/PACF, AR/MA/ARIMA, exponential smoothing, state space models and the Kalman filter. AI: forecasting, capacity planning.
- Causal inference — potential outcomes, structural causal models and DAGs, do-calculus, propensity scores, instrumental variables, difference-in-differences.
- Design of experiments — randomisation, blocking, power analysis.
- Survival analysis — Kaplan–Meier curves, Cox proportional hazards. AI: time-to-failure prediction.
- Sequential testing — Wald’s sequential probability ratio test (SPRT), control charts. AI: streaming anomaly detection.
- Hierarchical and empirical Bayes models.
- Conformal prediction — distribution-free prediction intervals with guaranteed coverage. AI: calibrated uncertainty for any model.
L4 · Expert
- Asymptotic statistics — delta method, asymptotic normality of the MLE.
- Statistical decision theory — risk, minimax and admissible estimators.
- High-dimensional statistics — sparsity, compressed sensing, the p ≫ n regime.
- Semiparametric theory and doubly robust estimation. AI: double/debiased machine learning for causal effects.
Optimization
Optimization is how parameters are found: every training run minimises a loss with a variant of gradient descent. The theory is what lets you debug a run that diverges or stalls.
The update every optimiser builds on (η = learning rate):
L1 · Core
- Objective (loss) functions — minimisation vs maximisation; arg min.
- Common losses — MSE, MAE, Huber, binary and categorical cross-entropy, hinge.
- Local vs global minima, saddle points.
- Gradient descent — the update above; effect of a learning rate that is too small or too large.
L2 · Intermediate
- Convex sets and convex functions — for a convex function, every local minimum is global.
- Jensen’s inequality — f(E[X]) ≤ E[f(X)] for convex f. AI: ELBO and EM derivations.
- Closed-form least squares (normal equations) — θ = (XᵀX)⁻¹Xᵀy when XᵀX is invertible.
- Batch, stochastic and mini-batch gradient descent.
- Momentum and Nesterov acceleration.
- Adaptive optimisers — AdaGrad, RMSProp, Adam, AdamW (decoupled weight decay).
- Learning-rate schedules — step decay, warmup, cosine annealing.
- Newton’s method and quasi-Newton methods — BFGS, L-BFGS.
- Lagrange multipliers — equality-constrained optimisation.
- Regularisation as optimisation — L1/L2 penalties, weight decay, early stopping.
- Gradient pathologies — vanishing and exploding gradients, gradient clipping.
- Initialisation math — Xavier/Glorot Var(W) = 2/(n_in + n_out); He Var(W) = 2/n_in. AI: keeps activation variance stable across layers.
L3 · Advanced
- Lagrangian duality and KKT conditions — stationarity, primal and dual feasibility, complementary slackness; Slater’s condition. AI: the SVM dual and the kernel trick.
- Linear and quadratic programming. AI: SVM training is a quadratic program.
- Convergence theory — L-smoothness, strong convexity; rates O(1/t), O(1/√t) and linear.
- Subgradients and proximal methods — ISTA/FISTA, soft-thresholding. AI: lasso, non-smooth losses.
- Coordinate descent. AI: lasso solvers; SMO for SVMs.
- Curvature-aware methods — Gauss–Newton, natural gradient, K-FAC, Shampoo.
- Non-convex landscapes — saddle points, sharp vs flat minima, mode connectivity.
- Stochastic optimisation theory — gradient noise, batch size vs learning-rate scaling, variance reduction (SVRG).
- Discrete and combinatorial optimisation — dynamic programming, beam search, integer programming. AI: decoding, scheduling.
- Derivative-free optimisation — Bayesian optimisation, evolution strategies, random search. AI: hyperparameter tuning.
- Min–max (saddle-point) optimisation. AI: GANs, adversarial training, robust optimisation.
- Bilevel and multi-objective optimisation — Pareto fronts. AI: hyperparameter optimisation, meta-learning (MAML).
L4 · Expert
- Convex analysis — Fenchel conjugates, Bregman divergences, mirror descent.
- Online convex optimisation and regret bounds. AI: bandits, online learning.
- Monotone operators and variational inequalities. AI: convergence of games and GAN training.
- Riemannian optimisation — optimising over manifolds such as spheres or orthogonal matrices.
- Deep-learning optimisation theory — implicit bias of gradient descent, edge of stability, lazy (NTK) vs feature-learning regimes.
- Distributed optimisation — data- and model-parallel SGD, local SGD, gradient compression, ADMM.
Information theory
Information theory supplies AI’s core losses: cross-entropy trains classifiers and LLMs, and KL divergence keeps fine-tuned models close to a reference model. It starts at L2 because it needs L1 probability.
Why minimising cross-entropy fits the data distribution p (H(p) is fixed, so only the KL term moves):
L2 · Intermediate
- Surprisal — −log p(x): rare events carry more information.
- Entropy — H(X) = −Σ p(x) log p(x). AI: uncertainty measures, decision-tree splits.
- Bits vs nats — log base 2 vs base e.
- Cross-entropy — H(p, q) = −Σ p(x) log q(x). AI: the standard classification and LLM training loss.
- KL divergence — D_KL(p ‖ q) = Σ p log(p/q) ≥ 0, not symmetric. AI: VAEs, knowledge distillation, RLHF and DPO penalties.
- Joint and conditional entropy, mutual information — I(X; Y) = H(X) − H(X | Y). AI: feature selection, contrastive learning.
- Perplexity — exp(average cross-entropy in nats). AI: language-model evaluation.
- Information gain and Gini impurity. AI: decision trees, random forests, XGBoost.
L3 · Advanced
- Jensen–Shannon divergence. AI: the original GAN objective.
- f-divergences and Rényi divergences — families that include KL and JS.
- Maximum-entropy principle — the least-committal distribution under constraints is an exponential-family one. AI: softmax, maximum-entropy RL.
- Data-processing inequality — processing cannot add information about the source.
- Information bottleneck. AI: representation-learning theory.
- Source coding — Shannon’s theorem, Huffman and arithmetic coding. AI: prediction is compression; tokenizer design (BPE began as a compression method).
- Minimum description length (MDL) — the best model gives the shortest total code length. AI: model selection, attribute importance.
- Rate–distortion theory. AI: β-VAE, quantisation, learned compression.
- Variational mutual-information bounds — InfoNCE, MINE. AI: contrastive learning (CLIP, SimCLR).
L4 · Expert
- Channel capacity and the noisy-channel coding theorem.
- Information geometry — statistical manifolds, Fisher–Rao metric. AI: natural gradient.
- Kolmogorov complexity and Solomonoff induction. AI: compression-based theories of generalisation.
- PAC-Bayes bounds. AI: generalisation guarantees for neural networks.
Discrete math, logic and graph theory
Discrete math covers what is not continuous: logic and search in classical AI, the cost of algorithms, and the graphs behind GNNs, knowledge graphs and vector indexes.
L1 · Core
- Set theory — relations, functions, equivalence relations, partial orders.
- Propositional and first-order logic — connectives, quantifiers, inference rules. AI: rule-based systems, knowledge representation.
- Boolean algebra.
- Combinatorics — permutations, combinations, binomial coefficients, pigeonhole principle, inclusion–exclusion.
- Proof techniques — induction, contradiction, construction.
- Big-O notation — time and memory complexity. AI: self-attention costs O(n²) in sequence length.
L2 · Intermediate
- Graph basics — directed/undirected, weighted, degree, paths, cycles, trees, DAGs. AI: computation graphs, Bayesian networks.
- Graph representations — adjacency matrix, adjacency list.
- Graph algorithms — BFS, DFS, Dijkstra, A*, topological sort, minimum spanning tree. AI: classical search; backprop runs in reverse topological order.
- Recurrence relations and dynamic programming. AI: Viterbi, edit distance, RL.
- Search and games — minimax, alpha–beta pruning, constraint satisfaction, SAT.
L3 · Advanced
- Spectral graph theory — Laplacian L = D − A, normalised Laplacian, Fiedler vector. AI: spectral clustering, graph convolutional networks.
- Random walks on graphs. AI: PageRank, node2vec, DeepWalk.
- Message passing on graphs. AI: graph neural networks.
- Proximity and small-world graphs — greedy routing on navigable graphs. AI: HNSW vector indexes.
- Automata and formal languages — regular and context-free grammars. AI: tokenizers, constrained decoding, structured output.
- Computability and complexity classes — P, NP, NP-hard. AI: recognising intractable problems.
L4 · Expert
- Weisfeiler–Lehman test and graph isomorphism. AI: the expressive power of GNNs.
- Hypergraphs, simplicial complexes, sheaves. AI: topological deep learning.
- Circuit complexity. AI: what transformers can and cannot compute.
- Category theory (niche). AI: compositional and categorical deep learning.
Numerical methods and floating point
Numerical methods decide whether correct math survives on real hardware: overflow, rounding and ill-conditioning break training long before the theory does.
L2 · Intermediate
- Floating-point formats (IEEE 754) — FP32, FP16, BF16, FP8; sign, exponent, mantissa, machine epsilon. AI: mixed-precision training.
- Overflow, underflow and catastrophic cancellation.
- Log-sum-exp trick — log Σ e^(xᵢ) = m + log Σ e^(xᵢ − m), with m = max xᵢ. AI: stable softmax and cross-entropy.
- Working in log space — add log-probabilities instead of multiplying probabilities.
- Epsilon terms — why Adam and LayerNorm add a small ε to denominators.
- Finite differences and gradient checking — compare autograd with [f(x + h) − f(x − h)] / 2h.
- Root finding — bisection, Newton–Raphson.
- Vectorisation — replace Python loops with array operations.
L3 · Advanced
- Numerical linear algebra — conditioning vs stability, why QR beats the normal equations, Householder reflections, iterative solvers, sparse matrices.
- Numerical integration — quadrature, Monte Carlo and quasi-Monte Carlo.
- ODE solvers — Euler, Runge–Kutta, adaptive step size, stiffness. AI: Neural ODEs, diffusion samplers (DDIM, DPM-Solver).
- Quantisation math — scale and zero-point, symmetric vs asymmetric, per-channel scales, rounding error. AI: INT8/INT4 inference.
- Approximate nearest-neighbour search — LSH, IVF (k-means partitions), HNSW graphs, product quantisation; recall vs latency. AI: vector databases and RAG.
- Streaming algorithms — running mean and variance (Welford), online softmax. AI: FlashAttention-style tiling.
L4 · Expert
- Backward error analysis — proving an algorithm is numerically stable.
- Fast transforms — FFT-based long convolutions. AI: S4, Hyena.
- IO-aware algorithm design — tiling for the GPU memory hierarchy. AI: FlashAttention.
- Numerical PDE methods — finite differences, finite elements. AI: scientific ML, neural operators.
Signal processing and Fourier analysis
Signal processing explains CNNs, audio models and position encodings: a convolution layer is a learned filter, and speech models read spectrograms.
L2 · Intermediate
- Discrete convolution and cross-correlation — padding, stride, dilation. AI: a CNN “convolution” is actually cross-correlation (no kernel flip).
- Complex exponentials — Euler’s formula e^(iθ) = cos θ + i sin θ. AI: rotary position embeddings (RoPE) rotate query/key pairs by position-dependent angles.
- Fourier series and the Fourier transform — any signal as a sum of sinusoids.
- Discrete Fourier transform and the FFT — frequency analysis in O(n log n).
- Convolution theorem — convolution in time equals multiplication in frequency. AI: fast long convolutions.
- Sampling theorem (Nyquist–Shannon) and aliasing — sample faster than twice the highest frequency.
L3 · Advanced
- Filters and frequency response — low-pass, high-pass, band-pass.
- Spectrograms, mel scale, MFCCs. AI: speech models such as Whisper take log-mel spectrograms as input.
- Sinusoidal positional encodings — sin/cos pairs at geometrically spaced frequencies. AI: the original Transformer.
- Linear time-invariant systems; Laplace and z-transforms. AI: state space models.
- Wavelets — multi-scale time–frequency analysis.
L4 · Expert
- Harmonic analysis on groups — Fourier analysis beyond the real line (spheres, rotation groups). AI: spherical CNNs, equivariant networks.
- Spectral bias — networks fit low frequencies first. AI: Fourier-feature encodings in NeRF and other implicit neural representations.
Statistical learning theory
Learning theory explains why a model that fits its training data works on new data, and when it will not. It starts at L3 because it combines probability, statistics and optimization.
L3 · Advanced
- The learning problem — hypothesis class, loss, true risk vs empirical risk; empirical risk minimisation (ERM).
- Generalisation gap — the i.i.d. assumption and what distribution shift breaks.
- Bias–variance decomposition (formal).
- PAC learning — “probably approximately correct” guarantees and sample complexity.
- VC dimension — shattering, growth function; linear classifiers in ℝᵈ have VC dimension d + 1.
- Rademacher complexity.
- No-free-lunch theorem — no learner wins on every possible problem.
- Structural risk minimisation and regularisation theory.
- Kernel methods — kernel trick, Mercer’s theorem, reproducing kernel Hilbert spaces (RKHS), representer theorem. AI: SVMs, Gaussian processes.
- Margin theory. AI: SVMs and boosting.
- Boosting theory — AdaBoost as exponential-loss minimisation; gradient boosting as functional gradient descent. AI: XGBoost.
- Universal approximation theorem — one wide-enough hidden layer with a non-polynomial activation approximates any continuous function on a compact set.
L4 · Expert
- Algorithmic stability bounds.
- PAC-Bayes and compression bounds.
- Double descent and benign overfitting.
- Implicit regularisation of gradient descent.
- Neural tangent kernel, infinite-width limits and mean-field theory.
- Approximation theory — depth-separation results, Barron spaces.
- Online learning and bandits — regret, UCB, Thompson sampling, lower bounds.
- Scaling laws — power-law fits of loss against parameters, data and compute; compute-optimal training (Chinchilla). These are empirical fits, not theorems.
- Theory of in-context learning — an open research area.
Reinforcement learning and decision-making math
RL math formalises sequential decisions, and it now also underpins LLM alignment (RLHF, DPO) and reasoning-model training.
L2 · Intermediate
- Markov decision processes — states, actions, transitions P(s′ | s, a), rewards, discount factor γ.
- Return — Gₜ = Σ γᵏ rₜ₊ₖ₊₁ (k = 0 to ∞).
- Value functions — Vπ(s) and Qπ(s, a).
- Bellman equations — expectation and optimality forms.
- Dynamic programming — policy evaluation, policy iteration, value iteration.
- Exploration — ε-greedy, multi-armed bandits, UCB, Thompson sampling.
L3 · Advanced
- Monte Carlo and temporal-difference learning — TD(0), TD(λ), SARSA, Q-learning.
- Function approximation — deep Q-networks, target networks, the “deadly triad” (function approximation + bootstrapping + off-policy data).
- Policy gradient theorem — ∇J(θ) = E[∇ log πθ(a | s) · Qπ(s, a)]; REINFORCE.
- Variance reduction — baselines, advantage A = Q − V, generalised advantage estimation (GAE).
- Actor–critic methods.
- Trust-region methods — TRPO (KL constraint), PPO (clipped probability ratio).
- RLHF math — Bradley–Terry preferences P(y_w ≻ y_l) = σ(r(y_w) − r(y_l)), reward modelling, KL-regularised policy objective.
- Direct preference optimisation (DPO) — the closed-form optimum of the KL-regularised objective turns preference learning into a logistic loss.
- Group relative policy optimisation (GRPO) — advantages measured against a group of sampled answers to the same prompt. AI: training reasoning models with verifiable rewards.
- POMDPs and belief states.
- Optimal control — LQR, Hamilton–Jacobi–Bellman equation, model predictive control.
L4 · Expert
- Game theory — Nash equilibrium, zero-sum games, von Neumann’s minimax theorem. AI: GANs, self-play, multi-agent RL.
- Regret minimisation in games — counterfactual regret minimisation (CFR). AI: poker-playing AIs.
- Stochastic approximation — Robbins–Monro conditions Σηₜ = ∞ and Σηₜ² < ∞. AI: convergence of SGD and TD learning.
- Mechanism design and social choice. AI: multi-agent systems, aggregating human preferences.
Expert and research-level math
Choose these by specialisation after L3, not all at once; each one underpins a specific frontier area. Typical pairings: generative models need stochastic calculus and optimal transport; geometric deep learning needs group theory and differential geometry; ML theory needs functional analysis and high-dimensional probability.
| Field | Core ideas | Where it is used |
|---|---|---|
| Measure theory | σ-algebras, Lebesgue integral, Radon–Nikodym derivative | Rigorous probability, theory of generative models |
| Functional analysis | Hilbert and Banach spaces, operators, spectral theory | Kernels and RKHS, neural operators, NTK |
| Differential geometry | Manifolds, Riemannian metrics, geodesics, curvature | Manifold learning, hyperbolic embeddings, Riemannian optimisation |
| Information geometry | Fisher–Rao metric, natural gradient, dual connections | Natural-gradient methods, K-FAC, mirror descent |
| Optimal transport | Monge and Kantorovich problems, Wasserstein distances, Sinkhorn | WGANs, flow matching, domain adaptation |
| Stochastic calculus and SDEs | Brownian motion, Itô’s lemma, Fokker–Planck, reverse-time SDEs | Diffusion and score-based models, Langevin sampling |
| Group and representation theory | Symmetry groups, invariance, equivariance, irreducible representations | Geometric deep learning, equivariant GNNs for molecules and proteins |
| Algebraic topology and TDA | Homology, persistent homology, simplicial complexes | Topological data analysis, the theory behind UMAP |
| Random matrix theory | Spectral laws of large random matrices | Weight-spectrum diagnostics, initialisation theory |
| High-dimensional probability | Concentration of measure, sub-Gaussian tails, covering numbers | Generalisation theory, embeddings, compressed sensing |
| Causality | Structural causal models, do-calculus, identifiability, counterfactuals | Causal ML, robust and fair models |
| Dynamical systems | Stability, attractors, Lyapunov exponents, chaos | RNN behaviour, training dynamics, neural ODEs |
| Interpretability math | Linear representation hypothesis, superposition, sparse dictionary learning | Sparse autoencoders, circuit analysis of LLMs |
| Advanced game theory | Equilibrium computation, mechanism design | Multi-agent systems, auctions, self-play |
Math behind major AI models
Use this to decide what to study next: find the model you are learning, then cover the math in its row.
| Model or technique | Math it rests on |
|---|---|
| Linear regression | Least squares, normal equations, orthogonal projection, Gaussian MLE |
| Logistic regression | Sigmoid, Bernoulli MLE, cross-entropy, convexity, gradient (p − y)x |
| Naive Bayes | Bayes’ theorem, conditional independence, log-probabilities |
| k-nearest neighbours | Distance metrics, curse of dimensionality |
| k-means | Euclidean distance, Lloyd’s algorithm (coordinate descent on within-cluster squared error), Voronoi cells |
| Decision trees | Entropy, Gini impurity, information gain |
| Random forests | Bootstrap sampling, bagging (averaging reduces variance) |
| Gradient boosting, XGBoost | Functional gradient descent, second-order Taylor expansion, regularised objective |
| Support vector machines | Hyperplanes, margins, hinge loss, convex QP, Lagrangian duality, KKT, kernels |
| PCA and SVD | Covariance eigendecomposition, SVD, Rayleigh quotient |
| Gaussian mixture models | Multivariate Gaussians, EM, Jensen’s inequality |
| Multilayer perceptrons | Matrix multiplication, activations, chain rule (backprop), SGD/Adam, initialisation variance |
| CNNs | Convolution (cross-correlation), translation equivariance, pooling |
| RNNs and LSTMs | Recurrence, backprop through time, eigenvalues of recurrent weights, sigmoid gating |
| Transformers | Scaled dot-product attention, softmax, layer normalisation, residuals, positional encodings (sinusoids, RoPE), O(n²) cost |
| LLM pre-training | Next-token MLE, cross-entropy, perplexity, scaling laws |
| LLM alignment | Bradley–Terry model, KL regularisation, PPO, DPO, GRPO |
| Embeddings and contrastive learning | Vector spaces, cosine similarity, InfoNCE (a mutual-information bound), PMI matrix factorisation (word2vec) |
| Vector search and RAG | Dot product, cosine, L2 distance, normalisation, ANN indexes (HNSW graphs, IVF k-means partitions, product quantisation) |
| LoRA and other PEFT | Low-rank factorisation ΔW = BA, matrix rank |
| Quantisation | Floating-point formats, affine (scale, zero-point) quantisation, rounding error |
| Mixture of experts | Softmax gating, top-k routing, load-balancing loss |
| VAEs | Latent variables, ELBO, KL divergence, reparameterisation trick |
| GANs | Min–max game, Jensen–Shannon divergence, Wasserstein distance, Lipschitz constraints |
| Normalizing flows | Change of variables, Jacobian determinants, invertible maps |
| Diffusion models | Gaussian Markov chain, variational bound, score matching, SDEs, probability-flow ODE |
| Flow matching | ODEs, vector fields, optimal-transport paths |
| Graph neural networks | Adjacency matrices, graph Laplacian, message passing, permutation invariance |
| State space models (S4, Mamba) | Linear ODEs, zero-order-hold discretisation, matrix exponential, convolution kernels |
| Gaussian processes, Bayesian optimisation | Kernels, Gaussian conditioning, acquisition functions |
| Reinforcement learning | MDPs, Bellman equations, policy gradients |
The transformer’s core operation; dividing by √dₖ keeps the dot products near unit variance so the softmax does not saturate:
Core references
One main text per pillar is enough; use the others for lookups and deeper dives.
| Pillar | Main reference | Also useful |
|---|---|---|
| All foundations | Deisenroth, Faisal, Ong — Mathematics for Machine Learning | Goodfellow, Bengio, Courville — Deep Learning, Part I |
| Linear algebra | Strang — Introduction to Linear Algebra, with MIT 18.06 lectures | 3Blue1Brown — Essence of Linear Algebra; Axler — Linear Algebra Done Right; Trefethen and Bau — Numerical Linear Algebra |
| Calculus | 3Blue1Brown — Essence of Calculus; MIT 18.01 and 18.02 | Petersen and Pedersen — The Matrix Cookbook; Parr and Howard — The Matrix Calculus You Need for Deep Learning |
| Probability | Blitzstein and Hwang — Introduction to Probability (Harvard Stat 110) | Bertsekas and Tsitsiklis — Introduction to Probability |
| Statistics | Wasserman — All of Statistics | Casella and Berger — Statistical Inference; Hastie, Tibshirani, Friedman — The Elements of Statistical Learning |
| Optimization | Boyd and Vandenberghe — Convex Optimization | Nocedal and Wright — Numerical Optimization |
| Information theory | Cover and Thomas — Elements of Information Theory | MacKay — Information Theory, Inference, and Learning Algorithms |
| Probabilistic ML | Bishop — Pattern Recognition and Machine Learning | Murphy — Probabilistic Machine Learning (two volumes) |
| Learning theory | Shalev-Shwartz and Ben-David — Understanding Machine Learning | Mohri, Rostamizadeh, Talwalkar — Foundations of Machine Learning |
| Reinforcement learning | Sutton and Barto — Reinforcement Learning: An Introduction | Bertsekas — Dynamic Programming and Optimal Control |
| Graphs and geometric DL | Hamilton — Graph Representation Learning | Bronstein, Bruna, Cohen, Veličković — Geometric Deep Learning |
| High-dimensional probability | Vershynin — High-Dimensional Probability | Wainwright — High-Dimensional Statistics |
| Optimal transport | Peyré and Cuturi — Computational Optimal Transport | Villani — Optimal Transport: Old and New |
| Modern deep learning | Bishop and Bishop — Deep Learning: Foundations and Concepts | Prince — Understanding Deep Learning |