TensorTonic guides

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.

By TensorTonic's founderLast updated Reference sheet

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.

The machine learning formulas that come up most
Sample variance with Bessel’s correction
s2=1n−1∑i=1n(xi−xˉ)2\displaystyle s^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i-\bar{x})^2

Dividing by n minus 1 makes the sample variance an unbiased estimate of the population variance.

Expectation and its linearity
E[X]=∑xx P(X=x)\displaystyle \mathbb{E}[X]=\sum_x x\,P(X=x)E[aX+bY]=a E[X]+b E[Y]\displaystyle \mathbb{E}[aX+bY]=a\,\mathbb{E}[X]+b\,\mathbb{E}[Y]

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.

Bayes’ theorem
P(H∣E)=P(E∣H) P(H)P(E)\displaystyle P(H\mid E)=\frac{P(E\mid H)\,P(H)}{P(E)}

Bayes turns the probability of the evidence given a hypothesis into the probability of the hypothesis given the evidence.

Normal (Gaussian) density
f(x)=1σ2πexp⁡ ⁣(−(x−μ)22σ2)\displaystyle f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)

About 68, 95 and 99.7 percent of the mass lies within 1, 2 and 3 standard deviations of the mean.

Dot product
a⋅b=a⊤b=∑iaibi=∥a∥ ∥b∥cos⁡θ\displaystyle a\cdot b=a^{\top}b=\sum_i a_i b_i=\lVert a\rVert\,\lVert b\rVert\cos\theta

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.

Matrix product
Cij=∑kAikBkj\displaystyle C_{ij}=\sum_{k} A_{ik}B_{kj}(m×n)(n×p)→m×p\displaystyle (m\times n)(n\times p)\to m\times p

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
Av=λv\displaystyle Av=\lambda vdet⁡(A−λI)=0\displaystyle \det(A-\lambda I)=0

An eigenvector keeps its direction under A and is only scaled by its eigenvalue λ.

Chain rule
dydx=dydu⋅dudx\displaystyle \frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}dfdx=∑j∂f∂ujdujdx\displaystyle \frac{df}{dx}=\sum_j \frac{\partial f}{\partial u_j}\frac{du_j}{dx}

Derivatives of composed functions multiply along a path and add across paths.

Gradient descent update
θt+1=θt−η ∇L(θt)\displaystyle \theta_{t+1}=\theta_t-\eta\,\nabla L(\theta_t)

Each step moves the parameters a small distance, set by the learning rate, against the gradient.

Adam bias correction and update
m^t=mt1−β1t,  v^t=vt1−β2t\displaystyle \hat{m}_t=\frac{m_t}{1-\beta_1^t},\ \ \hat{v}_t=\frac{v_t}{1-\beta_2^t}θt=θt−1−η m^tv^t+ϵ\displaystyle \theta_t=\theta_{t-1}-\eta\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}

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⁡(z)i=ezi−max⁡jzj∑kezk−max⁡jzj\displaystyle \operatorname{softmax}(z)_i=\frac{e^{z_i-\max_j z_j}}{\sum_k e^{z_k-\max_j z_j}}

Softmax turns logits into probabilities, and subtracting the largest logit changes nothing mathematically but prevents overflow.

Categorical cross-entropy
ℓ=−∑c=1Cyclog⁡y^c=−log⁡y^true\displaystyle \ell=-\sum_{c=1}^{C}y_c\log\hat{y}_c=-\log\hat{y}_{\text{true}}

With one-hot labels the loss is minus the log of the probability given to the correct class.

KL divergence
DKL(P ∥ Q)=∑xP(x)log⁡P(x)Q(x) ≥0\displaystyle D_{\mathrm{KL}}(P\,\Vert\,Q)=\sum_x P(x)\log\frac{P(x)}{Q(x)}\ \ge 0

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(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\displaystyle \text{Attention}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V

Attention is two matrix products around a row-wise softmax, scaled by the square root of the key dimension.

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.

Symbol decoder

Pick a symbol to see what it means. Every row on this page that uses it gets a green edge.

∇\nablanabla, the gradient

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.

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.

Statistics formulas for machine learning
Sample mean
xˉ=1n∑i=1nxi\displaystyle \bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i

The mean is the sum of the values divided by how many there are.

Population variance and standard deviation
σ2=1N∑i=1N(xi−μ)2\displaystyle \sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2σ=σ2\displaystyle \sigma=\sqrt{\sigma^2}

Variance is the average squared distance from the mean, and the standard deviation is its square root, in the same units as the data.

Interquartile range and outlier fences
IQR=Q3−Q1\displaystyle \text{IQR}=Q_3-Q_1x<Q1−1.5 IQR or x>Q3+1.5 IQR\displaystyle x<Q_1-1.5\,\text{IQR}\ \text{or}\ x>Q_3+1.5\,\text{IQR}

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.

Sample variance with Bessel’s correction
s2=1n−1∑i=1n(xi−xˉ)2\displaystyle s^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i-\bar{x})^2

Dividing by n minus 1 makes the sample variance an unbiased estimate of the population variance.

Standard error of the mean
SE(xˉ)=σn≈sn\displaystyle \text{SE}(\bar{x}) = \frac{\sigma}{\sqrt{n}} \approx \frac{s}{\sqrt{n}}

The spread of the sample mean shrinks with the square root of the sample size.

Standard error of a proportion
SE(p^)=p(1−p)n\displaystyle \text{SE}(\hat{p}) = \sqrt{\frac{p(1-p)}{n}}

A sample proportion varies around the true rate p by about this amount.

Central limit theorem
Xˉn≈N ⁣(μ,σ2n) for large n\displaystyle \bar{X}_n \approx \mathcal{N}\!\left(\mu, \frac{\sigma^2}{n}\right)\ \text{for large } n

The mean of many independent draws with finite variance is approximately normal whatever the original distribution, and the second argument here is a variance.

z-score of a sample mean
z=xˉ−μσ/n\displaystyle z = \frac{\bar{x}-\mu}{\sigma/\sqrt{n}}

The z-score counts how many standard errors the sample mean sits from the population mean.

Confidence interval for a mean
xˉ±z∗σn  or  xˉ±tn−1∗sn\displaystyle \bar{x} \pm z^{*}\frac{\sigma}{\sqrt{n}}\ \ \text{or}\ \ \bar{x} \pm t^{*}_{n-1}\frac{s}{\sqrt{n}}

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
p^±z∗p^(1−p^)n\displaystyle \hat{p} \pm z^{*}\sqrt{\frac{\hat{p}(1-\hat{p})}{n}}

This is the normal-approximation interval for a rate such as a click-through rate.

One-sample z-test statistic
z=xˉ−μ0σ/n\displaystyle z = \frac{\bar{x}-\mu_0}{\sigma/\sqrt{n}}

The test statistic measures how far the data sit from the null value, in standard-error units.

Chi-square statistic
χ2=∑(O−E)2E\displaystyle \chi^2 = \sum \frac{(O-E)^2}{E}

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.

Two-sided p-value from z
p=2(1−Φ(∣z∣))\displaystyle p = 2\left(1-\Phi(\lvert z\rvert)\right)

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.

Bonferroni correction
αper test=αm\displaystyle \alpha_{\text{per test}} = \frac{\alpha}{m}

Testing m hypotheses at α/m each keeps the chance of any false positive at or below α.

Type I error, Type II error and power
α=P(reject H0∣H0)\displaystyle \alpha = P(\text{reject } H_0 \mid H_0)β=P(keep H0∣H1)\displaystyle \beta = P(\text{keep } H_0 \mid H_1)power=1−β\displaystyle \text{power}=1-\beta

α is the false-positive rate, β is the false-negative rate and power is the chance of detecting a real effect.

One-sample t statistic
t=xˉ−μ0s/n\displaystyle t = \frac{\bar{x}-\mu_0}{s/\sqrt{n}}df=n−1\displaystyle \text{df}=n-1

The t statistic replaces σ with s, so its reference distribution has heavier tails for small samples.

Two-proportion z-test for an A/B test
z=p^B−p^Ap^(1−p^)(1nA+1nB)\displaystyle z = \frac{\hat{p}_B-\hat{p}_A}{\sqrt{\hat{p}(1-\hat{p})\left(\frac{1}{n_A}+\frac{1}{n_B}\right)}}p^=xA+xBnA+nB\displaystyle \hat{p}=\frac{x_A+x_B}{n_A+n_B}

The pooled rate gives the standard error under the null hypothesis that both variants convert equally.

A/B test sample size per group
n≈2pˉ(1−pˉ) (z1−α/2+z1−β)2(pB−pA)2\displaystyle n \approx \frac{2\bar{p}(1-\bar{p})\,(z_{1-\alpha/2}+z_{1-\beta})^2}{(p_B-p_A)^2}

Halving the lift you want to detect roughly quadruples the users needed in each group.

One-way ANOVA F statistic
F=SSB/(k−1)SSW/(N−k)\displaystyle F = \frac{\text{SSB}/(k-1)}{\text{SSW}/(N-k)}SST=SSB+SSW\displaystyle \text{SST}=\text{SSB}+\text{SSW}

F compares the variation between group means with the variation within groups, for k groups and N observations.

LessonANOVA
Pearson correlation
r=∑(xi−xˉ)(yi−yˉ)∑(xi−xˉ)2∑(yi−yˉ)2\displaystyle r = \frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum (x_i-\bar{x})^2}\sqrt{\sum (y_i-\bar{y})^2}}

r measures linear association on a scale from minus 1 to 1 and says nothing about causation.

Spearman rank correlation with no ties
ρ=1−6∑di2n(n2−1)\displaystyle \rho = 1 - \frac{6\sum d_i^2}{n(n^2-1)}

Spearman is Pearson computed on ranks, so it captures any monotonic relationship, and dᵢ is the difference between the two ranks of item i.

Bootstrap percentile interval
[θ^(α/2)∗, θ^(1−α/2)∗]\displaystyle \left[\hat{\theta}^{*}_{(\alpha/2)},\ \hat{\theta}^{*}_{(1-\alpha/2)}\right]

Resample the data with replacement many times, recompute the statistic each time and keep the middle 1 minus α of the results.

k-fold cross-validation estimate
CVk=1k∑j=1kErrj\displaystyle \text{CV}_k = \frac{1}{k}\sum_{j=1}^{k} \text{Err}_j

The model is trained k times, scored each time on the one fold it did not see, and the k scores are averaged.

Maximum likelihood estimate
θ^MLE=arg⁡max⁡θ∑i=1nlog⁡p(xi;θ)\displaystyle \hat{\theta}_{\text{MLE}} = \arg\max_{\theta} \sum_{i=1}^{n} \log p(x_i;\theta)

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
p^=kn (Bernoulli)\displaystyle \hat{p}=\frac{k}{n}\ \text{(Bernoulli)}μ^=xˉ,  σ^2=1n∑(xi−xˉ)2 (Gaussian)\displaystyle \hat{\mu}=\bar{x},\ \ \hat{\sigma}^2=\frac{1}{n}\sum (x_i-\bar{x})^2\ \text{(Gaussian)}

The Gaussian MLE of the variance divides by n, so it is slightly biased low.

Gaussian noise gives squared error
−log⁡L(μ)=12σ2∑i=1n(xi−μ)2+const\displaystyle -\log L(\mu) = \frac{1}{2\sigma^2}\sum_{i=1}^{n} (x_i-\mu)^2 + \text{const}

Maximising a Gaussian likelihood is the same as minimising squared error, which is why MSE is the default regression loss.

Posterior is likelihood times prior
p(θ∣D)∝p(D∣θ) p(θ)\displaystyle p(\theta \mid D) \propto p(D \mid \theta)\,p(\theta)

Bayesian inference updates a prior belief about the parameters with the likelihood of the observed data.

MAP estimate
θ^MAP=arg⁡max⁡θ[log⁡p(D∣θ)+log⁡p(θ)]\displaystyle \hat{\theta}_{\text{MAP}} = \arg\max_{\theta}\left[\log p(D\mid\theta) + \log p(\theta)\right]

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.

Probability formulas for machine learning
Conditional probability
P(A∣B)=P(A∩B)P(B)\displaystyle P(A \mid B) = \frac{P(A \cap B)}{P(B)}P(B)>0\displaystyle P(B)>0

Conditioning restricts the sample space to the outcomes where B happened.

Chain rule of probability
P(x1,…,xn)=∏i=1nP(xi∣x1,…,xi−1)\displaystyle P(x_1,\dots,x_n) = \prod_{i=1}^{n} P(x_i \mid x_1,\dots,x_{i-1})

Any joint distribution factors into a chain of conditionals, which is exactly how a language model scores a sentence.

Independence
P(A∩B)=P(A) P(B)\displaystyle P(A \cap B) = P(A)\,P(B)P(A∣B)=P(A) if P(B)>0\displaystyle P(A\mid B)=P(A)\ \text{if}\ P(B)>0

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.

Naive Bayes classifier
P(C∣x)∝P(C)∏i=1dP(xi∣C)\displaystyle P(C\mid x) \propto P(C)\prod_{i=1}^{d} P(x_i\mid C)

Naive Bayes assumes the features are independent given the class, so the likelihood factors into one term per feature.

CDF and PDF
F(x)=P(X≤x)\displaystyle F(x)=P(X\le x)P(a<X<b)=∫abf(x) dx\displaystyle P(a<X<b)=\int_a^b f(x)\,dx

The CDF accumulates probability, and for a continuous variable the PDF f is its derivative.

Bernoulli and binomial distributions
P(k)=(nk)pk(1−p)n−k\displaystyle P(k)=\binom{n}{k}p^k(1-p)^{n-k}E[K]=np, Var⁡(K)=np(1−p)\displaystyle \mathbb{E}[K]=np,\ \operatorname{Var}(K)=np(1-p)

The binomial counts successes in n independent trials that each succeed with probability p, and n equal to 1 is the Bernoulli case.

Poisson distribution
P(k)=λke−λk!\displaystyle P(k)=\frac{\lambda^k e^{-\lambda}}{k!}E[K]=Var⁡(K)=λ\displaystyle \mathbb{E}[K]=\operatorname{Var}(K)=\lambda

The Poisson models counts of rare events in a fixed window at an average rate λ.

Normal (Gaussian) density
f(x)=1σ2πexp⁡ ⁣(−(x−μ)22σ2)\displaystyle f(x)=\frac{1}{\sigma\sqrt{2\pi}}\exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)

About 68, 95 and 99.7 percent of the mass lies within 1, 2 and 3 standard deviations of the mean.

Exponential distribution
f(x)=λe−λx, x≥0\displaystyle f(x)=\lambda e^{-\lambda x},\ x\ge 0E[X]=1λ, Var⁡(X)=1λ2\displaystyle \mathbb{E}[X]=\frac{1}{\lambda},\ \operatorname{Var}(X)=\frac{1}{\lambda^2}

The exponential models the waiting time between Poisson events and has no memory of how long you have already waited.

Expectation and its linearity
E[X]=∑xx P(X=x)\displaystyle \mathbb{E}[X]=\sum_x x\,P(X=x)E[aX+bY]=a E[X]+b E[Y]\displaystyle \mathbb{E}[aX+bY]=a\,\mathbb{E}[X]+b\,\mathbb{E}[Y]

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.

Variance identities
Var⁡(X)=E[X2]−E[X]2\displaystyle \operatorname{Var}(X)=\mathbb{E}[X^2]-\mathbb{E}[X]^2Var⁡(aX+b)=a2Var⁡(X)\displaystyle \operatorname{Var}(aX+b)=a^2\operatorname{Var}(X)

Shifting a variable leaves its variance unchanged, and scaling it multiplies the variance by the square of the factor.

Variance of a sum
Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)+2Cov⁡(X,Y)\displaystyle \operatorname{Var}(X+Y)=\operatorname{Var}(X)+\operatorname{Var}(Y)+2\operatorname{Cov}(X,Y)

The covariance term vanishes only when X and Y are uncorrelated, for example when they are independent.

Marginalisation
P(x)=∑yP(x,y)\displaystyle P(x)=\sum_y P(x,y)p(x)=∫p(x,y) dy\displaystyle p(x)=\int p(x,y)\,dy

Summing or integrating a joint distribution over one variable leaves the distribution of the other.

Covariance
Cov⁡(X,Y)=E[XY]−E[X] E[Y]\displaystyle \operatorname{Cov}(X,Y)=\mathbb{E}[XY]-\mathbb{E}[X]\,\mathbb{E}[Y]

Covariance is positive when the variables tend to move together and zero when they are uncorrelated.

Sample covariance matrix
Σ=1n−1Xc⊤Xc\displaystyle \Sigma = \frac{1}{n-1}X_c^{\top}X_c

With every column of the data centred, the diagonal holds the variances and the off-diagonal entries hold the covariances.

Covariance under a linear map
Cov⁡(AX)=A Σ A⊤\displaystyle \operatorname{Cov}(AX)=A\,\Sigma\,A^{\top}

Transforming the data linearly transforms its covariance on both sides.

Mahalanobis distance
DM(x)=(x−μ)⊤Σ−1(x−μ)\displaystyle D_M(x)=\sqrt{(x-\mu)^{\top}\Sigma^{-1}(x-\mu)}

This distance measures how far a point is from the mean in units that account for the scale and correlation of the features.

Multivariate normal density
p(x)=1(2π)d/2∣Σ∣1/2exp⁡ ⁣(−12(x−μ)⊤Σ−1(x−μ))\displaystyle p(x)=\frac{1}{(2\pi)^{d/2}\lvert\Sigma\rvert^{1/2}}\exp\!\left(-\tfrac{1}{2}(x-\mu)^{\top}\Sigma^{-1}(x-\mu)\right)

Its contours of equal density are ellipses whose shape and tilt are set by the covariance matrix.

Bayes’ theorem
P(H∣E)=P(E∣H) P(H)P(E)\displaystyle P(H\mid E)=\frac{P(E\mid H)\,P(H)}{P(E)}

Bayes turns the probability of the evidence given a hypothesis into the probability of the hypothesis given the evidence.

Law of total probability
P(E)=∑iP(E∣Hi) P(Hi)\displaystyle P(E)=\sum_i P(E\mid H_i)\,P(H_i)

The evidence term in Bayes’ theorem is the sum over every hypothesis that could have produced the evidence.

Law of large numbers
Xˉn→μ as n→∞\displaystyle \bar{X}_n \to \mu\ \text{as}\ n\to\inftyVar⁡(Xˉn)=σ2n\displaystyle \operatorname{Var}(\bar{X}_n)=\frac{\sigma^2}{n}

The sample average converges to the true mean, which is why the average loss over a minibatch estimates the full training loss.

Markov’s inequality
P(X≥a)≤E[X]a\displaystyle P(X \ge a) \le \frac{\mathbb{E}[X]}{a}X≥0, a>0\displaystyle X\ge 0,\ a>0

A non-negative variable rarely exceeds a large multiple of its mean.

Chebyshev’s inequality
P(∣X−μ∣≥kσ)≤1k2\displaystyle P(\lvert X-\mu\rvert \ge k\sigma) \le \frac{1}{k^2}

For any distribution with finite variance, at most 1/k² of the probability lies k or more standard deviations from the mean.

Monte Carlo estimate
E[f(X)]≈1N∑i=1Nf(xi)\displaystyle \mathbb{E}[f(X)] \approx \frac{1}{N}\sum_{i=1}^{N} f(x_i)error∝1N\displaystyle \text{error} \propto \frac{1}{\sqrt{N}}

Averaging random samples estimates an expectation, and four times as many samples halve the error.

Markov property and state evolution
P(Xt+1∣Xt,…,X0)=P(Xt+1∣Xt)\displaystyle P(X_{t+1}\mid X_t,\dots,X_0)=P(X_{t+1}\mid X_t)πt=π0Pt\displaystyle \pi_t=\pi_0 P^{t}

The next state depends only on the current one, so the distribution over states evolves by repeated multiplication with the transition matrix.

Stationary distribution
πP=π\displaystyle \pi P = \pi∑iπi=1\displaystyle \sum_i \pi_i = 1

The stationary distribution, written here as a row vector, is unchanged by one more step of the chain.

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.

Linear Algebra formulas for machine learning
Dot product
a⋅b=a⊤b=∑iaibi=∥a∥ ∥b∥cos⁡θ\displaystyle a\cdot b=a^{\top}b=\sum_i a_i b_i=\lVert a\rVert\,\lVert b\rVert\cos\theta

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.

Lp norms
∥x∥p=(∑i∣xi∣p)1/p\displaystyle \lVert x\rVert_p=\left(\sum_i \lvert x_i\rvert^p\right)^{1/p}∥x∥∞=max⁡i∣xi∣\displaystyle \lVert x\rVert_\infty=\max_i \lvert x_i\rvert

The L1 norm sums absolute values, the L2 norm is Euclidean length and the L-infinity norm is the largest absolute entry.

Cosine similarity
cos⁡(a,b)=a⋅b∥a∥2 ∥b∥2\displaystyle \cos(a,b)=\frac{a\cdot b}{\lVert a\rVert_2\,\lVert b\rVert_2}

Cosine similarity compares direction only and ignores length, which is why it is the usual score for comparing embeddings.

Matrix product
Cij=∑kAikBkj\displaystyle C_{ij}=\sum_{k} A_{ik}B_{kj}(m×n)(n×p)→m×p\displaystyle (m\times n)(n\times p)\to m\times p

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
(AB)⊤=B⊤A⊤\displaystyle (AB)^{\top}=B^{\top}A^{\top}AB≠BA in general\displaystyle AB \ne BA\ \text{in general}

Transposing a product reverses the order, and matrix multiplication does not commute.

Scaled dot-product attention
Attention(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\displaystyle \text{Attention}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V

Attention is two matrix products around a row-wise softmax, scaled by the square root of the key dimension.

2×2 determinant and inverse
det⁡[abcd]=ad−bc\displaystyle \det\begin{bmatrix}a&b\\c&d\end{bmatrix}=ad-bcA−1=1ad−bc[d−b−ca]\displaystyle A^{-1}=\frac{1}{ad-bc}\begin{bmatrix}d&-b\\-c&a\end{bmatrix}

A square matrix is invertible exactly when its determinant is not zero.

Determinant and inverse rules
det⁡(AB)=det⁡A det⁡B\displaystyle \det(AB)=\det A\,\det B(AB)−1=B−1A−1\displaystyle (AB)^{-1}=B^{-1}A^{-1}det⁡(A−1)=1det⁡A\displaystyle \det(A^{-1})=\frac{1}{\det A}

The determinant is the factor by which the linear map scales volume, and inverting a product reverses its order.

Orthogonal matrix
Q⊤Q=QQ⊤=I\displaystyle Q^{\top}Q=QQ^{\top}=IQ−1=Q⊤\displaystyle Q^{-1}=Q^{\top}∥Qx∥=∥x∥\displaystyle \lVert Qx\rVert=\lVert x\rVert

Orthogonal matrices rotate or reflect vectors without changing their lengths or the angles between them.

Gram-Schmidt
uk=vk−∑j<k(vk⋅qj) qj\displaystyle u_k=v_k-\sum_{j<k}(v_k\cdot q_j)\,q_jqk=uk∥uk∥\displaystyle q_k=\frac{u_k}{\lVert u_k\rVert}

Subtracting every earlier direction from each new vector and normalising the result builds an orthonormal basis.

Projection onto a vector
proj⁡b(a)=a⋅bb⋅b b\displaystyle \operatorname{proj}_b(a)=\frac{a\cdot b}{b\cdot b}\,b

This is the closest point to a on the line through b.

Normal equations for least squares
X⊤Xw^=X⊤y  ⇒  w^=(X⊤X)−1X⊤y\displaystyle X^{\top}X\hat{w}=X^{\top}y \;\Rightarrow\; \hat{w}=(X^{\top}X)^{-1}X^{\top}y

Least squares picks the weights whose residual is orthogonal to every column of X.

Projection matrix
P=X(X⊤X)−1X⊤\displaystyle P=X(X^{\top}X)^{-1}X^{\top}P2=P, P⊤=P\displaystyle P^2=P,\ P^{\top}=P

P maps any vector onto the column space of X, and applying it twice changes nothing.

Ridge regression closed form
w^=(X⊤X+λI)−1X⊤y\displaystyle \hat{w}=(X^{\top}X+\lambda I)^{-1}X^{\top}y

Adding λI makes the system invertible for any λ above zero and shrinks the weights toward zero.

LU and QR factorisations
PA=LU\displaystyle PA=LUA=QR ⇒ Rx^=Q⊤b\displaystyle A=QR\ \Rightarrow\ R\hat{x}=Q^{\top}b

LU solves a square system with two triangular solves, and QR solves least squares stably without forming the product of A transpose and A.

Eigenvalue equation
Av=λv\displaystyle Av=\lambda vdet⁡(A−λI)=0\displaystyle \det(A-\lambda I)=0

An eigenvector keeps its direction under A and is only scaled by its eigenvalue λ.

Trace and determinant from eigenvalues
tr⁡(A)=∑iλi\displaystyle \operatorname{tr}(A)=\sum_i \lambda_idet⁡(A)=∏iλi\displaystyle \det(A)=\prod_i \lambda_i

The eigenvalues of a square matrix add up to its trace and multiply to its determinant.

Eigendecomposition
A=QΛQ−1 if diagonalisable\displaystyle A=Q\Lambda Q^{-1}\ \text{if diagonalisable}A=QΛQ⊤ if A=A⊤\displaystyle A=Q\Lambda Q^{\top}\ \text{if } A=A^{\top}

A real symmetric matrix always has real eigenvalues and an orthonormal set of eigenvectors.

Positive definite matrix
x⊤Ax>0  ∀x≠0  ⟺  λi(A)>0  ∀i\displaystyle x^{\top}Ax>0\ \ \forall x\neq 0 \iff \lambda_i(A)>0\ \ \forall i

For a symmetric matrix, positive definiteness holds exactly when every eigenvalue is positive.

Cholesky factorisation
A=LL⊤\displaystyle A=LL^{\top}

Every symmetric positive definite matrix factors into a lower-triangular matrix times its own transpose.

Singular value decomposition
A=UΣV⊤\displaystyle A=U\Sigma V^{\top}σi=λi(A⊤A)\displaystyle \sigma_i=\sqrt{\lambda_i(A^{\top}A)}

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)
Ak=∑i=1kσiuivi⊤\displaystyle A_k=\sum_{i=1}^{k}\sigma_i u_i v_i^{\top}∥A−Ak∥F2=∑i>kσi2\displaystyle \lVert A-A_k\rVert_F^2=\sum_{i>k}\sigma_i^2

Keeping the top k singular triplets gives the closest rank-k matrix, which is the idea behind the low-rank updates in LoRA.

Pseudoinverse
A+=VΣ+U⊤\displaystyle A^{+}=V\Sigma^{+}U^{\top}A+=(A⊤A)−1A⊤ if A has full column rank\displaystyle A^{+}=(A^{\top}A)^{-1}A^{\top}\ \text{if A has full column rank}

The pseudoinverse gives the minimum-norm least-squares solution even when A is not invertible.

Principal component analysis
Σw=λw\displaystyle \Sigma w=\lambda wZ=XcWk\displaystyle Z=X_c W_k

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
EVRi=λi∑j=1dλj\displaystyle \text{EVR}_i=\frac{\lambda_i}{\sum_{j=1}^{d}\lambda_j}

Each component’s share of the total variance tells you how many components to keep.

Gradients of linear and quadratic forms
∇x(a⊤x)=a\displaystyle \nabla_x(a^{\top}x)=a∇x(x⊤Ax)=(A+A⊤)x\displaystyle \nabla_x(x^{\top}Ax)=(A+A^{\top})x

For a symmetric A the gradient of the quadratic form simplifies to 2Ax.

Least-squares gradient
∇w∥Xw−y∥22=2X⊤(Xw−y)\displaystyle \nabla_w\lVert Xw-y\rVert_2^2=2X^{\top}(Xw-y)

Setting this gradient to zero gives the normal equations.

Gradient through a linear layer
Y=XW  ⇒  ∂L∂W=X⊤∂L∂Y\displaystyle Y=XW \;\Rightarrow\; \frac{\partial L}{\partial W}=X^{\top}\frac{\partial L}{\partial Y}∂L∂X=∂L∂YW⊤\displaystyle \frac{\partial L}{\partial X}=\frac{\partial L}{\partial Y}W^{\top}

Backpropagation through a matrix multiply is two more matrix multiplies with transposes.

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.

Calculus formulas for machine learning
Derivative as a limit
f′(x)=lim⁡h→0f(x+h)−f(x)h\displaystyle f'(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}

The derivative is the slope of the tangent line, the instantaneous rate of change of f at x.

Central-difference gradient check
f′(x)≈f(x+h)−f(x−h)2h\displaystyle f'(x)\approx\frac{f(x+h)-f(x-h)}{2h}error=O(h2)\displaystyle \text{error}=O(h^2)

Comparing this numerical estimate with an analytic gradient is the standard way to test backpropagation code.

Gradient
∇f(x)=[∂f∂x1,…,∂f∂xn]⊤\displaystyle \nabla f(x)=\left[\frac{\partial f}{\partial x_1},\dots,\frac{\partial f}{\partial x_n}\right]^{\top}

The gradient stacks every partial derivative into one vector that points in the direction of steepest increase.

Directional derivative
Duf=∇f⋅u\displaystyle D_u f=\nabla f\cdot u∥u∥=1\displaystyle \lVert u\rVert=1

The rate of change along a unit direction u is largest when u points the same way as the gradient.

Chain rule
dydx=dydu⋅dudx\displaystyle \frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}dfdx=∑j∂f∂ujdujdx\displaystyle \frac{df}{dx}=\sum_j \frac{\partial f}{\partial u_j}\frac{du_j}{dx}

Derivatives of composed functions multiply along a path and add across paths.

Activation derivatives
σ′(z)=σ(z)(1−σ(z))\displaystyle \sigma'(z)=\sigma(z)(1-\sigma(z))tanh⁡′(z)=1−tanh⁡2(z)\displaystyle \tanh'(z)=1-\tanh^2(z)ReLU⁡′(z)=1[z>0]\displaystyle \operatorname{ReLU}'(z)=\mathbf{1}[z>0]

The sigmoid derivative peaks at 0.25, which is one reason deep stacks of sigmoids suffer from vanishing gradients.

Jacobian
Jij=∂fi∂xj\displaystyle J_{ij}=\frac{\partial f_i}{\partial x_j}J∈Rm×n for f:Rn→Rm\displaystyle J\in\mathbb{R}^{m\times n}\ \text{for}\ f:\mathbb{R}^n\to\mathbb{R}^m

The Jacobian is the best linear approximation of a vector-valued function near a point.

Hessian
Hij=∂2f∂xi ∂xj\displaystyle H_{ij}=\frac{\partial^2 f}{\partial x_i\,\partial x_j}H=H⊤ for smooth f\displaystyle H=H^{\top}\ \text{for smooth } f

The Hessian holds the second derivatives and describes the curvature of the loss.

Second-order Taylor expansion
f(x)≈f(a)+∇f(a)⊤Δ+12Δ⊤H(a) Δ\displaystyle f(x)\approx f(a)+\nabla f(a)^{\top}\Delta+\tfrac{1}{2}\Delta^{\top}H(a)\,\DeltaΔ=x−a\displaystyle \Delta=x-a

Near a point, a smooth function looks like a quadratic, which is the basis of Newton’s method.

Trapezoidal rule
∫abf(x) dx≈h2[f(a)+2∑i=1n−1f(xi)+f(b)]\displaystyle \int_a^b f(x)\,dx\approx\frac{h}{2}\left[f(a)+2\sum_{i=1}^{n-1}f(x_i)+f(b)\right]

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.

ROC AUC
AUC=∫01TPR d(FPR)=P(s+>s−)\displaystyle \text{AUC}=\int_0^1 \text{TPR}\,d(\text{FPR})=P(s_{+}>s_{-})

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
dθdt=−∇L(θ)\displaystyle \frac{d\theta}{dt}=-\nabla L(\theta)

Gradient descent is a sequence of small discrete steps along this field of negative gradients.

Second-derivative test
∇f(x∗)=0\displaystyle \nabla f(x^{*})=0H≻0⇒minimum\displaystyle H\succ 0\Rightarrow\text{minimum}H≺0⇒maximum\displaystyle H\prec 0\Rightarrow\text{maximum}H indefinite⇒saddle\displaystyle H\ \text{indefinite}\Rightarrow\text{saddle}

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
δL=∇aL⊙σ′(zL)\displaystyle \delta^{L}=\nabla_{a}L\odot\sigma'(z^{L})δl=((Wl+1)⊤δl+1)⊙σ′(zl)\displaystyle \delta^{l}=\left((W^{l+1})^{\top}\delta^{l+1}\right)\odot\sigma'(z^{l})

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
∂L∂Wl=δl(al−1)⊤\displaystyle \frac{\partial L}{\partial W^{l}}=\delta^{l}(a^{l-1})^{\top}∂L∂bl=δl\displaystyle \frac{\partial L}{\partial b^{l}}=\delta^{l}

Each weight gradient is the outer product of the layer’s error signal and the layer’s input.

Gradient descent update
θt+1=θt−η ∇L(θt)\displaystyle \theta_{t+1}=\theta_t-\eta\,\nabla L(\theta_t)

Each step moves the parameters a small distance, set by the learning rate, against the gradient.

Gradient clipping by global norm
g←g⋅min⁡ ⁣(1,c∥g∥2)\displaystyle g \leftarrow g\cdot\min\!\left(1,\frac{c}{\lVert g\rVert_2}\right)

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.

Optimization formulas for machine learning
Convex function
f(tx+(1−t)y)≤tf(x)+(1−t)f(y)\displaystyle f(tx+(1-t)y)\le t f(x)+(1-t)f(y)t∈[0,1]\displaystyle t\in[0,1]

A convex function lies below every chord, so any local minimum is a global minimum.

Second-order convexity test
f convex  ⟺  ∇2f(x)⪰0  ∀x\displaystyle f\ \text{convex} \iff \nabla^2 f(x)\succeq 0\ \ \forall x

A twice-differentiable function is convex exactly when its Hessian is positive semidefinite everywhere.

Safe step size for a smooth convex loss
η≤1L  where  ∥∇f(x)−∇f(y)∥≤L∥x−y∥\displaystyle \eta\le\frac{1}{L}\ \ \text{where}\ \ \lVert\nabla f(x)-\nabla f(y)\rVert\le L\lVert x-y\rVert

With a step no larger than one over the smoothness constant L, gradient descent never increases the loss.

Minibatch SGD
θt+1=θt−η 1B∑i∈B∇ℓ(θt;xi,yi)\displaystyle \theta_{t+1}=\theta_t-\eta\,\frac{1}{B}\sum_{i\in\mathcal{B}}\nabla \ell(\theta_t;x_i,y_i)

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.

Cosine annealing schedule
ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡πtT)\displaystyle \eta_t=\eta_{\min}+\tfrac{1}{2}(\eta_{\max}-\eta_{\min})\left(1+\cos\frac{\pi t}{T}\right)

The learning rate falls smoothly from its peak to its floor over T steps.

Linear warmup
ηt=ηmax⁡⋅tTw  for t≤Tw\displaystyle \eta_t=\eta_{\max}\cdot\frac{t}{T_w}\ \ \text{for}\ t\le T_w

Warmup ramps the learning rate up over a fixed number of warmup steps so that early updates do not destabilise training.

Momentum
vt+1=βvt+η ∇L(θt)\displaystyle v_{t+1}=\beta v_t+\eta\,\nabla L(\theta_t)θt+1=θt−vt+1\displaystyle \theta_{t+1}=\theta_t-v_{t+1}

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
vt+1=βvt+η ∇L(θt−βvt)\displaystyle v_{t+1}=\beta v_t+\eta\,\nabla L(\theta_t-\beta v_t)θt+1=θt−vt+1\displaystyle \theta_{t+1}=\theta_t-v_{t+1}

Nesterov evaluates the gradient at the look-ahead point, which damps overshooting.

AdaGrad
Gt=Gt−1+gt2\displaystyle G_t=G_{t-1}+g_t^2θt+1=θt−ηGt+ϵ gt\displaystyle \theta_{t+1}=\theta_t-\frac{\eta}{\sqrt{G_t}+\epsilon}\,g_t

Each parameter’s step shrinks with its total squared gradient so far, which can stall long runs.

RMSProp
vt=ρ vt−1+(1−ρ) gt2\displaystyle v_t=\rho\,v_{t-1}+(1-\rho)\,g_t^2θt+1=θt−ηvt+ϵ gt\displaystyle \theta_{t+1}=\theta_t-\frac{\eta}{\sqrt{v_t}+\epsilon}\,g_t

RMSProp replaces the running sum in AdaGrad with a moving average, so the step size stops shrinking forever.

Adam moment estimates
mt=β1mt−1+(1−β1) gt\displaystyle m_t=\beta_1 m_{t-1}+(1-\beta_1)\,g_tvt=β2vt−1+(1−β2) gt2\displaystyle v_t=\beta_2 v_{t-1}+(1-\beta_2)\,g_t^2

Adam keeps a moving average of the gradient and a moving average of its element-wise square.

Adam bias correction and update
m^t=mt1−β1t,  v^t=vt1−β2t\displaystyle \hat{m}_t=\frac{m_t}{1-\beta_1^t},\ \ \hat{v}_t=\frac{v_t}{1-\beta_2^t}θt=θt−1−η m^tv^t+ϵ\displaystyle \theta_t=\theta_{t-1}-\eta\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}

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
θt=θt−1−η(m^tv^t+ϵ+λ θt−1)\displaystyle \theta_t=\theta_{t-1}-\eta\left(\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}+\lambda\,\theta_{t-1}\right)

AdamW applies weight decay directly to the weights instead of adding it to the gradient that Adam rescales.

Sharpness-aware minimisation
min⁡θ max⁡∥ϵ∥≤ρL(θ+ϵ)\displaystyle \min_{\theta}\ \max_{\lVert\epsilon\rVert\le\rho} L(\theta+\epsilon)

SAM looks for weights whose whole neighbourhood has a low loss, which favours flat minima.

L2 regularisation
Ltotal=Ldata+λ∑iwi2\displaystyle L_{\text{total}}=L_{\text{data}}+\lambda\sum_i w_i^2w←(1−2ηλ) w−η ∇Ldata\displaystyle w\leftarrow(1-2\eta\lambda)\,w-\eta\,\nabla L_{\text{data}}

With this penalty every SGD step shrinks each weight by a constant factor, which is why it is also called weight decay.

L1 regularisation and soft thresholding
Ltotal=Ldata+λ∑i∣wi∣\displaystyle L_{\text{total}}=L_{\text{data}}+\lambda\sum_i\lvert w_i\rvertSτ(z)=sign⁡(z)max⁡(∣z∣−τ,0)\displaystyle S_\tau(z)=\operatorname{sign}(z)\max(\lvert z\rvert-\tau,0)

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
h~=m⊙h1−p\displaystyle \tilde{h}=\frac{m\odot h}{1-p}mi∼Bernoulli⁡(1−p)\displaystyle m_i\sim\operatorname{Bernoulli}(1-p)

During training each unit is dropped with probability p and the survivors are scaled up, so nothing changes at inference.

Bias-variance decomposition
E[(y−f^(x))2]=Bias2+Variance+σnoise2\displaystyle \mathbb{E}\big[(y-\hat{f}(x))^2\big]=\text{Bias}^2+\text{Variance}+\sigma^2_{\text{noise}}

Expected squared error splits into systematic error, sensitivity to the particular training set and noise that no model can remove.

Batch normalisation
x^i=xi−μBσB2+ϵ\displaystyle \hat{x}_i=\frac{x_i-\mu_B}{\sqrt{\sigma_B^2+\epsilon}}yi=γx^i+β\displaystyle y_i=\gamma\hat{x}_i+\beta

Batch norm standardises each feature over the batch and then lets the network learn a scale and a shift.

Layer normalisation
μ=1d∑j=1dxj,  σ2=1d∑j=1d(xj−μ)2\displaystyle \mu=\frac{1}{d}\sum_{j=1}^{d}x_j,\ \ \sigma^2=\frac{1}{d}\sum_{j=1}^{d}(x_j-\mu)^2y=γ x−μσ2+ϵ+β\displaystyle y=\gamma\,\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta

Layer norm uses the statistics of each example’s own features, so it does not depend on the batch size.

RMSNorm
y=x1d∑j=1dxj2+ϵ⊙g\displaystyle y=\frac{x}{\sqrt{\frac{1}{d}\sum_{j=1}^{d} x_j^2+\epsilon}}\odot g

RMSNorm drops the mean subtraction and the bias of layer norm, and it is the normalisation that many recent large language models use.

Newton’s method
θt+1=θt−H−1∇f(θt)\displaystyle \theta_{t+1}=\theta_t-H^{-1}\nabla f(\theta_t)xt+1=xt−f′(xt)f′′(xt) in one dimension\displaystyle x_{t+1}=x_t-\frac{f'(x_t)}{f''(x_t)}\ \text{in one dimension}

Newton’s method jumps to the minimum of the local quadratic and converges quadratically near a solution.

Lagrange condition for an equality constraint
L(x,λ)=f(x)+λ g(x)\displaystyle \mathcal{L}(x,\lambda)=f(x)+\lambda\,g(x)∇f(x)=−λ∇g(x),  g(x)=0\displaystyle \nabla f(x)=-\lambda\nabla g(x),\ \ g(x)=0

At a constrained optimum the gradient of the objective is parallel to the gradient of the constraint.

KKT conditions
∇f+∑iλi∇gi+∑jνj∇hj=0\displaystyle \nabla f+\sum_i\lambda_i\nabla g_i+\sum_j\nu_j\nabla h_j=0gi≤0,  hj=0\displaystyle g_i\le 0,\ \ h_j=0λi≥0\displaystyle \lambda_i\ge 0λigi=0\displaystyle \lambda_i g_i=0

KKT extends Lagrange multipliers to inequality constraints, and complementary slackness says an inactive constraint has a zero multiplier.

Hard-margin SVM and hinge loss
min⁡w,b 12∥w∥2  s.t.  yi(w⊤xi+b)≥1\displaystyle \min_{w,b}\ \tfrac{1}{2}\lVert w\rVert^2\ \ \text{s.t.}\ \ y_i(w^{\top}x_i+b)\ge 1ℓ=max⁡(0, 1−y f(x))\displaystyle \ell=\max(0,\,1-y\,f(x))

The SVM maximises the margin, and the hinge loss is its soft-margin penalty for labels of minus 1 and plus 1.

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.

Graph Theory formulas for machine learning
Adjacency matrix and degree
Aij=1 if (i,j)∈E\displaystyle A_{ij}=1\ \text{if}\ (i,j)\in Edi=∑jAij\displaystyle d_i=\sum_j A_{ij}∑idi=2∣E∣\displaystyle \sum_i d_i=2\lvert E\rvert

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
adjacency matrix O(V2)\displaystyle \text{adjacency matrix } O(V^2)adjacency list O(V+E)\displaystyle \text{adjacency list } O(V+E)

Sparse graphs should be stored as adjacency lists or sparse matrices.

Graph Laplacian
L=D−A\displaystyle L=D-A

The Laplacian is the diagonal degree matrix minus the adjacency matrix.

Laplacian quadratic form
x⊤Lx=∑(i,j)∈E(xi−xj)2 ≥0\displaystyle x^{\top}Lx=\sum_{(i,j)\in E}(x_i-x_j)^2\ \ge 0

The form measures how much a signal on the nodes changes across edges, so the Laplacian is positive semidefinite.

Laplacian spectrum
0=λ1≤λ2≤⋯≤λn\displaystyle 0=\lambda_1\le\lambda_2\le\dots\le\lambda_n#{i:λi=0}=# connected components\displaystyle \#\{i:\lambda_i=0\}=\#\,\text{connected components}

The second-smallest eigenvalue measures how well connected the graph is, and its eigenvector, the Fiedler vector, splits the graph in spectral clustering.

Normalised Laplacians
Lsym=I−D−1/2AD−1/2\displaystyle L_{\text{sym}}=I-D^{-1/2}AD^{-1/2}Lrw=I−D−1A\displaystyle L_{\text{rw}}=I-D^{-1}A

Normalising by degree stops high-degree nodes from dominating the spectrum.

Random-walk transition matrix
P=D−1A\displaystyle P=D^{-1}AP(Xk=j∣X0=i)=[Pk]ij\displaystyle P(X_k=j\mid X_0=i)=[P^k]_{ij}

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
πi=di2∣E∣\displaystyle \pi_i=\frac{d_i}{2\lvert E\rvert}

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
r=α P⊤r+1−αn1\displaystyle r=\alpha\,P^{\top}r+\frac{1-\alpha}{n}\mathbf{1}α≈0.85\displaystyle \alpha\approx 0.85

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
vˉ=∂L∂v=∑c ∈ children(v)cˉ ∂c∂v\displaystyle \bar{v}=\frac{\partial L}{\partial v}=\sum_{c\,\in\,\text{children}(v)}\bar{c}\,\frac{\partial c}{\partial v}

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
H(l+1)=σ ⁣(D~−1/2A~D~−1/2H(l)W(l))\displaystyle H^{(l+1)}=\sigma\!\left(\tilde{D}^{-1/2}\tilde{A}\tilde{D}^{-1/2}H^{(l)}W^{(l)}\right)A~=A+I\displaystyle \tilde{A}=A+I

Each node averages its own features and its neighbours’ features with symmetric degree normalisation and then applies a shared linear map.

Message passing
mv=AGG⁡u∈N(v) MSG⁡(hu,hv,euv)\displaystyle m_v=\operatorname{AGG}_{u\in\mathcal{N}(v)}\,\operatorname{MSG}(h_u,h_v,e_{uv})hv′=UPDATE⁡(hv,mv)\displaystyle h_v'=\operatorname{UPDATE}(h_v,m_v)

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.

Graph attention weights
αvu=softmax⁡u∈N(v)(evu)\displaystyle \alpha_{vu}=\operatorname{softmax}_{u\in\mathcal{N}(v)}(e_{vu})evu=LeakyReLU⁡(a⊤[Whv ∥ Whu])\displaystyle e_{vu}=\operatorname{LeakyReLU}\big(a^{\top}[Wh_v\,\Vert\,Wh_u]\big)

A graph attention network learns how much each neighbour should count instead of using fixed degree weights.

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.

Information Theory formulas for machine learning
Self-information
I(x)=−log⁡2P(x)\displaystyle I(x)=-\log_2 P(x)

Rare outcomes carry more information, measured in bits with log base 2 or in nats with the natural log.

Shannon entropy
H(X)=−∑xP(x)log⁡P(x)\displaystyle H(X)=-\sum_x P(x)\log P(x)0≤H(X)≤log⁡n\displaystyle 0\le H(X)\le\log n

Entropy is the average surprise, and it is largest for the uniform distribution over n outcomes.

Bits and nats
1 nat=1ln⁡2 bits≈1.443 bits\displaystyle 1\ \text{nat}=\frac{1}{\ln 2}\ \text{bits}\approx 1.443\ \text{bits}

The base of the log only rescales entropy, and deep learning frameworks use the natural log, so their losses are in nats.

Cross-entropy
H(P,Q)=−∑xP(x)log⁡Q(x)\displaystyle H(P,Q)=-\sum_x P(x)\log Q(x)H(P,Q)=H(P)+DKL(P ∥ Q)\displaystyle H(P,Q)=H(P)+D_{\mathrm{KL}}(P\,\Vert\,Q)

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
ℓ=−[ylog⁡y^+(1−y)log⁡(1−y^)]\displaystyle \ell=-\left[y\log\hat{y}+(1-y)\log(1-\hat{y})\right]

Binary cross-entropy is the negative log-likelihood of a 0 or 1 label given the predicted probability.

Categorical cross-entropy
ℓ=−∑c=1Cyclog⁡y^c=−log⁡y^true\displaystyle \ell=-\sum_{c=1}^{C}y_c\log\hat{y}_c=-\log\hat{y}_{\text{true}}

With one-hot labels the loss is minus the log of the probability given to the correct class.

Softmax in its stable form
softmax⁡(z)i=ezi−max⁡jzj∑kezk−max⁡jzj\displaystyle \operatorname{softmax}(z)_i=\frac{e^{z_i-\max_j z_j}}{\sum_k e^{z_k-\max_j z_j}}

Softmax turns logits into probabilities, and subtracting the largest logit changes nothing mathematically but prevents overflow.

Gradient of softmax with cross-entropy
∂ℓ∂zi=y^i−yi\displaystyle \frac{\partial \ell}{\partial z_i}=\hat{y}_i-y_i

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.

KL divergence
DKL(P ∥ Q)=∑xP(x)log⁡P(x)Q(x) ≥0\displaystyle D_{\mathrm{KL}}(P\,\Vert\,Q)=\sum_x P(x)\log\frac{P(x)}{Q(x)}\ \ge 0

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
DKL(N1 ∥ N2)=log⁡σ2σ1+σ12+(μ1−μ2)22σ22−12\displaystyle D_{\mathrm{KL}}(\mathcal{N}_1\,\Vert\,\mathcal{N}_2)=\log\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac{1}{2}Nk=N(μk,σk2)\displaystyle \mathcal{N}_k=\mathcal{N}(\mu_k,\sigma_k^2)

VAEs use this closed form, and against a standard normal it becomes minus one half times the sum of 1 + log σ² − μ² − σ².

Mutual information
I(X;Y)=∑x,yP(x,y)log⁡P(x,y)P(x)P(y)\displaystyle I(X;Y)=\sum_{x,y}P(x,y)\log\frac{P(x,y)}{P(x)P(y)}I(X;Y)=H(X)−H(X∣Y)\displaystyle I(X;Y)=H(X)-H(X\mid Y)

Mutual information is how much knowing Y reduces uncertainty about X, and it is zero exactly when the two are independent.

Mutual information from entropies
I(X;Y)=H(X)+H(Y)−H(X,Y)\displaystyle I(X;Y)=H(X)+H(Y)-H(X,Y)I(X;Y)=DKL(PXY ∥ PXPY)\displaystyle I(X;Y)=D_{\mathrm{KL}}\big(P_{XY}\,\Vert\,P_X P_Y\big)

Mutual information is symmetric, never negative and no larger than the smaller of the two entropies.

Information gain
IG(S,A)=H(S)−∑v∣Sv∣∣S∣H(Sv)\displaystyle \text{IG}(S,A)=H(S)-\sum_{v}\frac{\lvert S_v\rvert}{\lvert S\rvert}H(S_v)

A decision tree picks the split that most reduces the size-weighted entropy of the child nodes.

Gini impurity
G=1−∑kpk2\displaystyle G=1-\sum_k p_k^2

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.

Perplexity
PPL=exp⁡ ⁣(−1N∑i=1Nlog⁡p(wi∣w<i))\displaystyle \text{PPL}=\exp\!\left(-\frac{1}{N}\sum_{i=1}^{N}\log p(w_i\mid w_{<i})\right)PPL=2Hbits\displaystyle \text{PPL}=2^{H_{\text{bits}}}

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(P ∥ Q)=12DKL(P ∥ M)+12DKL(Q ∥ M)\displaystyle \text{JSD}(P\,\Vert\,Q)=\tfrac{1}{2}D_{\mathrm{KL}}(P\,\Vert\,M)+\tfrac{1}{2}D_{\mathrm{KL}}(Q\,\Vert\,M)M=12(P+Q)\displaystyle M=\tfrac{1}{2}(P+Q)

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.

Related guides