Machine Learning Math Cheat Sheet by Module
153 machine learning math formulas across seven modules, from statistics to information theory, each with a one-line meaning and a link to the lesson that teaches it.
What are the essential ML math formulas?
The essential ML math formulas are sample variance, expectation, Bayes' theorem, the normal density, the dot product, matrix multiplication, eigenvalues, the chain rule, the gradient descent and Adam updates, softmax, cross-entropy, KL divergence and attention. The table below gives each one with its meaning and the lesson that derives it.
| Formula | What it means |
|---|---|
Sample variance with Bessel’s correction | Dividing by n minus 1 makes the sample variance an unbiased estimate of the population variance. |
Expectation and its linearity | Expectation is the probability-weighted average, with an integral in place of the sum for continuous variables, and it is linear even when the variables are dependent. LessonRandom Variables & ExpectationPracticeExpected Value |
Bayes’ theorem | Bayes turns the probability of the evidence given a hypothesis into the probability of the hypothesis given the evidence. LessonBayes' Theorem & InferencePracticeGaussian Naive Bayes |
Normal (Gaussian) density | About 68, 95 and 99.7 percent of the mass lies within 1, 2 and 3 standard deviations of the mean. |
Dot product | The dot product is large when two vectors point the same way and zero when they are orthogonal, where θ here is the angle between them. LessonDot Product & Vector NormsPracticeDot Product |
Matrix product | Each output entry is a row of A dotted with a column of B, at a cost of m times n times p multiply-adds. |
Eigenvalue equation | An eigenvector keeps its direction under A and is only scaled by its eigenvalue λ. LessonEigenvalues & EigenvectorsPracticeEigenvalues of a Matrix |
Chain rule | Derivatives of composed functions multiply along a path and add across paths. LessonChain Rule |
Gradient descent update | Each step moves the parameters a small distance, set by the learning rate, against the gradient. |
Adam bias correction and update | Bias correction undoes the pull toward zero in the first steps, and the usual defaults are β₁ = 0.9, β₂ = 0.999 and ε = 1e-8. |
Softmax in its stable form | Softmax turns logits into probabilities, and subtracting the largest logit changes nothing mathematically but prevents overflow. LessonCross-Entropy LossPracticeNumerically Stable Softmax |
Categorical cross-entropy | With one-hot labels the loss is minus the log of the probability given to the correct class. LessonCross-Entropy LossPracticeCross-Entropy Loss |
KL divergence | KL divergence measures the extra cost of using Q in place of P, and it is zero only when they match and is not symmetric. |
Scaled dot-product attention | Attention is two matrix products around a row-wise softmax, scaled by the square root of the key dimension. LessonMatrix Multiplication & Tensor OperationsPracticeCausal Masking for AttentionLLM InternalsAttention Mechanism |
The full sheet below has 153 formulas in the order of the ML Math modules. Each row gives the formula, one sentence on what it means and a link to the lesson that teaches it, plus a practice problem or an LLM Internals lesson where one exists. Throughout the sheet, n is the sample size, vectors are columns except the probability row vector π in the Markov chain rows, η is the learning rate and log is the natural log unless a base is written.
Most formulas feel hard to read because of a small set of symbols that repeat across every module. The decoder below explains each one and marks every row that uses it.
Pick a symbol to see what it means. Every row on this page that uses it gets a green edge.
The vector of partial derivatives of a function with respect to every parameter. It points uphill, so training steps go the opposite way.
Say it as “grad L with respect to theta”. It appears in 18 formulas across 3 modules of this sheet.
- Gradients of linear and quadratic forms
- Least-squares gradient
- Gradient
- Directional derivative
- Second-order Taylor expansion
- Gradient flow
- Second-derivative test
- Backpropagation error signals
- Gradient descent update
- Second-order convexity test
- Safe step size for a smooth convex loss
- Minibatch SGD
- Momentum
- Nesterov momentum
- L2 regularisation
- Newton’s method
- Lagrange condition for an equality constraint
- KKT conditions
Which statistics formulas does machine learning use?
Machine learning uses statistics formulas to summarise data, measure uncertainty and decide whether a difference is real. The ones below cover summaries, sampling, confidence intervals, hypothesis tests, A/B tests, correlation, resampling and the two ways of fitting parameters, maximum likelihood and Bayesian estimation.
| Formula | What it means |
|---|---|
Sample mean | The mean is the sum of the values divided by how many there are. LessonBasic StatisticsPracticeMean, Median and Mode |
Population variance and standard deviation | Variance is the average squared distance from the mean, and the standard deviation is its square root, in the same units as the data. LessonBasic StatisticsPracticeSample Variance and Standard Deviation |
Interquartile range and outlier fences | The IQR is the spread of the middle half of the data, and points more than 1.5 IQR beyond the quartiles are flagged as outliers. LessonBasic StatisticsPracticePercentiles and Quantiles |
Sample variance with Bessel’s correction | Dividing by n minus 1 makes the sample variance an unbiased estimate of the population variance. |
Standard error of the mean | The spread of the sample mean shrinks with the square root of the sample size. LessonSampling Distributions |
Standard error of a proportion | A sample proportion varies around the true rate p by about this amount. LessonSampling Distributions |
Central limit theorem | The mean of many independent draws with finite variance is approximately normal whatever the original distribution, and the second argument here is a variance. LessonCentral Limit Theorem |
z-score of a sample mean | The z-score counts how many standard errors the sample mean sits from the population mean. LessonCentral Limit Theorem |
Confidence interval for a mean | Use z when the population standard deviation is known and t with n minus 1 degrees of freedom when it is estimated, where z* is 1.645, 1.96 and 2.576 for 90, 95 and 99 percent. |
Confidence interval for a proportion | This is the normal-approximation interval for a rate such as a click-through rate. LessonConfidence Intervals |
One-sample z-test statistic | The test statistic measures how far the data sit from the null value, in standard-error units. |
Chi-square statistic | Chi-square compares observed and expected counts, with k minus 1 degrees of freedom for goodness of fit and (r minus 1)(c minus 1) for a test of independence. LessonHypothesis Testing FundamentalsPracticeChi-Square Test |
Two-sided p-value from z | The p-value is the probability of a result at least this extreme if the null hypothesis is true, where Φ is the standard normal CDF. LessonP-Values & Significance |
Bonferroni correction | Testing m hypotheses at α/m each keeps the chance of any false positive at or below α. LessonP-Values & Significance |
Type I error, Type II error and power | α is the false-positive rate, β is the false-negative rate and power is the chance of detecting a real effect. LessonType I vs Type II Errors |
One-sample t statistic | The t statistic replaces σ with s, so its reference distribution has heavier tails for small samples. LessonOne-Sample T-TestPracticeOne-Sample t-Test |
Two-proportion z-test for an A/B test | The pooled rate gives the standard error under the null hypothesis that both variants convert equally. LessonA/B Testing |
A/B test sample size per group | Halving the lift you want to detect roughly quadruples the users needed in each group. LessonA/B Testing |
One-way ANOVA F statistic | F compares the variation between group means with the variation within groups, for k groups and N observations. LessonANOVA |
Pearson correlation | r measures linear association on a scale from minus 1 to 1 and says nothing about causation. LessonCorrelation vs CausationPracticePearson Correlation Matrix |
Spearman rank correlation with no ties | Spearman is Pearson computed on ranks, so it captures any monotonic relationship, and dᵢ is the difference between the two ranks of item i. LessonCorrelation vs Causation |
Bootstrap percentile interval | Resample the data with replacement many times, recompute the statistic each time and keep the middle 1 minus α of the results. LessonResampling MethodsPracticeBootstrap Mean and Confidence Interval |
k-fold cross-validation estimate | The model is trained k times, scored each time on the one fold it did not see, and the k scores are averaged. LessonResampling MethodsPracticeK-Fold Split |
Maximum likelihood estimate | MLE picks the parameters that make the observed data most probable, and the log turns the product of probabilities into a sum. |
Closed-form MLEs | The Gaussian MLE of the variance divides by n, so it is slightly biased low. |
Gaussian noise gives squared error | Maximising a Gaussian likelihood is the same as minimising squared error, which is why MSE is the default regression loss. LessonMaximum Likelihood Estimation (MLE)PracticeMean Squared Error |
Posterior is likelihood times prior | Bayesian inference updates a prior belief about the parameters with the likelihood of the observed data. |
MAP estimate | MAP adds a log-prior to the log-likelihood, and a zero-mean Gaussian prior on the weights gives L2 regularisation. |
Which probability formulas should you know for machine learning?
You should know the rules for conditional probability and Bayes’ theorem, the common distributions, expectation and variance, covariance, and the limit results that justify training on samples. Language models, Naive Bayes, Gaussian models and Monte Carlo methods are all built from these rows.
| Formula | What it means |
|---|---|
Conditional probability | Conditioning restricts the sample space to the outcomes where B happened. LessonConditional Probability |
Chain rule of probability | Any joint distribution factors into a chain of conditionals, which is exactly how a language model scores a sentence. LessonConditional ProbabilityPracticeBigram Probabilities |
Independence | Two events are independent when the joint probability factors, which for P(B) above zero means knowing that B happened does not change the probability of A. LessonConditional Probability |
Naive Bayes classifier | Naive Bayes assumes the features are independent given the class, so the likelihood factors into one term per feature. |
CDF and PDF | The CDF accumulates probability, and for a continuous variable the PDF f is its derivative. |
Bernoulli and binomial distributions | The binomial counts successes in n independent trials that each succeed with probability p, and n equal to 1 is the Bernoulli case. LessonProbability Distributions (PDF, PMF, CDF)PracticeBinomial PMF and CDFPracticeBernoulli PMF and Moments |
Poisson distribution | The Poisson models counts of rare events in a fixed window at an average rate λ. |
Normal (Gaussian) density | About 68, 95 and 99.7 percent of the mass lies within 1, 2 and 3 standard deviations of the mean. |
Exponential distribution | The exponential models the waiting time between Poisson events and has no memory of how long you have already waited. |
Expectation and its linearity | Expectation is the probability-weighted average, with an integral in place of the sum for continuous variables, and it is linear even when the variables are dependent. LessonRandom Variables & ExpectationPracticeExpected Value |
Variance identities | Shifting a variable leaves its variance unchanged, and scaling it multiplies the variance by the square of the factor. LessonRandom Variables & ExpectationPracticeExpected Value |
Variance of a sum | The covariance term vanishes only when X and Y are uncorrelated, for example when they are independent. |
Marginalisation | Summing or integrating a joint distribution over one variable leaves the distribution of the other. |
Covariance | Covariance is positive when the variables tend to move together and zero when they are uncorrelated. |
Sample covariance matrix | With every column of the data centred, the diagonal holds the variances and the off-diagonal entries hold the covariances. LessonCovariance MatricesPracticeCovariance Matrix |
Covariance under a linear map | Transforming the data linearly transforms its covariance on both sides. LessonCovariance Matrices |
Mahalanobis distance | This distance measures how far a point is from the mean in units that account for the scale and correlation of the features. LessonCovariance Matrices |
Multivariate normal density | Its contours of equal density are ellipses whose shape and tilt are set by the covariance matrix. LessonCovariance Matrices |
Bayes’ theorem | Bayes turns the probability of the evidence given a hypothesis into the probability of the hypothesis given the evidence. LessonBayes' Theorem & InferencePracticeGaussian Naive Bayes |
Law of total probability | The evidence term in Bayes’ theorem is the sum over every hypothesis that could have produced the evidence. |
Law of large numbers | The sample average converges to the true mean, which is why the average loss over a minibatch estimates the full training loss. LessonLaw of Large Numbers |
Markov’s inequality | A non-negative variable rarely exceeds a large multiple of its mean. LessonChebyshev's Inequality |
Chebyshev’s inequality | For any distribution with finite variance, at most 1/k² of the probability lies k or more standard deviations from the mean. LessonChebyshev's Inequality |
Monte Carlo estimate | Averaging random samples estimates an expectation, and four times as many samples halve the error. |
Markov property and state evolution | The next state depends only on the current one, so the distribution over states evolves by repeated multiplication with the transition matrix. LessonMarkov ChainsPracticeBigram Probabilities |
Stationary distribution | The stationary distribution, written here as a row vector, is unchanged by one more step of the chain. LessonMarkov Chains |
Which linear algebra formulas come up most in machine learning?
The linear algebra formulas that come up most are the dot product, norms, matrix multiplication, inverses, least squares, eigenvalues, the SVD and PCA. Every layer of a neural network is a matrix product, and attention, embeddings and low-rank fine-tuning are all built from the rows below.
| Formula | What it means |
|---|---|
Dot product | The dot product is large when two vectors point the same way and zero when they are orthogonal, where θ here is the angle between them. LessonDot Product & Vector NormsPracticeDot Product |
Lp norms | The L1 norm sums absolute values, the L2 norm is Euclidean length and the L-infinity norm is the largest absolute entry. |
Cosine similarity | Cosine similarity compares direction only and ignores length, which is why it is the usual score for comparing embeddings. |
Matrix product | Each output entry is a row of A dotted with a column of B, at a cost of m times n times p multiply-adds. |
Transpose of a product | Transposing a product reverses the order, and matrix multiplication does not commute. |
Scaled dot-product attention | Attention is two matrix products around a row-wise softmax, scaled by the square root of the key dimension. LessonMatrix Multiplication & Tensor OperationsPracticeCausal Masking for AttentionLLM InternalsAttention Mechanism |
2×2 determinant and inverse | A square matrix is invertible exactly when its determinant is not zero. LessonDeterminants & Matrix InversesPracticeMatrix Inverse |
Determinant and inverse rules | The determinant is the factor by which the linear map scales volume, and inverting a product reverses its order. |
Orthogonal matrix | Orthogonal matrices rotate or reflect vectors without changing their lengths or the angles between them. LessonOrthogonality & Basis VectorsLLM InternalsRoPE |
Gram-Schmidt | Subtracting every earlier direction from each new vector and normalising the result builds an orthonormal basis. |
Projection onto a vector | This is the closest point to a on the line through b. |
Normal equations for least squares | Least squares picks the weights whose residual is orthogonal to every column of X. LessonProjections & Least SquaresPracticeLinear Regression Closed Form |
Projection matrix | P maps any vector onto the column space of X, and applying it twice changes nothing. |
Ridge regression closed form | Adding λI makes the system invertible for any λ above zero and shrinks the weights toward zero. LessonPositive Definite MatricesPracticeRidge Regression |
LU and QR factorisations | LU solves a square system with two triangular solves, and QR solves least squares stably without forming the product of A transpose and A. LessonLU / QR Decomposition |
Eigenvalue equation | An eigenvector keeps its direction under A and is only scaled by its eigenvalue λ. LessonEigenvalues & EigenvectorsPracticeEigenvalues of a Matrix |
Trace and determinant from eigenvalues | The eigenvalues of a square matrix add up to its trace and multiply to its determinant. LessonEigenvalues & EigenvectorsPracticeMatrix Trace |
Eigendecomposition | A real symmetric matrix always has real eigenvalues and an orthonormal set of eigenvectors. |
Positive definite matrix | For a symmetric matrix, positive definiteness holds exactly when every eigenvalue is positive. |
Cholesky factorisation | Every symmetric positive definite matrix factors into a lower-triangular matrix times its own transpose. |
Singular value decomposition | Any matrix acts as a rotation or reflection, a scaling along the axes and another rotation or reflection, and the singular values are the square roots of the eigenvalues of A transpose A. |
Best rank-k approximation (Eckart-Young) | Keeping the top k singular triplets gives the closest rank-k matrix, which is the idea behind the low-rank updates in LoRA. LessonSingular Value Decomposition (SVD) IntuitionLLM InternalsLoRA |
Pseudoinverse | The pseudoinverse gives the minimum-norm least-squares solution even when A is not invertible. |
Principal component analysis | The principal components are the top eigenvectors of the covariance matrix, and projecting the centred data onto the first k of them reduces the dimension. |
Explained variance ratio | Each component’s share of the total variance tells you how many components to keep. |
Gradients of linear and quadratic forms | For a symmetric A the gradient of the quadratic form simplifies to 2Ax. LessonMatrix Calculus |
Least-squares gradient | Setting this gradient to zero gives the normal equations. LessonMatrix CalculusPracticeLinear Regression Closed Form |
Gradient through a linear layer | Backpropagation through a matrix multiply is two more matrix multiplies with transposes. LessonMatrix Calculus |
Which calculus formulas does training a model depend on?
Training depends on the gradient, the chain rule and the derivatives of activation functions, because backpropagation is the chain rule applied layer by layer. The Jacobian, the Hessian and the Taylor expansion describe how the loss bends, and the integral rows explain where ROC AUC comes from.
| Formula | What it means |
|---|---|
Derivative as a limit | The derivative is the slope of the tangent line, the instantaneous rate of change of f at x. LessonLimits & Continuity |
Central-difference gradient check | Comparing this numerical estimate with an analytic gradient is the standard way to test backpropagation code. LessonPartial DerivativesPracticeGradient-Check an Autodiff Graph |
Gradient | The gradient stacks every partial derivative into one vector that points in the direction of steepest increase. LessonPartial Derivatives |
Directional derivative | The rate of change along a unit direction u is largest when u points the same way as the gradient. LessonPartial Derivatives |
Chain rule | Derivatives of composed functions multiply along a path and add across paths. LessonChain Rule |
Activation derivatives | The sigmoid derivative peaks at 0.25, which is one reason deep stacks of sigmoids suffer from vanishing gradients. |
Jacobian | The Jacobian is the best linear approximation of a vector-valued function near a point. |
Hessian | The Hessian holds the second derivatives and describes the curvature of the loss. |
Second-order Taylor expansion | Near a point, a smooth function looks like a quadratic, which is the basis of Newton’s method. |
Trapezoidal rule | The area under a curve is approximated by n trapezoids of equal width h, and the same sum with uneven widths is how ROC AUC is computed from a list of points. LessonIntegration & AUC |
ROC AUC | AUC is the area under the ROC curve, and it equals the chance that a random positive scores above a random negative, with ties counted as half. |
Gradient flow | Gradient descent is a sequence of small discrete steps along this field of negative gradients. LessonVector FieldsPracticeGradient Descent on a Quadratic |
Second-derivative test | The type of a critical point is set by the signs of the Hessian’s eigenvalues, and the test is inconclusive when some of them are zero. |
Backpropagation error signals | The error at each layer is the next layer’s error sent back through the transposed weights and scaled by the local slope of the activation. |
Backpropagation weight gradients | Each weight gradient is the outer product of the layer’s error signal and the layer’s input. |
Gradient descent update | Each step moves the parameters a small distance, set by the learning rate, against the gradient. |
Gradient clipping by global norm | Clipping rescales the whole gradient when its norm exceeds c, so one bad batch cannot blow up training. |
What are the update rules for gradient descent, momentum and Adam?
Gradient descent subtracts the learning rate times the gradient, momentum adds a running velocity to that step, and Adam divides a running average of the gradient by the square root of a running average of its square. The rows below give each update exactly, along with learning rate schedules, regularisation, normalisation and constrained optimisation.
| Formula | What it means |
|---|---|
Convex function | A convex function lies below every chord, so any local minimum is a global minimum. |
Second-order convexity test | A twice-differentiable function is convex exactly when its Hessian is positive semidefinite everywhere. |
Safe step size for a smooth convex loss | With a step no larger than one over the smoothness constant L, gradient descent never increases the loss. |
Minibatch SGD | The minibatch gradient is an unbiased but noisy estimate of the full gradient, where a batch of 1 is plain SGD and a batch of the whole dataset is batch gradient descent. LessonStochastic Gradient Descent (SGD) VariantsLLM InternalsGradient Accumulation |
Cosine annealing schedule | The learning rate falls smoothly from its peak to its floor over T steps. |
Linear warmup | Warmup ramps the learning rate up over a fixed number of warmup steps so that early updates do not destabilise training. |
Momentum | Momentum accumulates a running velocity, so in a steady direction the effective step approaches η/(1 minus β), which is ten times η at β = 0.9. |
Nesterov momentum | Nesterov evaluates the gradient at the look-ahead point, which damps overshooting. LessonMomentum & Nesterov AccelerationPracticeNesterov Momentum |
AdaGrad | Each parameter’s step shrinks with its total squared gradient so far, which can stall long runs. |
RMSProp | RMSProp replaces the running sum in AdaGrad with a moving average, so the step size stops shrinking forever. |
Adam moment estimates | Adam keeps a moving average of the gradient and a moving average of its element-wise square. |
Adam bias correction and update | Bias correction undoes the pull toward zero in the first steps, and the usual defaults are β₁ = 0.9, β₂ = 0.999 and ε = 1e-8. |
AdamW with decoupled weight decay | AdamW applies weight decay directly to the weights instead of adding it to the gradient that Adam rescales. LessonAdaptive Learning Rate Methods (Adam, RMSprop)PracticeAdamW |
Sharpness-aware minimisation | SAM looks for weights whose whole neighbourhood has a low loss, which favours flat minima. LessonLoss Landscapes |
L2 regularisation | With this penalty every SGD step shrinks each weight by a constant factor, which is why it is also called weight decay. LessonRegularization (L1, L2, Dropout)PracticeRidge Regression |
L1 regularisation and soft thresholding | The L1 penalty pushes small weights to exactly zero, and its proximal step is soft thresholding with τ equal to the learning rate times λ. |
Inverted dropout | During training each unit is dropped with probability p and the survivors are scaled up, so nothing changes at inference. LessonRegularization (L1, L2, Dropout)PracticeDropout in Training Mode |
Bias-variance decomposition | Expected squared error splits into systematic error, sensitivity to the particular training set and noise that no model can remove. |
Batch normalisation | Batch norm standardises each feature over the batch and then lets the network learn a scale and a shift. LessonBatch NormalizationPracticeBatch Normalization |
Layer normalisation | Layer norm uses the statistics of each example’s own features, so it does not depend on the batch size. LessonBatch Normalization |
RMSNorm | RMSNorm drops the mean subtraction and the bias of layer norm, and it is the normalisation that many recent large language models use. LessonBatch NormalizationPracticeRMSNorm Forward Pass |
Newton’s method | Newton’s method jumps to the minimum of the local quadratic and converges quadratically near a solution. LessonNewton's MethodPracticeL-BFGS Two-Loop Recursion |
Lagrange condition for an equality constraint | At a constrained optimum the gradient of the objective is parallel to the gradient of the constraint. |
KKT conditions | KKT extends Lagrange multipliers to inequality constraints, and complementary slackness says an inactive constraint has a zero multiplier. |
Hard-margin SVM and hinge loss | The SVM maximises the margin, and the hinge loss is its soft-margin penalty for labels of minus 1 and plus 1. LessonLagrange Multipliers & KKTPracticeHinge Loss |
Which graph theory formulas are used in graph neural networks?
Graph neural networks use the adjacency and degree matrices, the graph Laplacian and its normalised forms, random-walk transition matrices and the message-passing update. The same graph view also explains backpropagation, which runs on the computational graph of a model.
| Formula | What it means |
|---|---|
Adjacency matrix and degree | The adjacency matrix lists the edges, and in an undirected graph the degrees add up to twice the number of edges. |
Storage cost of a graph | Sparse graphs should be stored as adjacency lists or sparse matrices. |
Graph Laplacian | The Laplacian is the diagonal degree matrix minus the adjacency matrix. LessonSpectral Graph Theory |
Laplacian quadratic form | The form measures how much a signal on the nodes changes across edges, so the Laplacian is positive semidefinite. LessonSpectral Graph Theory |
Laplacian spectrum | The second-smallest eigenvalue measures how well connected the graph is, and its eigenvector, the Fiedler vector, splits the graph in spectral clustering. LessonSpectral Graph Theory |
Normalised Laplacians | Normalising by degree stops high-degree nodes from dominating the spectrum. LessonSpectral Graph Theory |
Random-walk transition matrix | Each step moves to a uniformly random neighbour, and k steps are given by the k-th power of P. |
Stationary distribution of a random walk | On a connected undirected graph the walk spends time at each node in proportion to its degree, and it converges to this distribution when the graph is not bipartite. |
PageRank | PageRank is the stationary distribution of a random walk that jumps to a random node with probability 1 minus α. |
Reverse-mode accumulation on a computational graph | Backpropagation visits the graph in reverse topological order and sums the gradient arriving along every path that leaves a node, where the bar here means an adjoint. |
GCN layer | Each node averages its own features and its neighbours’ features with symmetric degree normalisation and then applies a shared linear map. LessonIntroduction to GNNs |
Message passing | Every GNN layer gathers messages from the neighbours, combines them with an order-independent function such as a sum or mean and updates the node state. LessonMessage Passing (GNNs) |
Graph attention weights | A graph attention network learns how much each neighbour should count instead of using fixed degree weights. LessonMessage Passing (GNNs) |
Which information theory formulas does machine learning use?
Machine learning uses entropy, cross-entropy, KL divergence, mutual information, information gain and perplexity. Cross-entropy is the loss for almost every classifier and language model, KL divergence appears in VAEs and RLHF, and information gain is how decision trees choose splits.
| Formula | What it means |
|---|---|
Self-information | Rare outcomes carry more information, measured in bits with log base 2 or in nats with the natural log. LessonShannon Entropy |
Shannon entropy | Entropy is the average surprise, and it is largest for the uniform distribution over n outcomes. LessonShannon EntropyPracticeEntropy for a Node |
Bits and nats | The base of the log only rescales entropy, and deep learning frameworks use the natural log, so their losses are in nats. |
Cross-entropy | Cross-entropy is the cost of coding data from P with a code built for Q, so minimising it over Q also minimises the KL gap. |
Binary cross-entropy | Binary cross-entropy is the negative log-likelihood of a 0 or 1 label given the predicted probability. LessonCross-Entropy LossPracticeBinary Log Loss |
Categorical cross-entropy | With one-hot labels the loss is minus the log of the probability given to the correct class. LessonCross-Entropy LossPracticeCross-Entropy Loss |
Softmax in its stable form | Softmax turns logits into probabilities, and subtracting the largest logit changes nothing mathematically but prevents overflow. LessonCross-Entropy LossPracticeNumerically Stable Softmax |
Gradient of softmax with cross-entropy | The gradient with respect to the logits is the predicted probability minus the true label, and the same holds for a sigmoid with binary cross-entropy. LessonCross-Entropy Loss |
KL divergence | KL divergence measures the extra cost of using Q in place of P, and it is zero only when they match and is not symmetric. |
KL divergence between two Gaussians | VAEs use this closed form, and against a standard normal it becomes minus one half times the sum of 1 + log σ² − μ² − σ². |
Mutual information | Mutual information is how much knowing Y reduces uncertainty about X, and it is zero exactly when the two are independent. LessonMutual Information |
Mutual information from entropies | Mutual information is symmetric, never negative and no larger than the smaller of the two entropies. LessonMutual Information |
Information gain | A decision tree picks the split that most reduces the size-weighted entropy of the child nodes. LessonInformation Gain (Decision Trees)PracticeInformation Gain |
Gini impurity | Gini is the chance of mislabelling a random sample if you label it at random from the node’s class mix, and it is a cheaper alternative to entropy. LessonInformation Gain (Decision Trees)PracticeGini Impurity |
Perplexity | Perplexity is e raised to the average cross-entropy per token in nats, or 2 raised to the same quantity in bits, and a model that guesses uniformly over V tokens has perplexity V. |
Jensen-Shannon divergence | JSD is a symmetric and bounded version of KL divergence that lies between 0 and ln 2 nats, and its square root is a true distance metric. |
How should you use this formula sheet?
Use the sheet as an index into the lessons. When a formula looks unfamiliar, read its one-line meaning, open the lesson in that row to see where it comes from, and then implement it in the linked problem until you can write it without looking.
Implementing a formula in code is the fastest way to find the parts you only half understand, such as which axis a softmax runs over or why Adam needs bias correction. The essay on learning machine learning from scratch explains why building each piece yourself works, and the guide to ML coding interview questions shows which of these formulas turn up as implementation tasks. When you need to choose between formulas for your own model, the guides on which loss function to use, which optimizer to use and which evaluation metric to use make that decision, and the machine learning glossary defines the terms in plain words.
What else do learners ask about ML math formulas?
Is a formula sheet enough to learn the maths for machine learning?
A formula sheet is a lookup tool and is not enough on its own. It tells you what a formula says, while the lesson linked in each row shows where the formula comes from, and implementing it in a practice problem is what makes it stick.
Why does sample variance divide by n minus 1?
The sample mean is computed from the same data, so the squared deviations from it are slightly smaller on average than the squared deviations from the true mean. Dividing by n minus 1 instead of n, which is called Bessel’s correction, removes that bias and makes the sample variance an unbiased estimate of the population variance.
What is the difference between cross-entropy and KL divergence?
Cross-entropy equals the entropy of the true distribution plus the KL divergence between the true distribution and the model. When the labels are fixed, that entropy is a constant, so minimising cross-entropy and minimising KL divergence give the same gradients.
What does a hat or a bar over a symbol mean in ML formulas?
A hat marks an estimate or a prediction, so y hat is the model output and theta hat is a fitted parameter. A bar usually marks a sample mean, so x bar is the average of the data you have while mu is the true mean. In backpropagation formulas a bar can also mean the gradient of the loss with respect to that variable.
Which formulas should you know by heart for an ML interview?
Candidates commonly report being asked to write softmax, cross-entropy, the gradient descent update, Adam and scaled dot-product attention from memory and to explain each term. For most of the other rows, it is usually enough to recognise the formula and say what it does.
Which math topic matters most for machine learning?
Linear algebra and calculus run every forward and backward pass of a neural network, so they matter most for deep learning. Probability, statistics and information theory define the losses and the evaluation, and optimization decides how training behaves, so most ML engineers use six of the seven areas regularly. Graph theory matters mainly when the data is a graph.
Practice this
Each of these problems has you implement a formula from the sheet in Python and checks it against test cases. Then browse the problem library, or work through the ML Math lessons in order.
- Implement Numerically Stable Softmax has you subtract the largest logit before exponentiating, as in the stable softmax row.
- Implement Cross-Entropy Loss has you turn predicted probabilities and labels into the categorical cross-entropy loss.
- Implement KL Divergence has you compute the divergence between two discrete distributions, as in the KL divergence row.
- Implement Adam Optimizer Step has you write the moment estimates, the bias correction and the update from the optimization rows.
Related guides
- Machine learning glossary
- Which loss function to use
- Which optimizer to use
- Which evaluation metric to use
- Why training loss is not decreasing
- Learning machine learning from scratch
- Twenty ML coding interview questions to implement
- ML papers to implement from scratch
- How to prepare for an ML engineer interview