Math you need
- Three mathematical pillars underpin virtually all of ML: linear algebra, calculus, and probability
- You do not need a PhD-level treatment - you need fluency with specific operations that recur constantly
- Understanding the math lets you read papers, debug models, and design architectures instead of just calling APIs
ML math boils down to: vectors and matrices for representing data and parameters, derivatives and gradients for optimization, and probability distributions for modeling uncertainty and designing losses.
- Linear algebra is used in every layer of a neural network (matrix multiply)
- Calculus powers backpropagation and all gradient-based optimization
- Probability theory underlies Bayes classifiers, VAEs, diffusion models, and model calibration
- Read a modern ML paper without getting stuck on notation.
- Differentiate a scalar loss with respect to a matrix without consulting a table.
- Distinguish maximum likelihood from maximum a posteriori, and write down both objectives.
- Compute the entropy of a distribution and the KL divergence between two.
- Identify which mathematical tool a given paper is using, even when it is not labelled.
TL;DR
You do not need every result in every textbook; you need fluency in five chapters: linear algebra (vectors, matrices, eigendecomposition, SVD), calculus (gradients, chain rule, Jacobians), probability (random variables, Bayes, expectation), statistics (estimators, MLE/MAP), and information theory (entropy, KL divergence). The Mathematics for Machine Learning book [1] is a single 400-page reference for all five.
Intuition
You do not need every theorem in every chapter. You need:
- Linear algebra: vectors, matrices, products, norms, eigendecomposition, SVD.
- Calculus: gradients, chain rule, Jacobians, the matrix-cookbook identities.
- Probability: Bayes rule, expectations, common distributions, the law of total expectation.
- Statistics: maximum likelihood, MAP, bias and variance of estimators.
- Information theory: entropy, cross-entropy, KL divergence, mutual information.
Five short chapters across three books [1][3][4] cover everything you will see in a modern ML paper.
Linear algebra
Everything in ML is a vector or a matrix. Linear algebra is the language; eigendecomposition and SVD are the verbs.
Linear algebra: the operators that show up everywhere
Vectors and norms
A vector has a length (norm). The two you will see constantly:
The norm penalises large coordinates quadratically; the norm penalises them linearly and is the source of the sparsity-inducing behaviour of Lasso regression.
Matrix multiplication
For and , the product has entries
A neural-network forward pass is a sequence of matrix multiplies interleaved with element-wise nonlinearities.
Eigendecomposition
A square matrix that has linearly independent eigenvectors can be written
where is diagonal with the eigenvalues and ‘s columns are the eigenvectors. PCA finds the eigendecomposition of the empirical covariance matrix.
Singular Value Decomposition (SVD)
Every real matrix has a decomposition
where and are orthogonal and is diagonal with non-negative entries (the singular values). SVD generalises eigendecomposition to non-square and singular matrices and is the workhorse behind low-rank approximation, recommender systems, and LoRA fine-tuning of LLMs.
Pseudo-inverse and least squares
The least-squares problem has solution
when has full column rank, and more generally where is the Moore-Penrose pseudo-inverse. This is the closed-form for ordinary linear regression.
Positive (semi-)definiteness
A symmetric matrix is positive definite if for all (positive semi-definite for ). Covariance matrices and Hessians of convex functions are PSD; PSD matrices have non-negative eigenvalues and a unique square root.
For a deeper treatment, Strang [5] is the canonical applied reference.
Calculus
Optimisation runs on gradients. The chain rule, applied through a computation graph, is what backpropagation actually computes.
Calculus: gradients, Jacobians, Hessians, and Taylor expansion
Gradient of a scalar function
For , the gradient is the vector of partial derivatives:
It points in the direction of steepest ascent; is the descent direction used by SGD.
Chain rule
For and ,
Backpropagation is the chain rule applied through a computation DAG, with intermediate gradients reused.
Jacobian
For a vector-valued function , the Jacobian is the matrix
The Jacobian-vector product (JVP) and vector-Jacobian product (VJP) are the building blocks of forward-mode and reverse-mode autodiff respectively.
Hessian
The Hessian of is the matrix of second partials:
Newton’s method uses ; second-order optimisers in deep learning approximate it because the full Hessian is memory.
Taylor expansion
Around , a smooth function admits the second-order Taylor expansion
Gradient descent minimises the linear part; Newton’s method minimises the full quadratic.
Matrix calculus identities
Three identities you will use without thinking:
For more, consult the Matrix Cookbook (Petersen and Pedersen 2012).
Convexity
A function is convex if for all and ,
For convex , every local minimum is global. Linear regression, logistic regression, and SVMs have convex losses; deep nets do not. Boyd and Vandenberghe [2] is the canonical reference.
Probability
ML is statistics in disguise. The Bayes rule, expectations, and a handful of distributions are the moves you reach for.
Probability: random variables, Bayes, distributions
| Distribution | Support | Parameters | Use in ML |
|---|---|---|---|
| Bernoulli | {0, 1} | p in [0, 1] | Binary classification labels; output of sigmoid. |
| Categorical | {1, ..., K} | p_1, ..., p_K with sum 1 | Multiclass classification; output of softmax. |
| Binomial | {0, ..., n} | n, p | Counts of successes in n trials. |
| Gaussian (normal) | R | mu, sigma^2 | Noise model in regression; prior on weights. |
| Multivariate Gaussian | R^d | mu, Sigma | Latent variables in VAEs; Gaussian processes. |
| Beta | [0, 1] | alpha, beta | Conjugate prior for Bernoulli; smoothing rates. |
| Dirichlet | (K-1)-simplex | alpha in R^K_+ | Conjugate prior for Categorical; topic models. |
| Exponential | [0, infinity) | lambda > 0 | Inter-arrival times; survival analysis. |
Statistics
Estimators have bias, variance, and consistency. MLE and MAP are the two most common ways to fit them.
Statistics: estimators, MLE, MAP, hypothesis testing
Estimator properties
An estimator of has:
- Bias: .
- Variance: .
- Consistency: as .
Mean squared error decomposes as . This decomposition is the backbone of the bias-variance tradeoff (see Bias, variance, over/under-fitting).
Maximum Likelihood Estimation (MLE)
Given iid data with density ,
For the Gaussian likelihood, MLE recovers the empirical mean and (uncorrected) variance. For a softmax classifier, MLE is exactly cross-entropy minimisation.
Maximum A Posteriori (MAP)
If we have a prior ,
A Gaussian prior on corresponds exactly to L2 regularisation; a Laplace prior corresponds to L1 regularisation. This is why ridge and Lasso are sometimes called “MAP with Gaussian / Laplace prior”.
Confidence intervals and hypothesis tests
A 95% confidence interval is constructed so that, under repeated sampling, the interval covers the true parameter 95% of the time. It is not the probability that the parameter lies in this particular interval (that is the Bayesian credible interval).
Hypothesis testing fixes a null , computes a test statistic, and rejects if the p-value falls below a chosen significance level. In ML, hypothesis tests show up in A/B testing and in evaluating whether one model is significantly better than another (paired t-tests on cross-validation folds, McNemar’s test for classifiers).
Information theory
Cross-entropy is just the log-loss. KL divergence measures how surprised one distribution is by another. Mutual information measures shared structure.
Information theory: entropy, cross-entropy, KL, mutual information
Entropy
The entropy of a discrete distribution is
It is the minimum average number of bits (or nats, with natural log) required to encode samples from .
Cross-entropy
For two distributions (the truth) and (the model),
This is the average number of bits a code optimised for uses to encode samples from . In supervised classification, is a one-hot label and is the model’s softmax, so cross-entropy reduces to - exactly the negative log-likelihood, also known as log-loss.
KL divergence
The Kullback-Leibler divergence from to is
It is non-negative, zero iff , and asymmetric in its arguments. Minimising cross-entropy with fixed (as in classification) is equivalent to minimising .
Mutual information
For two random variables and ,
Mutual information is the reduction in uncertainty about from observing . It is symmetric and non-negative. In ML, mutual information underlies feature selection (mRMR), representation learning (InfoNCE, contrastive loss), and information-bottleneck analyses of deep nets.
For the canonical reference, Cover and Thomas [4] is the standard textbook.
Where each tool shows up
| Tool | Where you meet it in ML |
|---|---|
| Matrix multiplication | Every neural-network forward pass; attention; embedding lookups. |
| Eigendecomposition / SVD | PCA; spectral methods; low-rank adaptation (LoRA). |
| Gradient + chain rule | Backpropagation; SGD, Adam, RMSprop. |
| Jacobian / Hessian | Second-order optimisers (L-BFGS, K-FAC, Newton); influence functions. |
| Bayes rule | Naive Bayes; Bayesian deep learning; diffusion models. |
| Gaussian distribution | Linear regression noise model; VAE prior; Gaussian processes. |
| Categorical / softmax | Multiclass classification output; LLM next-token distribution. |
| MLE | Default training objective for almost every supervised model. |
| MAP / regularisation | Ridge (L2), Lasso (L1), early stopping, weight decay. |
| Cross-entropy | Standard classification loss; training objective for LLMs. |
| KL divergence | VAE ELBO; PPO trust-region penalty in RLHF; knowledge distillation. |
| Mutual information | Feature selection; contrastive learning (InfoNCE); information-bottleneck. |
Pop quiz
- 1. What is the gradient of f(x) = x^T A x with respect to x, when A is square but not necessarily symmetric?
- 2. Which of these statements about KL divergence is FALSE?
- 3. L2 regularisation on linear regression weights corresponds to which Bayesian setup?
- 4. Which decomposition exists for ANY real matrix A in R^{m x n}, square or not, full rank or not?
- 5. For a discrete distribution with support {a, b}, what is the entropy H(p) maximised at?
Interview Q&A
Derive the closed-form solution for ordinary least squares from scratch.phone
We want to minimise .
Expand:
Take the gradient w.r.t. using for symmetric :
Set to zero: , i.e. the normal equations. If is invertible (X has full column rank),
If is singular, use the pseudo-inverse , computed via SVD.
Show that softmax + cross-entropy gives the same gradient as a logistic regression update on a single example.onsite
Softmax with logits : . Cross-entropy with one-hot label (true class ):
Differentiate w.r.t. :
So the gradient of softmax + cross-entropy with respect to logits is (prediction - one-hot target). For binary classification this reduces to where is the sigmoid output - exactly the logistic regression gradient. The simplicity of this gradient is why softmax + cross-entropy is the default classification head.
What is the connection between MLE and minimising KL divergence?research
For iid data from an unknown true distribution , the empirical distribution puts mass on each . MLE chooses to maximise
Now,
The first term does not depend on , so minimising in is the same as maximising - that is, MLE. As , in the appropriate sense, so MLE asymptotically minimises , the discrepancy between the truth and the model. This is why MLE is “the natural” estimator when you trust your model class to contain the truth, and why it goes wrong when the model class is misspecified.
A function f is convex. What does that buy you computationally?onsite
Three concrete things, paraphrased from Boyd and Vandenberghe [2].
- Every local minimum is global. SGD or any first-order method that finds a stationary point finds an optimum.
- Strong duality often holds. The dual problem gives a lower bound that matches the primal, which means cross-checking optimality is cheap.
- Optimisation is well-conditioned. Convex losses (linear regression, logistic regression, SVM) admit polynomial-time solvers and lots of theory; non-convex losses (deep nets) do not, which is why “did the model train” is a real question for neural networks but never for logistic regression.
The flip side: convexity is restrictive. Almost no expressive function class is convex in its parameters. Deep learning trades convexity for expressiveness and absorbs the optimisation difficulty.
References
- Deisenroth, M. P., Faisal, A. A., and Ong, C. S. (2020). Mathematics for Machine Learning. Cambridge University Press. https://mml-book.github.io/
- Boyd, S. and Vandenberghe, L. (2004). Convex Optimization. Cambridge University Press. https://web.stanford.edu/~boyd/cvxbook/
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. ISBN 978-0-387-31073-2
- Cover, T. M. and Thomas, J. A. (2006). Elements of Information Theory (2nd ed.). Wiley. ISBN 978-0-471-24195-9
- Strang, G. (2019). Linear Algebra and Learning from Data. Wellesley-Cambridge Press. ISBN 978-0-692-19638-0