Excyst/Formulas

A chart of formulas, catalogued by field.

1,038 formulas, from probability distributions and statistics to linear algebra, optimisation, deep learning, signal processing and finance. Each has LaTeX to paste into your paper, its symbols defined, and a worked example that is checked in code.

1,038 formulas

Probability

Bernoulli distribution

P(X = x) = pˣ (1−p)¹⁻ˣ

where p = probability of success

Mean p, variance p(1−p).

Worked example: x = 1, p = 0.3 → 0.3 ✓ checked

See also: binomial distribution

LaTeX source
P(X=x) = p^{x}(1-p)^{1-x},\quad x\in\{0,1\}
Probability

beta distribution

f(x) = x^(α−1) (1−x)^(β−1) / B(α,β)

where α, β > 0; x ∈ [0,1]

Conjugate prior for the Bernoulli/binomial success probability.

Worked example: a = 2, b = 3, x = 0.5 → 1.5 ✓ checked

See also: Bernoulli distribution · binomial distribution · Bayes' theorem

LaTeX source
f(x) = \frac{x^{\alpha-1}(1-x)^{\beta-1}}{B(\alpha,\beta)},\quad B(\alpha,\beta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}
Probability

beta distribution: mean

E[X] = α/(α+β)

Verified against numerical integration of the density.

Worked example: al = 2, be = 5, x0 = 0.3 → 0.285714 ✓ checked

See also: beta distribution: variance

LaTeX source
\mathbb E[X]=\frac{\alpha}{\alpha+\beta}
Probability

beta distribution: variance

Var(X) = αβ / ((α+β)²(α+β+1))

Verified against numerical integration of the density.

Worked example: al = 2, be = 5, x0 = 0.3 → 0.0255102 ✓ checked

See also: beta distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}
Probability

beta-binomial distribution: probability mass

P(X = k) = C(n,k) B(k+α, n−k+β) / B(α, β)

A binomial whose success probability is itself Beta(α, β): overdispersed relative to the binomial.

Worked example: n = 10, al = 2, be = 3, x0 = 4 → 0.13986 ✓ checked

See also: beta-binomial distribution: mean

LaTeX source
P(X=k)=\binom nk\frac{B(k+\alpha,\,n-k+\beta)}{B(\alpha,\beta)}
Probability

beta-binomial distribution: variance

Var(X) = nαβ(α+β+n) / ((α+β)²(α+β+1))

Verified against summation of the mass function.

Worked example: n = 10, al = 2, be = 3, x0 = 4 → 6 ✓ checked

See also: beta-binomial distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{n\alpha\beta(\alpha+\beta+n)}{(\alpha+\beta)^2(\alpha+\beta+1)}
Probability

binomial distribution

P(X = k) = C(n,k) pᵏ (1−p)ⁿ⁻ᵏ

where n trials, k successes, p = success probability

Mean np, variance np(1−p).

Worked example: n = 10, k = 3, p = 0.5 → 0.117188 ✓ checked

See also: Bernoulli distribution · Poisson distribution

LaTeX source
P(X=k) = \binom{n}{k}p^{k}(1-p)^{n-k}
Probability

birth–death chain stationary distribution

πₖ = π₀ Π λ_{i−1}/μᵢ

Worked example: rho = 0.8, k = 3 → 0.1024 ✓ checked

See also: M/M/1 queue

LaTeX source
\pi_k=\pi_0\prod_{i=1}^{k}\frac{\lambda_{i-1}}{\mu_i}\quad\Rightarrow\quad M/M/1:\ \pi_k=(1-\rho)\rho^k
Probability

Brownian motion (Wiener process)

increments are independent N(0, t − s);  Cov(Wₛ, Wₜ) = min(s, t)

Continuous but nowhere differentiable; the limit of a scaled random walk.

Worked example: s = 2, t = 5 → [3, 2] ✓ checked

See also: random walk · geometric Brownian motion

LaTeX source
W_0=0,\quad W_t-W_s\sim\mathcal N(0,\,t-s),\quad \operatorname{Cov}(W_s,W_t)=\min(s,t)
Probability

categorical distribution

P(X = k) = pₖ

One draw from K classes; the output of a softmax classifier. Log-likelihood of one observation is log pₖ.

Worked example: p = [0.2, 0.5, 0.3], k = 1 → 0.5 ✓ checked

See also: softmax · multinomial distribution

LaTeX source
P(X=k)=p_k,\quad \sum_k p_k=1
Probability

Cauchy distribution: density

f(x) = 1 / (πγ [1 + ((x − x₀)/γ)²])

No mean and no variance (the integrals diverge): sample averages of Cauchy data do not settle down.

Worked example: loc = 0.5, g = 2, x0 = 1 → 0.149793 ✓ checked

See also: Cauchy distribution: cumulative distribution function

LaTeX source
f(x)=\frac{1}{\pi\gamma\Big[1+\big(\frac{x-x_0}{\gamma}\big)^2\Big]}
Probability

chain rule of probability

P(A₁,…,Aₙ) = Πᵢ P(Aᵢ | A₁,…,Aᵢ₋₁)

The basis of autoregressive language models.

Worked example: p = [0.5, 0.4, 0.2] → 0.04 ✓ checked

See also: Bayes' theorem

LaTeX source
P(A_1,\dots,A_n) = \prod_{i=1}^{n} P(A_i \mid A_1,\dots,A_{i-1})
Probability

change of variables for densities

f_Y(y) = f_X(g⁻¹(y))·|d g⁻¹/dy|

Example: Y = 2X for X ~ Exp(1) gives f_Y = ½ e^(−y/2).

Worked example: y = 2 → 0.18394 ✓ checked

See also: normalising flow change of variables

LaTeX source
Y=g(X)\ \Rightarrow\ f_Y(y)=f_X\big(g^{-1}(y)\big)\Big|\frac{d\,g^{-1}(y)}{dy}\Big|
Probability

Chebyshev's inequality

P(|X − μ| ≥ kσ) ≤ 1/k²

where k > 0

Needs only a finite variance.

Worked example: k = 2 → 0.25 ✓ checked

See also: Markov's inequality

LaTeX source
P\big(|X-\mu|\ge k\sigma\big)\le \frac{1}{k^2}
Probability

chi-square distribution: density

f(x) = x^(k/2−1) e^(−x/2) / (2^(k/2) Γ(k/2))

The sum of k squared independent standard normals. Gamma with shape k/2 and scale 2.

Worked example: k = 4, x0 = 3 → 0.167348 ✓ checked

See also: chi-square distribution: mean

LaTeX source
f(x)=\frac{x^{k/2-1}e^{-x/2}}{2^{k/2}\Gamma(k/2)}
Probability

compound Poisson process

E S = λt·E[Y];  Var S = λt·E[Y²]

Insurance claims and call-centre loads.

Worked example: lam = 3, t = 2, EY = 10, EY2 = 150 → [60, 900] ✓ checked

See also: Wald's identity

LaTeX source
S_t=\sum_{i=1}^{N_t}Y_i:\quad \mathbb E S_t=\lambda t\,\mathbb E Y,\quad \operatorname{Var}S_t=\lambda t\,\mathbb E[Y^2]
Probability

covariance

Cov(X,Y) = E[XY] − E[X]E[Y]

Zero covariance does not imply independence. Cov(X,X) = Var(X).

Worked example: x = [1, 2, 3, 4], y = [2, 4, 5, 9] → 2.75 ✓ checked

See also: Pearson correlation · variance and standard deviation

LaTeX source
\operatorname{Cov}(X,Y) = \mathbb{E}[XY] - \mathbb{E}[X]\,\mathbb{E}[Y]
Probability

cumulant generating function

K(t) = ln M(t);  κ₁ = mean, κ₂ = variance

Cumulants of independent sums add. For a normal, all cumulants above the second vanish.

Worked example: mu = 1, s = 2 → [1, 4] ✓ checked

See also: moments from the moment generating function

LaTeX source
K_X(t)=\ln M_X(t),\quad \kappa_1=\mathbb E[X],\ \kappa_2=\operatorname{Var}(X)
Probability

density of an order statistic

f₍ₖ₎ = n!/((k−1)!(n−k)!) F^(k−1) (1 − F)^(n−k) f

Worked example: n = 5, k = 3, x = 0.5 → 1.875 ✓ checked

See also: order statistics of uniforms

LaTeX source
f_{(k)}(x)=\frac{n!}{(k-1)!\,(n-k)!}F(x)^{k-1}\big(1-F(x)\big)^{n-k}f(x)
Probability

Dirichlet distribution

f(p) = Γ(α₀)/ΠΓ(αₖ) · Π pₖ^(αₖ−1)

Mean αₖ/α₀. The conjugate prior of the categorical and multinomial; the multivariate beta.

Worked example: al = [2, 3, 4], p = [0.2, 0.3, 0.5] → 7.56 ✓ checked

See also: beta distribution: mean · multinomial distribution

LaTeX source
f(\mathbf p)=\frac{\Gamma(\alpha_0)}{\prod_k\Gamma(\alpha_k)}\prod_k p_k^{\alpha_k-1},\quad \alpha_0=\sum_k\alpha_k
Probability

expected value

E[X] = Σₓ x·p(x)        (continuous: ∫ x f(x) dx)

where p(x) = probability mass, f(x) = density

Linear: E[aX + bY] = aE[X] + bE[Y], always, even when X and Y are dependent.

Worked example: x = [1, 2, 3], p = [0.2, 0.5, 0.3] → 2.1 ✓ checked

See also: variance and standard deviation · law of iterated expectation

LaTeX source
\mathbb{E}[X] = \sum_x x\,p(x) \qquad \mathbb{E}[X] = \int x\,f(x)\,dx
Probability

exponential distribution

f(x) = λ e^(−λx)        F(x) = 1 − e^(−λx)

where λ = rate; mean 1/λ

Memoryless: P(X > s+t | X > s) = P(X > t).

Worked example: lam = 2, x = 0.5 → 0.735759 ✓ checked

See also: Poisson distribution

LaTeX source
f(x) = \lambda e^{-\lambda x},\ x\ge 0 \qquad F(x) = 1-e^{-\lambda x}
Probability

F distribution distribution: density

f(x) = √( (d₁x)^d₁ d₂^d₂ / (d₁x+d₂)^(d₁+d₂) ) / (x B(d₁/2, d₂/2))

The ratio of two scaled chi-squares; the null distribution of the ANOVA F statistic.

Worked example: d1 = 5, d2 = 10, x0 = 1.5 → 0.286459 ✓ checked

See also: F distribution distribution: mean

LaTeX source
f(x)=\frac{1}{x\,B(d_1/2,d_2/2)}\sqrt{\frac{(d_1x)^{d_1}\,d_2^{d_2}}{(d_1x+d_2)^{d_1+d_2}}}
Probability

F distribution distribution: variance

Var(X) = 2d₂²(d₁+d₂−2) / (d₁(d₂−2)²(d₂−4))

Verified against numerical integration of the density.

Worked example: d1 = 5, d2 = 10, x0 = 1.5 → 1.35416 ✓ checked

See also: F distribution distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{2d_2^2(d_1+d_2-2)}{d_1(d_2-2)^2(d_2-4)}\ \ (d_2>4)
Probability

gambler's-ruin hitting time

E[T] = i(N − i)

Worked example: i = 10, N = 30 → 200 ✓ checked

See also: gambler's ruin

LaTeX source
\mathbb E[T]=i(N-i)\quad\text{for a symmetric walk on }\{0,\dots,N\}\text{ started at }i
Probability

gamma distribution: cumulative distribution function

F(x) = 1 − e^(−x/θ) Σ_{j<k} (x/θ)ʲ/j!   (integer k, the Erlang case)

Verified against numerical integration of the density up to x.

Worked example: k = 3, th = 2, x0 = 4 → 0.323324 ✓ checked

See also: gamma distribution: density

LaTeX source
F(x)=1-e^{-x/\theta}\sum_{j=0}^{k-1}\frac{(x/\theta)^j}{j!}\ \ (k\in\mathbb N)
Probability

gamma distribution: density

f(x) = x^(k−1) e^(−x/θ) / (Γ(k) θᵏ)

Shape k, scale θ. The sum of k independent exponentials (mean θ) is gamma. Some texts use rate β = 1/θ.

Worked example: k = 3, th = 2, x0 = 4 → 0.135335 ✓ checked

See also: gamma distribution: mean

LaTeX source
f(x)=\frac{x^{k-1}e^{-x/\theta}}{\Gamma(k)\,\theta^{k}}
Probability

gamma distribution: mean

E[X] = kθ

Verified against numerical integration of the density.

Worked example: k = 3, th = 2, x0 = 4 → 6 ✓ checked

See also: gamma distribution: variance

LaTeX source
\mathbb E[X]=k\theta
Probability

gamma distribution: variance

Var(X) = kθ²

Verified against numerical integration of the density.

Worked example: k = 3, th = 2, x0 = 4 → 12 ✓ checked

See also: gamma distribution: mean

LaTeX source
\operatorname{Var}(X)=k\theta^2
Probability

geometric Brownian motion

S_t = S₀ exp((μ − σ²/2)t + σW_t);  E S_t = S₀ e^(μt)

The Black–Scholes model of a stock price.

Worked example: S0 = 100, mu = 0.05, s = 0.2, t = 1 → [105.127, 451.029] ✓ checked

See also: Itô's lemma · Black–Scholes option price

LaTeX source
dS=\mu S\,dt+\sigma S\,dW,\quad S_t=S_0\exp\!\big((\mu-\tfrac12\sigma^2)t+\sigma W_t\big),\quad \mathbb E S_t=S_0e^{\mu t}
Probability

Hoeffding's inequality

P( X̄ − E[X̄] ≥ t ) ≤ exp( −2n t² / (b−a)² )

where Xᵢ independent, in [a, b]; n samples

Gives finite-sample confidence bounds for bounded variables.

Worked example: n = 100, t = 0.1, r = 1 → 0.135335 ✓ checked

See also: Chebyshev's inequality

LaTeX source
P\big(\bar X-\mathbb{E}\bar X\ge t\big)\le \exp\!\left(-\frac{2nt^2}{(b-a)^2}\right)
Probability

hypergeometric distribution: probability mass

P(X = k) = C(K,k) C(N−K, n−k) / C(N, n)

Successes when drawing n items without replacement from N containing K successes. The factor (N−n)/(N−1) is the finite-population correction.

Worked example: N = 50, K = 10, n = 8, x0 = 2 → 0.321725 ✓ checked

See also: hypergeometric distribution: mean

LaTeX source
P(X=k)=\frac{\binom Kk\binom{N-K}{n-k}}{\binom Nn}
Probability

hypergeometric distribution: variance

Var(X) = n (K/N)(1 − K/N)(N − n)/(N − 1)

Verified against summation of the mass function.

Worked example: N = 50, K = 10, n = 8, x0 = 2 → 1.09714 ✓ checked

See also: hypergeometric distribution: mean

LaTeX source
\operatorname{Var}(X)=n\frac KN\Big(1-\frac KN\Big)\frac{N-n}{N-1}
Probability

inverse gamma distribution: density

f(x) = βᵅ/Γ(α) · x^(−α−1) e^(−β/x)

Conjugate prior for the variance of a normal.

Worked example: al = 4, be = 3, x0 = 1 → 0.672125 ✓ checked

See also: inverse gamma distribution: mean

LaTeX source
f(x)=\frac{\beta^{\alpha}}{\Gamma(\alpha)}x^{-\alpha-1}e^{-\beta/x}
Probability

inverse gamma distribution: variance

Var(X) = β² / ((α−1)²(α−2))

Verified against numerical integration of the density.

Worked example: al = 4, be = 3, x0 = 1 → 0.5 ✓ checked

See also: inverse gamma distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{\beta^2}{(\alpha-1)^2(\alpha-2)}\ \ (\alpha>2)
Probability

Itô's lemma

df = (f_t + μf_x + ½σ²f_xx)dt + σf_x dW

The extra ½σ²f_xx term is why ln S has drift μ − σ²/2 for geometric Brownian motion.

Worked example: mu = 0.05, s = 0.2 → 0.03 ✓ checked

See also: geometric Brownian motion

LaTeX source
df(t,X)=\Big(f_t+\mu f_x+\tfrac12\sigma^2f_{xx}\Big)dt+\sigma f_x\,dW
Probability

Jensen's inequality

f(E[X]) ≤ E[f(X)]  for convex f

Reverses for concave f. Gives KL ≥ 0.

Worked example: x = [1, 3], p = [0.5, 0.5] → 1 ✓ checked

See also: Kullback–Leibler divergence

LaTeX source
f(\mathbb{E}[X])\le \mathbb{E}[f(X)]\quad (f\ \text{convex})
Probability

joint, marginal and conditional densities

marginalise, divide, and independence factorises

Worked example: pxy = 0.12, py = 0.4 → 0.3 ✓ checked

See also: Bayes' theorem

LaTeX source
f_X(x)=\int f_{X,Y}(x,y)\,dy,\qquad f_{X\mid Y}(x\mid y)=\frac{f_{X,Y}(x,y)}{f_Y(y)},\qquad X\perp Y\iff f_{X,Y}=f_Xf_Y
Probability

law of total probability

P(B) = Σᵢ P(B|Aᵢ)·P(Aᵢ)

where A₁…Aₙ partition the sample space

Worked example: pba = [0.9, 0.05], pa = [0.01, 0.99] → 0.0585 ✓ checked

See also: Bayes' theorem

LaTeX source
P(B) = \sum_i P(B\mid A_i)\,P(A_i)
Probability

law of total variance

Var(Y) = E[Var(Y|X)] + Var(E[Y|X])

Within-group variance plus between-group variance.

Worked example: v = [1, 4], m = [0, 2], p = [0.5, 0.5] → 3.5 ✓ checked

See also: variance and standard deviation

LaTeX source
\operatorname{Var}(Y) = \mathbb{E}[\operatorname{Var}(Y\mid X)] + \operatorname{Var}(\mathbb{E}[Y\mid X])
Probability

log-normal distribution: density

f(x) = exp(−(ln x − μ)²/2σ²) / (xσ√2π)

X is log-normal if ln X is normal. Models positive, multiplicative quantities.

Worked example: mu = 0, s = 0.5, x0 = 1.5 → 0.38287 ✓ checked

See also: log-normal distribution: mean

LaTeX source
f(x)=\frac{1}{x\sigma\sqrt{2\pi}}\exp\!\Big(-\frac{(\ln x-\mu)^2}{2\sigma^2}\Big),\ x>0
Probability

log-normal distribution: variance

Var(X) = (e^σ² − 1) e^(2μ+σ²)

Verified against numerical integration of the density.

Worked example: mu = 0, s = 0.5, x0 = 1.5 → 0.364696 ✓ checked

See also: log-normal distribution: mean

LaTeX source
\operatorname{Var}(X)=\big(e^{\sigma^2}-1\big)e^{2\mu+\sigma^2}
Probability

logistic distribution: density

f(x) = e^(−z) / (s(1 + e^(−z))²),  z = (x−μ)/s

Its cdf is the sigmoid, which is why logistic regression uses it.

Worked example: mu = 1, s = 2, x0 = 0.5 → 0.123067 ✓ checked

See also: logistic distribution: mean

LaTeX source
f(x)=\frac{e^{-(x-\mu)/s}}{s\big(1+e^{-(x-\mu)/s}\big)^2}
Probability

logistic distribution: variance

Var(X) = s²π²/3

Verified against numerical integration of the density.

Worked example: mu = 1, s = 2, x0 = 0.5 → 13.1595 ✓ checked

See also: logistic distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{s^2\pi^2}{3}
Probability

Lyapunov's moment inequality

(E|X|ʳ)^(1/r) ≤ (E|X|ˢ)^(1/s)

Higher moments dominate: E|X| ≤ √(E X²).

Worked example: x = [1, 3], p = [0.5, 0.5] → [2, 2.23607] ✓ checked

See also: Jensen's inequality

LaTeX source
\big(\mathbb E|X|^r\big)^{1/r}\le\big(\mathbb E|X|^s\big)^{1/s}\quad(0<r<s)
Probability

multivariate normal density

f(x) = (2π)^(−k/2) |Σ|^(−1/2) exp( −½ (x−μ)ᵀ Σ⁻¹ (x−μ) )

where k = dimension, μ = mean vector, Σ = covariance matrix (positive definite)

Worked example: x = [0, 0], mu = [0, 0], S = [[1, 0], [0, 1]] → 0.159155 ✓ checked

See also: normal (Gaussian) density

LaTeX source
f(\mathbf{x}) = (2\pi)^{-k/2}\,|\Sigma|^{-1/2}\exp\!\left(-\tfrac12(\mathbf{x}-\boldsymbol\mu)^{\top}\Sigma^{-1}(\mathbf{x}-\boldsymbol\mu)\right)
Probability

multivariate normal: conditional distribution

μ₁|₂ = μ₁ + Σ₁₂ Σ₂₂⁻¹ (x₂ − μ₂);  Σ₁|₂ = Σ₁₁ − Σ₁₂ Σ₂₂⁻¹ Σ₂₁

Conditioning a Gaussian gives a Gaussian whose covariance does not depend on the observed value. The basis of Gaussian processes and Kalman filters.

Worked example: S = [[1, 0.8], [0.8, 1]], x2 = 1 → [0.8, 0.36] ✓ checked

See also: multivariate normal density · Gaussian process posterior

LaTeX source
\boldsymbol\mu_{1|2}=\boldsymbol\mu_1+\Sigma_{12}\Sigma_{22}^{-1}(\mathbf x_2-\boldsymbol\mu_2),\quad \Sigma_{1|2}=\Sigma_{11}-\Sigma_{12}\Sigma_{22}^{-1}\Sigma_{21}
Probability

multivariate normal: marginal and linear maps

x ~ N(μ, Σ)  ⇒  Ax + b ~ N(Aμ + b, AΣAᵀ)

Marginals are sub-vectors of μ and sub-blocks of Σ.

Worked example: A = [[1, 1]], S = [[1, 0.5], [0.5, 2]] → 4 ✓ checked

See also: multivariate normal: conditional distribution

LaTeX source
\mathbf x\sim\mathcal N(\boldsymbol\mu,\Sigma)\ \Rightarrow\ A\mathbf x+\mathbf b\sim\mathcal N\big(A\boldsymbol\mu+\mathbf b,\ A\Sigma A^{\top}\big)
Probability

normal approximation of the binomial

P(X ≤ k) ≈ Φ((k + ½ − np)/√(np(1−p)))

The ½ is the continuity correction. Use when np and n(1−p) are both at least 10.

Worked example: n = 100, p = 0.5, k = 55 → 0.864334 ✓ checked

See also: binomial distribution: mean · normal cumulative distribution

LaTeX source
\operatorname{Bin}(n,p)\approx\mathcal N\big(np,\ np(1-p)\big),\qquad P(X\le k)\approx\Phi\!\Big(\frac{k+\frac12-np}{\sqrt{np(1-p)}}\Big)
Probability

normal cumulative distribution

Φ(x) = ½ [ 1 + erf(x/√2) ]

Φ(1.96) ≈ 0.975, the source of the 95% interval.

Worked example: x = 1.96 → 0.975002 ✓ checked

See also: normal (Gaussian) density · z-score

LaTeX source
\Phi(x) = \tfrac12\left[1+\operatorname{erf}\!\left(\frac{x}{\sqrt2}\right)\right]
Probability

normal distribution: variance

Var(X) = σ²

Verified against numerical integration of the density.

Worked example: mu = 1, s = 2, x0 = 0 → 4 ✓ checked

See also: normal distribution: mean

LaTeX source
\operatorname{Var}(X)=\sigma^2
Probability

Ornstein–Uhlenbeck process

mean-reverting;  stationary variance σ²/(2θ)

The continuous-time AR(1); also the forward process of the variance-preserving diffusion model.

Worked example: theta = 0.5, mu = 1, x0 = 3, t = 2, s = 0.4 → [1.73576, 0.16] ✓ checked

See also: AR(1) process · Brownian motion (Wiener process)

LaTeX source
dX=\theta(\mu-X)\,dt+\sigma\,dW,\quad \mathbb E X_t=\mu+(x_0-\mu)e^{-\theta t},\quad \operatorname{Var}(X_\infty)=\frac{\sigma^2}{2\theta}
Probability

Pareto (type I) distribution: variance

Var(X) = x_m² α / ((α−1)²(α−2))

Verified against numerical integration of the density.

Worked example: xm = 1, al = 4, x0 = 2 → 0.222232 ✓ checked

See also: Pareto (type I) distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{x_m^2\alpha}{(\alpha-1)^2(\alpha-2)}\ \ (\alpha>2)
Probability

Poisson distribution

P(X = k) = λᵏ e^(−λ) / k!

where λ = rate (the mean and the variance)

Limit of Binomial(n, λ/n) as n → ∞.

Worked example: lam = 2, k = 3 → 0.180447 ✓ checked

See also: binomial distribution · exponential distribution

LaTeX source
P(X=k) = \frac{\lambda^{k}e^{-\lambda}}{k!}
Probability

Poisson process

N_t ~ Poisson(λt);  waiting times ~ Exp(λ)

Worked example: lam = 3, t = 2, k = 4 → 0.133853 ✓ checked

See also: Poisson distribution · exponential distribution

LaTeX source
N_t\sim\mathrm{Poisson}(\lambda t),\qquad T_i\sim\mathrm{Exp}(\lambda)\ \text{(inter-arrival times)},\qquad \mathbb E[T_i]=\frac1\lambda
Probability

Rayleigh distribution: density

f(x) = (x/σ²) e^(−x²/2σ²)

The length of a 2-D vector with independent N(0, σ²) components.

Worked example: s = 2, x0 = 1.5 → 0.283065 ✓ checked

See also: Rayleigh distribution: mean

LaTeX source
f(x)=\frac{x}{\sigma^2}e^{-x^2/2\sigma^2},\ x\ge0
Probability

Rayleigh distribution: mean

E[X] = σ√(π/2)

Verified against numerical integration of the density.

Worked example: s = 2, x0 = 1.5 → 2.50663 ✓ checked

See also: Rayleigh distribution: variance

LaTeX source
\mathbb E[X]=\sigma\sqrt{\tfrac\pi2}
Probability

Rayleigh distribution: variance

Var(X) = (4 − π)σ²/2

Verified against numerical integration of the density.

Worked example: s = 2, x0 = 1.5 → 1.71681 ✓ checked

See also: Rayleigh distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{4-\pi}{2}\sigma^2
Probability

renewal theorem

renewals per unit time → 1/μ

where μ = mean inter-renewal time

Worked example: mu = 4, t = 100 → 25 ✓ checked

See also: Poisson process

LaTeX source
\frac{N(t)}t\to\frac1\mu\ \text{a.s.},\qquad \mathbb E[N(t)]\approx\frac t\mu
Probability

sampling distributions from normal data

x̄ ~ N(μ, σ²/n);  (n − 1)s²/σ² ~ χ²ₙ₋₁;  t and F ratios

Worked example: n = 10, s2 = 4 → [0.4, 18] ✓ checked

See also: chi-square distribution: mean · Student's t distribution: density · F distribution distribution: density

LaTeX source
\bar X\sim\mathcal N\Big(\mu,\frac{\sigma^2}n\Big),\quad \frac{(n-1)s^2}{\sigma^2}\sim\chi^2_{n-1},\quad \frac{\bar X-\mu}{s/\sqrt n}\sim t_{n-1},\quad \frac{s_1^2/\sigma_1^2}{s_2^2/\sigma_2^2}\sim F_{n_1-1,n_2-1}
Probability

spectral gap and mixing time

t_mix ≤ (1/γ) ln(1/(ε π_min))

where γ = spectral gap

A larger gap means faster convergence to the stationary distribution.

Worked example: lam2 = 0.4, eps = 0.01, pimin = 0.166667 → 10.6615 ✓ checked

See also: stationary distribution of a Markov chain · Gelman–Rubin R̂

LaTeX source
t_{\text{mix}}(\varepsilon)\le\frac1{\gamma}\ln\frac1{\varepsilon\,\pi_{\min}},\qquad \gamma=1-\lambda_2
Probability

Student's t distribution: density

f(x) = Γ((ν+1)/2) / (√(νπ) Γ(ν/2)) · (1 + x²/ν)^(−(ν+1)/2)

Heavier tails than the normal; tends to the normal as ν grows. Used for small-sample inference.

Worked example: nu = 5, x0 = 1.2 → 0.177659 ✓ checked

See also: Student's t distribution: mean

LaTeX source
f(x)=\frac{\Gamma\!\big(\frac{\nu+1}{2}\big)}{\sqrt{\nu\pi}\,\Gamma\!\big(\frac\nu2\big)}\Big(1+\frac{x^2}{\nu}\Big)^{-\frac{\nu+1}{2}}
Probability

Student's t distribution: variance

Var(X) = ν/(ν−2)  (ν > 2)

Verified against numerical integration of the density.

Worked example: nu = 5, x0 = 1.2 → 1.66667 ✓ checked

See also: Student's t distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{\nu}{\nu-2}\ \ (\nu>2)
Probability

sum of independent normals

Σ aᵢXᵢ ~ N(Σ aᵢμᵢ, Σ aᵢ²σᵢ²)

Variances add, standard deviations do not.

Worked example: a = [1, 2], mu = [1, 3], v = [4, 1] → [7, 8] ✓ checked

See also: normal (Gaussian) density

LaTeX source
X_i\sim\mathcal N(\mu_i,\sigma_i^2)\ \Rightarrow\ \sum_i a_iX_i\sim\mathcal N\Big(\sum_i a_i\mu_i,\ \sum_i a_i^2\sigma_i^2\Big)
Probability

triangular distribution: density

f(x) = 2(x−a)/((b−a)(c−a)) for x < c;  2(b−x)/((b−a)(b−c)) for x ≥ c

Min a, max b, mode c: a quick model when only those three are known.

Worked example: a = 0, b = 4, c = 1, x0 = 2 → 0.333333 ✓ checked

See also: triangular distribution: mean

LaTeX source
f(x)=\begin{cases}\frac{2(x-a)}{(b-a)(c-a)}&a\le x<c\\[2pt]\frac{2(b-x)}{(b-a)(b-c)}&c\le x\le b\end{cases}
Probability

triangular distribution: variance

Var(X) = (a²+b²+c²−ab−ac−bc)/18

Verified against numerical integration of the density.

Worked example: a = 0, b = 4, c = 1, x0 = 2 → 0.722222 ✓ checked

See also: triangular distribution: mean

LaTeX source
\operatorname{Var}(X)=\frac{a^2+b^2+c^2-ab-ac-bc}{18}
Probability

variance and standard deviation

Var(X) = E[X²] − E[X]²        σ = √Var(X)

where σ = standard deviation

Var(aX + b) = a² Var(X). Variances of independent variables add.

Worked example: x = [1, 2, 3], p = [0.2, 0.5, 0.3] → 0.49 ✓ checked

See also: expected value · covariance · sample variance (Bessel's correction)

LaTeX source
\operatorname{Var}(X) = \mathbb{E}[X^2] - \mathbb{E}[X]^2 \qquad \sigma = \sqrt{\operatorname{Var}(X)}
Probability

variance of a sum

Var(aX + bY) = a²Var X + b²Var Y + 2ab Cov(X, Y)

Worked example: a = 2, b = -1, vx = 4, vy = 9, c = 3 → 13 ✓ checked

See also: covariance · variance and standard deviation

LaTeX source
\operatorname{Var}(aX+bY)=a^2\operatorname{Var}X+b^2\operatorname{Var}Y+2ab\operatorname{Cov}(X,Y),\qquad \operatorname{Var}\Big(\sum_iX_i\Big)=\sum_i\operatorname{Var}X_i\ \text{(independent)}
Probability

Wald's identity

E[S_N] = E[N]·E[X]

where N a stopping time

Worked example: EN = 8, EX = 2.5 → 20 ✓ checked

See also: compound Poisson process

LaTeX source
\mathbb E\Big[\sum_{i=1}^{N}X_i\Big]=\mathbb E[N]\,\mathbb E[X]
Probability

Weibull distribution: density

f(x) = (k/λ)(x/λ)^(k−1) e^(−(x/λ)ᵏ)

Failure times; k < 1 decreasing hazard, k > 1 increasing hazard, k = 1 exponential.

Worked example: k = 1.5, lam = 2, x0 = 1.5 → 0.339242 ✓ checked

See also: Weibull distribution: mean

LaTeX source
f(x)=\frac k\lambda\Big(\frac x\lambda\Big)^{k-1}e^{-(x/\lambda)^k}
Probability

Weibull distribution: mean

E[X] = λ Γ(1 + 1/k)

Verified against numerical integration of the density.

Worked example: k = 1.5, lam = 2, x0 = 1.5 → 1.80549 ✓ checked

See also: Weibull distribution: variance

LaTeX source
\mathbb E[X]=\lambda\,\Gamma\!\big(1+\tfrac1k\big)
Probability

Weibull distribution: variance

Var(X) = λ²[Γ(1 + 2/k) − Γ(1 + 1/k)²]

Verified against numerical integration of the density.

Worked example: k = 1.5, lam = 2, x0 = 1.5 → 1.50276 ✓ checked

See also: Weibull distribution: mean

LaTeX source
\operatorname{Var}(X)=\lambda^2\Big[\Gamma\!\big(1+\tfrac2k\big)-\Gamma\!\big(1+\tfrac1k\big)^2\Big]
Probability

Zipf's law

frequency of the k-th most common item ∝ 1/k^s

Word frequencies follow it with s ≈ 1.

Worked example: N = 1000, s = 1, k = 1 → 0.133592 ✓ checked

See also: Pareto (type I) distribution: density

LaTeX source
f(k)=\frac{k^{-s}}{\sum_{n=1}^{N}n^{-s}},\qquad f(k)\propto\frac1{k^{s}}
Statistics

additive (Laplace) smoothing

p̂ₖ = (cₖ + α)/(N + αK)

where α = 1 is Laplace's rule of succession

Avoids zero probabilities for unseen events (naive Bayes, n-gram models).

Worked example: c = 0, a = 1, N = 10, K = 5 → 0.0666667 ✓ checked

See also: Dirichlet–multinomial conjugate update

LaTeX source
\hat p_k=\frac{c_k+\alpha}{N+\alpha K}
Statistics

Akaike information criterion

AIC = 2k − 2 ln L̂

where k = parameters, L̂ = maximised likelihood

Lower is better.

Worked example: k = 3, lnl = -100 → 206 ✓ checked

See also: Bayesian information criterion

LaTeX source
\mathrm{AIC}=2k-2\ln\hat L
Statistics

AR(1) process

xₜ = φxₜ₋₁ + εₜ;  Var = σ²/(1 − φ²);  ρₖ = φᵏ

Stationary only if |φ| < 1; φ = 1 is a random walk.

Worked example: phi = 0.8, s2 = 1, k = 3 → [2.77778, 0.512] ✓ checked

See also: random walk · Yule–Walker equations (AR(2))

LaTeX source
x_t=\phi x_{t-1}+\varepsilon_t,\quad \operatorname{Var}(x_t)=\frac{\sigma^2}{1-\phi^2},\quad \rho_k=\phi^k\quad(|\phi|<1)
Statistics

ARCH(1) and GARCH(1,1) variance

σₜ² = ω + αεₜ₋₁² + βσₜ₋₁²

where β = 0 gives ARCH(1)

Stationary variance ω/(1 − α − β).

Worked example: w = 0.1, a = 0.1, be = 0.8, e = 2, s2 = 1 → [1.3, 1] ✓ checked

See also: EWMA volatility (RiskMetrics)

LaTeX source
\sigma_t^2=\omega+\alpha\varepsilon_{t-1}^2+\beta\sigma_{t-1}^2
Statistics

autocorrelation function

ρ̂ₖ = Σ (xₜ − x̄)(xₜ₊ₖ − x̄) / Σ (xₜ − x̄)²

where k = lag

Worked example: x = [1, 2, 3, 4, 5], k = 1 → 0.4 ✓ checked

See also: Durbin–Watson statistic · Ljung–Box statistic

LaTeX source
\hat\rho_k=\frac{\sum_{t=1}^{n-k}(x_t-\bar x)(x_{t+k}-\bar x)}{\sum_{t=1}^{n}(x_t-\bar x)^2}
Statistics

average treatment effect

ATE = E[Y(1) − Y(0)];  difference in means when T is randomised

Without randomisation, confounding makes the difference in means biased.

Worked example: t = [10, 12, 14], c = [8, 9, 10] → 3 ✓ checked

See also: inverse-propensity weighting · backdoor adjustment

LaTeX source
\mathrm{ATE}=\mathbb E[Y(1)-Y(0)]=\mathbb E[Y\mid T=1]-\mathbb E[Y\mid T=0]\ \ (\text{randomised})
Statistics

backdoor adjustment

P(y | do(x)) = Σ_z P(y | x, z) P(z)

where Z blocks all backdoor paths from X to Y

Pearl's adjustment formula; conditioning on a collider or mediator would break it.

Worked example: pyxz = [0.8, 0.4], pz = [0.3, 0.7] → 0.52 ✓ checked

See also: average treatment effect · Bayes' theorem

LaTeX source
P\big(y\mid\operatorname{do}(x)\big)=\sum_zP(y\mid x,z)\,P(z)
Statistics

Bayes factor and posterior odds

posterior odds = Bayes factor × prior odds

Above 10 is usually called strong evidence for H₁.

Worked example: bf = 6, prior = 0.5 → 6 ✓ checked

See also: Bayes' theorem

LaTeX source
\mathrm{BF}_{10}=\frac{p(D\mid H_1)}{p(D\mid H_0)},\qquad \frac{P(H_1\mid D)}{P(H_0\mid D)}=\mathrm{BF}_{10}\cdot\frac{P(H_1)}{P(H_0)}
Statistics

Bayesian A/B test

compare posterior samples of each arm's conversion rate

Worked example: sa = 100, fa = 900, sb = 120, fb = 880 → [0.100798, 0.120758] ✓ checked

See also: Beta–binomial conjugate update

LaTeX source
p_A\sim\mathrm{Beta}(1+s_A,1+f_A),\quad P(p_B>p_A)\approx\frac1M\sum_m\mathbf 1\big[p_B^{(m)}>p_A^{(m)}\big]
Statistics

Bayesian information criterion

BIC = k ln n − 2 ln L̂

where n = number of observations

Penalises complexity more than AIC when n > 7.

Worked example: k = 3, n = 100, lnl = -100 → 213.816 ✓ checked

See also: Akaike information criterion

LaTeX source
\mathrm{BIC}=k\ln n-2\ln\hat L
Statistics

Benjamini–Hochberg (false discovery rate)

k = max{i : p₍ᵢ₎ ≤ (i/m)q}; reject the k smallest

where q = target false discovery rate

Controls the expected share of false discoveries, not the chance of any.

Worked example: p = [0.001, 0.012, 0.03, 0.2], q = 0.05 → 3 ✓ checked

See also: Holm–Bonferroni procedure · Bonferroni correction

LaTeX source
\text{reject all } p_{(i)}\text{ with } i\le k,\quad k=\max\Big\{i:\ p_{(i)}\le\frac{i}{m}q\Big\}
Statistics

Bernstein's inequality

P(Σ(Xᵢ − EXᵢ) ≥ t) ≤ exp(−(t²/2)/(ΣVar + Mt/3))

where |Xᵢ − EXᵢ| ≤ M

Tighter than Hoeffding when the variance is small.

Worked example: t = 10, v = 25, M = 1 → 0.171237 ✓ checked

See also: Hoeffding's inequality

LaTeX source
P\Big(\sum_i(X_i-\mathbb E X_i)\ge t\Big)\le\exp\!\Big(-\frac{t^2/2}{\sum_i\operatorname{Var}(X_i)+Mt/3}\Big)
Statistics

Berry–Esseen bound

sup|Fₙ − Φ| ≤ Cρ/(σ³√n)

A quantitative CLT: the normal approximation error shrinks like 1/√n.

Worked example: C = 0.4748, rho = 2, s = 1, n = 100 → 0.09496 ✓ checked

See also: central limit theorem (standardised mean)

LaTeX source
\sup_x\big|F_n(x)-\Phi(x)\big|\le\frac{C\,\rho}{\sigma^3\sqrt n},\quad \rho=\mathbb E|X-\mu|^3,\ C\le0.4748
Statistics

Beta–binomial conjugate update

posterior = Beta(α + x, β + n − x)

Posterior mean (α + x)/(α + β + n): a weighted average of prior mean and sample proportion.

Worked example: al = 2, be = 2, x = 7, n = 10 → [9, 5, 0.642857] ✓ checked

See also: beta distribution: mean · maximum a posteriori (Gaussian mean, Gaussian prior) · additive (Laplace) smoothing

LaTeX source
\theta\sim\mathrm{Beta}(\alpha,\beta),\ x\text{ successes in }n\ \Rightarrow\ \theta\mid x\sim\mathrm{Beta}(\alpha+x,\ \beta+n-x)
Statistics

bias, variance and MSE of an estimator

MSE = Var + Bias²

A little bias can buy a lot of variance reduction (ridge, James–Stein).

Worked example: var = 0.04, bias = 0.1 → 0.05 ✓ checked

See also: bias–variance decomposition · James–Stein estimator

LaTeX source
\operatorname{Bias}(\hat\theta)=\mathbb E\hat\theta-\theta,\qquad \mathrm{MSE}(\hat\theta)=\operatorname{Var}(\hat\theta)+\operatorname{Bias}(\hat\theta)^2
Statistics

bias–variance decomposition

E[(y − f̂)²] = Bias² + Variance + σ²

where σ² = irreducible noise

Flexible models trade bias for variance.

Worked example: bias = 0.5, var = 0.3, noise = 0.2 → 0.75 ✓ checked

See also: mean squared error

LaTeX source
\mathbb{E}\big[(y-\hat f(x))^2\big]=\operatorname{Bias}[\hat f]^2+\operatorname{Var}[\hat f]+\sigma^2
Statistics

Bland–Altman limits of agreement

d̄ ± 1.96 s_d

where d = difference between two measurement methods

Worked example: dbar = 0.5, sd = 2 → [-3.42, 4.42] ✓ checked

See also: Cohen's kappa

LaTeX source
\bar d\pm1.96\,s_d
Statistics

Bonferroni correction

α_each = α / m

where m = number of tests

Controls the family-wise error rate; conservative.

Worked example: alpha = 0.05, m = 10 → 0.005 ✓ checked

See also: one-sample t statistic

LaTeX source
\alpha_{\text{each}}=\frac{\alpha}{m}
Statistics

bootstrap standard error

SE_boot = std of the statistic over B resamples

where θ̂*_b = statistic on resample b

Resample the data with replacement B times.

Worked example: t = [1, 2, 3, 4] → 1.29099 ✓ checked

See also: jackknife variance estimate

LaTeX source
\widehat{\mathrm{SE}}_{\text{boot}}=\sqrt{\frac1{B-1}\sum_{b=1}^{B}\big(\hat\theta^{*}_b-\bar{\hat\theta}^{*}\big)^2}
Statistics

Box–Cox transformation

(yᵏ − 1)/λ, or ln y when λ = 0

where y > 0

Stabilises variance and makes data more normal.

Worked example: y = 4, lam = 0.5 → 2 ✓ checked

See also: logarithm and exponent rules

LaTeX source
y^{(\lambda)}=\begin{cases}\dfrac{y^\lambda-1}{\lambda}&\lambda\ne0\\[2pt]\ln y&\lambda=0\end{cases}
Statistics

Cantelli's inequality

P(X − μ ≥ t) ≤ σ²/(σ² + t²)

The one-sided Chebyshev.

Worked example: s2 = 4, t = 4 → 0.2 ✓ checked

See also: Chebyshev's inequality

LaTeX source
P(X-\mu\ge t)\le\frac{\sigma^2}{\sigma^2+t^2}
Statistics

central limit theorem (standardised mean)

Zₙ = √n (X̄ₙ − μ) / σ  →  N(0, 1)

where X̄ₙ = sample mean, μ and σ = true mean and standard deviation

Needs i.i.d. samples with finite variance.

Worked example: n = 100, xbar = 10.5, mu = 10, s = 2 → 2.5 ✓ checked

See also: standard error of the mean · z-score

LaTeX source
Z_n=\frac{\sqrt{n}\,(\bar X_n-\mu)}{\sigma}\ \xrightarrow{d}\ \mathcal N(0,1)
Statistics

Chernoff bound (binomial tail)

P(X ≥ (1 + δ)μ) ≤ exp(−δ²μ/(2 + δ))

where X a sum of independent Bernoulli variables, μ = E[X]

Worked example: mu = 50, d = 0.2 → 0.40289 ✓ checked

See also: Hoeffding's inequality · Markov's inequality

LaTeX source
P(X\ge(1+\delta)\mu)\le\exp\!\Big(-\frac{\delta^2\mu}{2+\delta}\Big)
Statistics

chi-square goodness of fit

χ² = Σ (Oᵢ − Eᵢ)²/Eᵢ

where O observed counts, E expected counts, m fitted parameters

Needs expected counts of about 5 or more.

Worked example: O = [18, 22, 20, 40], E = [25, 25, 25, 25] → 12.32 ✓ checked

See also: chi-square test of independence

LaTeX source
\chi^2=\sum_i\frac{(O_i-E_i)^2}{E_i},\quad \nu=k-1-m
Statistics

chi-square test of independence

Eᵢⱼ = RᵢCⱼ/N;  χ² = Σ (Oᵢⱼ − Eᵢⱼ)²/Eᵢⱼ

where R, C = row and column totals

Worked example: O = [[20, 30], [30, 20]] → 4 ✓ checked

See also: chi-square goodness of fit · Cramér's V

LaTeX source
E_{ij}=\frac{R_iC_j}{N},\qquad \chi^2=\sum_{ij}\frac{(O_{ij}-E_{ij})^2}{E_{ij}},\quad \nu=(r-1)(c-1)
Statistics

coefficient of variation

CV = σ/μ

Unit-free spread; meaningful only for positive ratio-scale data.

Worked example: s = 2, m = 10 → 0.2 ✓ checked

See also: variance and standard deviation

LaTeX source
\mathrm{CV}=\frac{\sigma}{\mu}
Statistics

Cohen's d (effect size)

d = (μ₁ − μ₂) / s_pooled

About 0.2 small, 0.5 medium, 0.8 large (rules of thumb).

Worked example: m1 = 10, m2 = 8, s = 4 → 0.5 ✓ checked

See also: one-sample t statistic

LaTeX source
d=\frac{\mu_1-\mu_2}{s_{\text{pooled}}}
Statistics

Cohen's kappa

κ = (p_o − p_e)/(1 − p_e)

where p_o = observed agreement, p_e = agreement expected by chance

0 is chance-level agreement, 1 is perfect.

Worked example: po = 0.85, pe = 0.5 → 0.7 ✓ checked

See also: intraclass correlation (one-way)

LaTeX source
\kappa=\frac{p_o-p_e}{1-p_e}
Statistics

confidence interval for a difference of means

(x̄₁ − x̄₂) ± t·√(s₁²/n₁ + s₂²/n₂)

Worked example: d = 2, t = 2, se2 = 0.5 → [0.585786, 3.41421] ✓ checked

See also: Welch's t test

LaTeX source
(\bar x_1-\bar x_2)\pm t_{\nu,1-\alpha/2}\sqrt{\frac{s_1^2}{n_1}+\frac{s_2^2}{n_2}}
Statistics

confidence interval for a mean

x̄ ± z · s/√n

where z = 1.96 for 95%; use t instead of z for small n

Frequentist: 95% of such intervals contain the true mean.

Worked example: xbar = 10, s = 2, n = 100, z = 1.96 → [9.608, 10.392] ✓ checked

See also: standard error of the mean · one-sample t statistic

LaTeX source
\bar x \pm z_{1-\alpha/2}\,\frac{s}{\sqrt n}
Statistics

confidence interval for a variance

((n−1)s²/χ²_upper, (n−1)s²/χ²_lower)

where χ² quantiles with n − 1 degrees of freedom

Sensitive to non-normality.

Worked example: n = 20, s2 = 4, qlo = 8.907, qhi = 32.852 → [2.31341, 8.53261] ✓ checked

See also: sample variance (Bessel's correction)

LaTeX source
\Big(\frac{(n-1)s^2}{\chi^2_{1-\alpha/2,\,n-1}},\ \frac{(n-1)s^2}{\chi^2_{\alpha/2,\,n-1}}\Big)
Statistics

confidence interval for an odds ratio

exp(ln OR ± z√(1/a + 1/b + 1/c + 1/d))

Worked example: a = 20, b = 80, c = 10, d = 90, z = 1.96 → [0.99428, 5.09162] ✓ checked

See also: odds ratio and relative risk

LaTeX source
\exp\Big(\ln\widehat{\mathrm{OR}}\pm z_{1-\alpha/2}\sqrt{\tfrac1a+\tfrac1b+\tfrac1c+\tfrac1d}\Big)
Statistics

Cook's distance

Dᵢ = eᵢ²/(p s²) · hᵢᵢ/(1 − hᵢᵢ)²

where eᵢ = residual, p = parameters

Large values flag influential points (rule of thumb: > 4/n).

Worked example: e = 2, p = 2, s2 = 1, h = 0.4 → 2.22222 ✓ checked

See also: hat matrix and leverage

LaTeX source
D_i=\frac{e_i^2}{p\,s^2}\cdot\frac{h_{ii}}{(1-h_{ii})^2}
Statistics

Cox proportional hazards model

h(t|x) = h₀(t) exp(βᵀx)

where h₀ = baseline hazard

exp(β) is the hazard ratio for a one-unit increase in x.

Worked example: beta = 0.7 → 2.01375 ✓ checked

See also: hazard and survival functions

LaTeX source
h(t\mid\mathbf x)=h_0(t)\,\exp\big(\boldsymbol\beta^{\top}\mathbf x\big)
Statistics

Cramér's V

V = √( (χ²/N) / min(r−1, c−1) )

Effect size for association between categorical variables, from 0 to 1.

Worked example: chi2 = 4, N = 100, r = 2, c = 2 → 0.2 ✓ checked

See also: chi-square test of independence · phi coefficient (2×2)

LaTeX source
V=\sqrt{\frac{\chi^2/N}{\min(r-1,\,c-1)}}
Statistics

Cramér–Rao bound

Var(θ̂) ≥ 1 / (n·I(θ))

where for any unbiased estimator

Worked example: n = 100, info = 4 → 0.0025 ✓ checked

See also: Fisher information (Bernoulli)

LaTeX source
\operatorname{Var}(\hat\theta)\ge\frac{1}{n\,I(\theta)}
Statistics

Cronbach's alpha

α = (k/(k−1))(1 − Σσᵢ²/σ_T²)

where k items, σ_T² = variance of the total score

A reliability measure of internal consistency.

Worked example: k = 4, vi = [1, 1, 1, 1], vt = 10 → 0.8 ✓ checked

See also: intraclass correlation (one-way)

LaTeX source
\alpha=\frac{k}{k-1}\Big(1-\frac{\sum_i\sigma_i^2}{\sigma_T^2}\Big)
Statistics

CUPED variance reduction

adjust the metric with a pre-experiment covariate

A correlation of 0.7 halves the variance.

Worked example: rho = 0.7 → 0.51 ✓ checked

See also: control variates

LaTeX source
Y^{*}=Y-\theta\,(X-\mathbb E X),\quad \theta=\frac{\operatorname{Cov}(X,Y)}{\operatorname{Var}X},\quad \operatorname{Var}(Y^{*})=(1-\rho^2)\operatorname{Var}(Y)
Statistics

CUSUM change detection

Sₜ = max(0, Sₜ₋₁ + xₜ − μ₀ − k);  alarm when Sₜ > h

where k = allowance, h = threshold

Detects a small sustained shift faster than a Shewhart chart.

Worked example: x = [10, 10.5, 11, 12], mu0 = 10, k = 0.25 → 2.75 ✓ checked

See also: sequential probability ratio test

LaTeX source
S_t=\max\big(0,\ S_{t-1}+x_t-\mu_0-k\big),\qquad \text{alarm if }S_t>h
Statistics

delta method

Var(g(θ̂)) ≈ g′(θ)² Var(θ̂)

Propagates uncertainty through a smooth function.

Worked example: gp = 2, v = 0.25 → 1 ✓ checked

See also: standard error of the mean

LaTeX source
\sqrt n\big(g(\hat\theta)-g(\theta)\big)\xrightarrow{d}\mathcal N\big(0,\ g'(\theta)^2\sigma^2\big)
Statistics

design effect (cluster sampling)

deff = 1 + (m − 1)ρ

where m = cluster size, ρ = intraclass correlation

Correlated observations carry less information than independent ones.

Worked example: m = 20, rho = 0.05, n = 1000 → [1.95, 512.821] ✓ checked

See also: intraclass correlation (one-way)

LaTeX source
\mathrm{deff}=1+(m-1)\rho,\qquad n_{\text{eff}}=\frac{n}{\mathrm{deff}}
Statistics

deviance

D = 2(ℓ_saturated − ℓ_model)

For the normal it is the residual sum of squares; compare nested models by the drop in deviance (≈ χ²).

Worked example: ls = -10, lm = -14 → 8 ✓ checked

See also: likelihood ratio test

LaTeX source
D=2\big(\ell_{\text{saturated}}-\ell_{\text{model}}\big)
Statistics

difference-in-differences

τ̂ = (treated: post − pre) − (control: post − pre)

Needs parallel trends.

Worked example: tp = 12, tq = 10, cp = 9, cq = 8 → 1 ✓ checked

See also: average treatment effect

LaTeX source
\hat\tau=\big(\bar Y_{T,\text{post}}-\bar Y_{T,\text{pre}}\big)-\big(\bar Y_{C,\text{post}}-\bar Y_{C,\text{pre}}\big)
Statistics

Dirichlet–multinomial conjugate update

posterior = Dir(α + x)

Posterior mean (αₖ + xₖ)/(α₀ + n): additive smoothing.

Worked example: al = [1, 1, 1], x = [5, 3, 2] → [0.461538, 0.307692, 0.230769] ✓ checked

See also: additive (Laplace) smoothing

LaTeX source
\mathbf p\sim\mathrm{Dir}(\boldsymbol\alpha),\ \text{counts }\mathbf x\ \Rightarrow\ \mathbf p\mid\mathbf x\sim\mathrm{Dir}(\boldsymbol\alpha+\mathbf x)
Statistics

Durbin–Watson statistic

d = Σ(eₜ − eₜ₋₁)²/Σeₜ² ≈ 2(1 − ρ̂₁)

Near 2 means no first-order autocorrelation.

Worked example: e = [1, -1, 1, -1] → 3 ✓ checked

See also: autocorrelation function

LaTeX source
d=\frac{\sum_{t=2}^{n}(e_t-e_{t-1})^2}{\sum_{t=1}^{n}e_t^2}\approx2(1-\hat\rho_1)
Statistics

Dvoretzky–Kiefer–Wolfowitz inequality

P(sup|Fₙ − F| > ε) ≤ 2 exp(−2nε²)

Gives a distribution-free confidence band for a cdf.

Worked example: n = 100, e = 0.1 → 0.270671 ✓ checked

See also: empirical distribution function

LaTeX source
P\Big(\sup_x|F_n(x)-F(x)|>\varepsilon\Big)\le 2e^{-2n\varepsilon^2}
Statistics

effective degrees of freedom of ridge

df(λ) = Σ dⱼ²/(dⱼ² + λ)

where dⱼ = singular values of X

Falls from p (λ = 0) toward 0 as λ grows.

Worked example: d = [3, 1], lam = 1 → 1.4 ✓ checked

See also: ridge regression (closed form)

LaTeX source
\mathrm{df}(\lambda)=\operatorname{tr}\big[X(X^{\top}X+\lambda I)^{-1}X^{\top}\big]=\sum_j\frac{d_j^2}{d_j^2+\lambda}
Statistics

Fisher information (Bernoulli)

I(p) = E[(∂ ln f/∂p)²] = 1 / (p(1−p))

Larger information means a sharper likelihood and a more precise estimate.

Worked example: p = 0.5 → 4 ✓ checked

See also: Cramér–Rao bound

LaTeX source
I(p)=\mathbb{E}\!\left[\left(\frac{\partial}{\partial p}\ln f(X;p)\right)^{2}\right]=\frac{1}{p(1-p)}
Statistics

Fisher z-transformation of a correlation

z = ½ ln((1 + r)/(1 − r));  SE = 1/√(n − 3)

Makes r approximately normal; build the interval on z and transform back with tanh.

Worked example: r = 0.6, n = 28 → [0.693147, 0.2] ✓ checked

See also: Pearson correlation

LaTeX source
z=\operatorname{artanh}(r)=\tfrac12\ln\frac{1+r}{1-r},\qquad \mathrm{SE}=\frac1{\sqrt{n-3}}
Statistics

Fisher's exact test (one table)

p = C(a+b, a) C(c+d, c) / C(n, a+c)

where table [[a, b], [c, d]], n = a+b+c+d

The hypergeometric probability of this exact table given the margins; sum over equal or more extreme tables for the p-value.

Worked example: a = 3, b = 1, c = 1, d = 3 → 0.228571 ✓ checked

See also: hypergeometric distribution: probability mass

LaTeX source
p=\frac{\binom{a+b}{a}\binom{c+d}{c}}{\binom{n}{a+c}}
Statistics

Frisch–Waugh–Lovell theorem

partial out the controls from both x and y, then regress the residuals

Explains what 'controlling for' means.

Worked example: x = [1, 2, 3, 4], z = [1, 1, 2, 2], y = [2, 3, 6, 7] → 2.66454e-15 ✓ checked

See also: ordinary least squares (normal equations) · orthogonal projection matrix

LaTeX source
\hat\beta_1=\frac{\tilde x^{\top}\tilde y}{\tilde x^{\top}\tilde x},\quad \tilde x=M_2x,\ \tilde y=M_2y,\ M_2=I-X_2(X_2^{\top}X_2)^{-1}X_2^{\top}
Statistics

gamma–Poisson conjugate update

posterior = Gamma(α + Σxᵢ, β + n)  (rate parameterisation)

Posterior mean (α + s)/(β + n).

Worked example: al = 2, be = 1, s = 14, n = 5 → [16, 6, 2.66667] ✓ checked

See also: Poisson distribution: mean · Beta–binomial conjugate update

LaTeX source
\lambda\sim\mathrm{Gamma}(\alpha,\beta),\ \sum x_i=s\text{ over }n\ \Rightarrow\ \lambda\mid x\sim\mathrm{Gamma}(\alpha+s,\ \beta+n)
Statistics

generalised least squares

β̂ = (XᵀΣ⁻¹X)⁻¹ XᵀΣ⁻¹y

where Σ = error covariance

Worked example: X = [[1, 0], [1, 1], [1, 2]], y = [1, 3, 5], S = [9 values] → [1, 2] ✓ checked

See also: weighted least squares

LaTeX source
\hat\beta=(X^{\top}\Sigma^{-1}X)^{-1}X^{\top}\Sigma^{-1}\mathbf y,\quad \operatorname{Var}(\hat\beta)=(X^{\top}\Sigma^{-1}X)^{-1}
Statistics

geometric mean

x̄_g = (Π xᵢ)^(1/n)

where xᵢ > 0

The right average for growth rates and ratios.

Worked example: x = [1, 2, 4, 8] → 2.82843 ✓ checked

See also: harmonic mean · AM–GM inequality

LaTeX source
\bar x_g=\Big(\prod_i x_i\Big)^{1/n}=\exp\!\Big(\frac1n\sum_i\ln x_i\Big)
Statistics

harmonic mean

x̄_h = n / Σ (1/xᵢ)

where xᵢ > 0

The right average for rates (speed over equal distances) and the basis of the F₁ score.

Worked example: x = [1, 2, 4] → 1.71429 ✓ checked

See also: geometric distribution: mean · F1 score

LaTeX source
\bar x_h=\frac{n}{\sum_i 1/x_i}
Statistics

hat matrix and leverage

H = X(XᵀX)⁻¹Xᵀ;  ŷ = Hy;  Σ hᵢᵢ = p

where p = number of columns of X

hᵢᵢ is the leverage of observation i.

Worked example: X = [[1, 1], [1, 2], [1, 3], [1, 4]] → 2 ✓ checked

See also: Cook's distance · leave-one-out residual shortcut

LaTeX source
H=X(X^{\top}X)^{-1}X^{\top},\qquad \hat{\mathbf y}=H\mathbf y,\quad h_{ii}\in[0,1],\ \ \sum_ih_{ii}=p
Statistics

Hedges' g

g = d·(1 − 3/(4(n₁+n₂) − 9))

where d = Cohen's d

Removes the small-sample bias of d.

Worked example: d = 0.5, n1 = 10, n2 = 10 → 0.478873 ✓ checked

See also: Cohen's d (effect size)

LaTeX source
g=d\Big(1-\frac{3}{4(n_1+n_2)-9}\Big)
Statistics

Holm–Bonferroni procedure

reject H₍ᵢ₎ while p₍ᵢ₎ ≤ α/(m − i + 1), in order of increasing p

Controls the family-wise error rate; uniformly more powerful than Bonferroni.

Worked example: p = [0.001, 0.012, 0.03, 0.2], alpha = 0.05 → 2 ✓ checked

See also: Bonferroni correction · Benjamini–Hochberg (false discovery rate)

LaTeX source
\text{reject } H_{(i)}\text{ while } p_{(i)}\le\frac{\alpha}{m-i+1}
Statistics

Holt's linear trend method

level and trend recursions; forecast ℓₜ + h·bₜ

Worked example: y = 12, l = 10, b = 1, a = 0.5, be = 0.5 → [11.5, 1.25, 14] ✓ checked

See also: simple exponential smoothing

LaTeX source
\ell_t=\alpha y_t+(1-\alpha)(\ell_{t-1}+b_{t-1}),\ \ b_t=\beta(\ell_t-\ell_{t-1})+(1-\beta)b_{t-1},\ \ \hat y_{t+h}=\ell_t+hb_t
Statistics

Horvitz–Thompson estimator

T̂ = Σ yᵢ/πᵢ

where πᵢ = inclusion probability

Unbiased for the population total under any design.

Worked example: y = [10, 20], pi = [0.1, 0.2] → 200 ✓ checked

See also: importance sampling

LaTeX source
\hat T=\sum_{i\in s}\frac{y_i}{\pi_i}
Statistics

intention-to-treat and LATE

LATE = ITT / (share of compliers)

Worked example: itt = 2, comp = 0.5 → 4 ✓ checked

See also: instrumental-variable estimator

LaTeX source
\mathrm{LATE}=\frac{\mathrm{ITT}}{\text{compliance rate}}=\frac{\mathbb E[Y\mid Z=1]-\mathbb E[Y\mid Z=0]}{\mathbb E[T\mid Z=1]-\mathbb E[T\mid Z=0]}
Statistics

inverse-propensity weighting

τ̂ = (1/n) Σ (TᵢYᵢ/e(Xᵢ) − (1 − Tᵢ)Yᵢ/(1 − e(Xᵢ)))

where e(x) = propensity score P(T = 1 | x)

Reweights units to mimic a randomised experiment.

Worked example: T = [1, 0], Y = [10, 6], e = [0.5, 0.5] → 4 ✓ checked

See also: average treatment effect · Horvitz–Thompson estimator

LaTeX source
\hat\tau=\frac1n\sum_i\Big(\frac{T_iY_i}{e(X_i)}-\frac{(1-T_i)Y_i}{1-e(X_i)}\Big)
Statistics

jackknife variance estimate

Var_jack = ((n−1)/n) Σ (θ̂₍₋ᵢ₎ − mean)²

where θ̂₍₋ᵢ₎ = statistic leaving out observation i

Worked example: x = [1, 2, 4, 7] → 1.75 ✓ checked

See also: bootstrap standard error

LaTeX source
\widehat{\operatorname{Var}}_{\text{jack}}=\frac{n-1}{n}\sum_{i=1}^{n}\big(\hat\theta_{(-i)}-\bar\theta_{(\cdot)}\big)^2
Statistics

James–Stein estimator

θ̂ = (1 − (p − 2)σ²/‖x‖²) x

where p ≥ 3 means

Shrinking toward 0 beats the raw estimate in total squared error when p ≥ 3: the origin of shrinkage and regularisation.

Worked example: x = [3, 4, 0], s2 = 1 → [2.88, 3.84, 0] ✓ checked

See also: ridge regression (closed form)

LaTeX source
\hat\theta_{JS}=\Big(1-\frac{(p-2)\sigma^2}{\|\mathbf x\|^2}\Big)\mathbf x
Statistics

Jeffreys prior

π(θ) ∝ √I(θ)

where I = Fisher information

Invariant under reparameterisation. For a Bernoulli, Beta(½, ½).

Worked example: p = 0.25 → 2.3094 ✓ checked

See also: Fisher information (Bernoulli)

LaTeX source
\pi(\theta)\propto\sqrt{I(\theta)}
Statistics

Kaplan–Meier estimator

Ŝ(t) = Π (1 − dᵢ/nᵢ)

where dᵢ = events, nᵢ = at risk at time tᵢ

Handles censored observations.

Worked example: d = [1, 1, 2], n = [10, 8, 5] → 0.4725 ✓ checked

See also: hazard and survival functions

LaTeX source
\hat S(t)=\prod_{t_i\le t}\Big(1-\frac{d_i}{n_i}\Big)
Statistics

Kendall's tau

τ = (C − D)/C(n, 2)

where C, D = concordant and discordant pairs

Worked example: C = 8, D = 2 → 0.6 ✓ checked

See also: Spearman's rank correlation

LaTeX source
\tau=\frac{C-D}{\binom n2}
Statistics

Kolmogorov–Smirnov statistic

D_n = sup_x |Fₙ(x) − F(x)|

where Fₙ = empirical cdf

Distribution-free under the null; reject for large √n·Dₙ.

Worked example: x = [0.1, 0.4, 0.7] → 0.3 ✓ checked

See also: empirical distribution function

LaTeX source
D_n=\sup_x\big|F_n(x)-F(x)\big|
Statistics

Kruskal–Wallis H

H = 12/(N(N+1)) Σ R_g²/n_g − 3(N + 1)

where R_g = rank sum of group g

Nonparametric one-way ANOVA.

Worked example: R = [15, 25, 38], n = [4, 4, 4] → 5.11538 ✓ checked

See also: one-way ANOVA F statistic

LaTeX source
H=\frac{12}{N(N+1)}\sum_g\frac{R_g^2}{n_g}-3(N+1)
Statistics

kurtosis (excess)

γ₂ = E[((X − μ)/σ)⁴] − 3

Zero for the normal. Positive means heavier tails than the normal.

Worked example: x = [1, 2, 3, 4, 10] → -0.212 ✓ checked

See also: skewness

LaTeX source
\gamma_2=\mathbb E\Big[\Big(\frac{X-\mu}{\sigma}\Big)^4\Big]-3
Statistics

lasso solution for an orthonormal design

β̂ⱼ = sign(β̂_OLS)(|β̂_OLS| − λ)₊

where (·)₊ = max(·, 0)

The soft-thresholding operator: small coefficients become exactly zero.

Worked example: b = [3, -0.5, 1.2], lam = 1 → [2, -0, 0.2] ✓ checked

See also: L1 penalty (lasso) · proximal operator of the L1 norm

LaTeX source
\hat\beta_j=\operatorname{sign}(\hat\beta_j^{\mathrm{OLS}})\big(|\hat\beta_j^{\mathrm{OLS}}|-\lambda\big)_+
Statistics

law of large numbers

P(|X̄ₙ − μ| ≥ ε) ≤ σ²/(nε²) → 0

Weak law via Chebyshev. The strong law says X̄ₙ → μ with probability 1.

Worked example: s2 = 4, n = 100, e = 0.5 → 0.16 ✓ checked

See also: Chebyshev's inequality · central limit theorem (standardised mean)

LaTeX source
P\big(|\bar X_n-\mu|\ge\varepsilon\big)\le\frac{\sigma^2}{n\varepsilon^2}\ \xrightarrow{n\to\infty}\ 0
Statistics

leave-one-out residual shortcut

e₍₋ᵢ₎ = eᵢ/(1 − hᵢᵢ)

Exact leave-one-out error for linear smoothers without refitting.

Worked example: e = 0.5, h = 0.25 → 0.666667 ✓ checked

See also: hat matrix and leverage

LaTeX source
e_{(-i)}=\frac{e_i}{1-h_{ii}},\qquad \mathrm{PRESS}=\sum_i\Big(\frac{e_i}{1-h_{ii}}\Big)^2
Statistics

likelihood ratio test

−2 ln Λ = 2(ℓ(θ̂₁) − ℓ(θ̂₀)) → χ²(q)

where q = difference in free parameters (Wilks' theorem)

Worked example: l1 = -100, l0 = -104 → 8 ✓ checked

See also: Akaike information criterion

LaTeX source
-2\ln\Lambda=2\big(\ell(\hat\theta_1)-\ell(\hat\theta_0)\big)\ \xrightarrow{d}\ \chi^2_{q}
Statistics

Ljung–Box statistic

Q = n(n + 2) Σ ρ̂ₖ²/(n − k)

Tests whether residual autocorrelations are jointly zero.

Worked example: n = 100, rho = [0.2, 0.1] → 5.16203 ✓ checked

See also: autocorrelation function

LaTeX source
Q=n(n+2)\sum_{k=1}^{h}\frac{\hat\rho_k^2}{n-k}\ \sim\ \chi^2_h
Statistics

log-odds (logit)

logit(p) = ln( p / (1 − p) )

The inverse of the sigmoid. Logistic regression is linear in the log-odds.

Worked example: p = 0.8 → 1.38629 ✓ checked

See also: sigmoid (logistic function) · logistic regression model

LaTeX source
\operatorname{logit}(p)=\ln\frac{p}{1-p},\qquad \sigma(\operatorname{logit}(p))=p
Statistics

log-rank statistic

χ² = (O₁ − E₁)²/V

Compares survival curves of two groups.

Worked example: o = 12, e = 8, v = 4 → 4 ✓ checked

See also: Kaplan–Meier estimator

LaTeX source
\chi^2=\frac{(O_1-E_1)^2}{V},\quad E_1=\sum_t\frac{n_{1t}d_t}{n_t}
Statistics

MA(1) process

xₜ = εₜ + θεₜ₋₁;  ρ₁ = θ/(1 + θ²)

Worked example: th = 0.5 → 0.4 ✓ checked

See also: AR(1) process

LaTeX source
x_t=\varepsilon_t+\theta\varepsilon_{t-1},\quad \rho_1=\frac{\theta}{1+\theta^2},\ \rho_k=0\ (k\ge2)
Statistics

Mallows' Cp

Cp = SSE_p/σ̂² − n + 2p

A good subset model has Cp close to p.

Worked example: sse = 50, s2 = 2, n = 30, p = 4 → 3 ✓ checked

See also: Akaike information criterion

LaTeX source
C_p=\frac{\mathrm{SSE}_p}{\hat\sigma^2}-n+2p
Statistics

Mann–Whitney U

U₁ = R₁ − n₁(n₁+1)/2;  z = (U − n₁n₂/2)/√(n₁n₂(n₁+n₂+1)/12)

where R₁ = rank sum of group 1

Distribution-free alternative to the two-sample t test.

Worked example: r1 = 40, n1 = 7, n2 = 8 → [12, -1.85164] ✓ checked

See also: Welch's t test

LaTeX source
U_1=R_1-\frac{n_1(n_1+1)}{2},\quad z=\frac{U-n_1n_2/2}{\sqrt{n_1n_2(n_1+n_2+1)/12}}
Statistics

maximum a posteriori (Gaussian mean, Gaussian prior)

μ̂_MAP = ( (n/σ²) x̄ + μ₀/τ² ) / ( n/σ² + 1/τ² )

where likelihood N(μ, σ²), prior N(μ₀, τ²), n samples with mean x̄

A precision-weighted average of the data mean and the prior mean; the prior fades as n grows.

Worked example: n = 10, s2 = 4, xbar = 2, mu0 = 0, t2 = 1 → 1.42857 ✓ checked

See also: Bayes' theorem · maximum likelihood estimates of a Gaussian · L2 penalty (weight decay)

LaTeX source
\hat\mu_{\mathrm{MAP}}=\frac{\frac{n}{\sigma^2}\bar x+\frac{1}{\tau^2}\mu_0}{\frac{n}{\sigma^2}+\frac{1}{\tau^2}}
Statistics

McDiarmid's inequality

P(f − Ef ≥ t) ≤ exp(−2t²/Σcᵢ²)

where changing coordinate i alters f by at most cᵢ

Bounded differences; underlies many generalisation bounds.

Worked example: t = 5, c = [25 values] → 0.135335 ✓ checked

See also: Hoeffding's inequality

LaTeX source
P\big(f-\mathbb Ef\ge t\big)\le\exp\!\Big(-\frac{2t^2}{\sum_ic_i^2}\Big)
Statistics

McNemar's test

χ² = (b − c)²/(b + c)

where b, c = discordant pairs

Compares two classifiers (or paired binary outcomes) on the same test set.

Worked example: b = 15, c = 5 → 5 ✓ checked

See also: paired t test

LaTeX source
\chi^2=\frac{(b-c)^2}{b+c}\quad(\nu=1)
Statistics

median

median = middle order statistic (average of the middle two if n is even)

where x₍ᵢ₎ = i-th smallest

Minimises Σ|xᵢ − c|; robust to outliers.

Worked example: x = [7, 1, 3, 9, 5, 100] → 6 ✓ checked

See also: sample mean · median absolute deviation

LaTeX source
\tilde x=\begin{cases}x_{((n+1)/2)}&n\text{ odd}\\ \tfrac12\big(x_{(n/2)}+x_{(n/2+1)}\big)&n\text{ even}\end{cases}
Statistics

median absolute deviation

MAD = median(|xᵢ − median|);  σ̂ ≈ 1.4826·MAD

A robust spread; the 1.4826 factor makes it consistent with σ for normal data.

Worked example: x = [1, 2, 3, 4, 100] → 1 ✓ checked

See also: median · interquartile range

LaTeX source
\mathrm{MAD}=\operatorname{median}\big(|x_i-\tilde x|\big),\qquad \hat\sigma\approx1.4826\,\mathrm{MAD}
Statistics

mediation (product of coefficients)

indirect = a·b;  total = direct + indirect

where a: X → M, b: M → Y given X

Worked example: a = 0.5, b = 0.8, cp = 0.3 → [0.4, 0.7] ✓ checked

See also: average treatment effect

LaTeX source
\text{indirect effect}=a\,b,\qquad \text{total}=c'+ab
Statistics

normal quantiles (probit)

z_p = Φ⁻¹(p);  68–95–99.7 rule

z₀.₉₇₅ = 1.96, z₀.₉₅ = 1.645, z₀.₉₉₅ = 2.576.

Worked example: p = 0.975 → [1.95996, 0.682689, 0.9545] ✓ checked

See also: normal cumulative distribution · z-score

LaTeX source
z_p=\Phi^{-1}(p),\qquad P(|Z|<k)=\operatorname{erf}\!\Big(\frac k{\sqrt2}\Big)\ \ (\approx68\%,\ 95\%,\ 99.7\%\text{ for }k=1,2,3)
Statistics

normal–normal conjugate update (known variance)

precision-weighted mean; posterior precision = prior precision + n/σ²

where prior N(μ₀, τ²), data variance σ²

Worked example: m0 = 0, t2 = 1, xbar = 2, s2 = 4, n = 10 → [1.42857, 0.285714] ✓ checked

See also: maximum a posteriori (Gaussian mean, Gaussian prior)

LaTeX source
\mu\mid x\sim\mathcal N\Big(\frac{\mu_0/\tau^2+n\bar x/\sigma^2}{1/\tau^2+n/\sigma^2},\ \Big(\frac1{\tau^2}+\frac n{\sigma^2}\Big)^{-1}\Big)
Statistics

odds and probability

odds = p/(1 − p);  p = odds/(1 + odds)

Worked example: p = 0.8 → [4, 0.8] ✓ checked

See also: log-odds (logit) · odds ratio and relative risk

LaTeX source
\text{odds}=\frac p{1-p},\qquad p=\frac{\text{odds}}{1+\text{odds}},\qquad \text{log-odds}=\ln\frac p{1-p}
Statistics

odds ratio and relative risk

OR = ad/(bc);  RR = (a/(a+b)) / (c/(c+d))

where table [[a, b], [c, d]]: exposed (events a, none b), unexposed (events c, none d)

OR approximates RR only when events are rare.

Worked example: a = 20, b = 80, c = 10, d = 90 → [2.25, 2] ✓ checked

See also: log-odds (logit)

LaTeX source
\mathrm{OR}=\frac{ad}{bc},\qquad \mathrm{RR}=\frac{a/(a+b)}{c/(c+d)}
Statistics

one-sample t statistic

t = (x̄ − μ₀) / (s/√n)

where μ₀ = hypothesised mean; n − 1 degrees of freedom

Worked example: xbar = 10.5, mu0 = 10, s = 2, n = 100 → 2.5 ✓ checked

See also: z-score · standard error of the mean

LaTeX source
t=\frac{\bar x-\mu_0}{s/\sqrt n}
Statistics

one-way ANOVA F statistic

F = (SS_B/(k−1)) / (SS_W/(N−k))

where k groups, N observations

Worked example: g1 = [1, 2, 3], g2 = [2, 3, 4], g3 = [5, 6, 7] → 13 ✓ checked

See also: eta squared (effect size) · F distribution distribution: mean

LaTeX source
F=\frac{\mathrm{SS}_B/(k-1)}{\mathrm{SS}_W/(N-k)},\quad \mathrm{SS}_B=\sum_g n_g(\bar x_g-\bar x)^2,\ \mathrm{SS}_W=\sum_g\sum_i(x_{gi}-\bar x_g)^2
Statistics

paired t test

t = d̄ / (s_d/√n)

where dᵢ = paired differences

A one-sample t test on the differences.

Worked example: d = [1, 2, 0, 3, 4] → 2.82843 ✓ checked

See also: one-sample t statistic

LaTeX source
t=\frac{\bar d}{s_d/\sqrt n},\quad d_i=x_i-y_i
Statistics

Paley–Zygmund inequality

P(X > θEX) ≥ (1 − θ)² (EX)²/E[X²]

where X ≥ 0, 0 ≤ θ ≤ 1

A lower bound on how often X is not small.

Worked example: th = 0.5, m1 = 2, m2 = 5 → 0.2 ✓ checked

See also: Markov's inequality

LaTeX source
P\big(X>\theta\,\mathbb E X\big)\ge(1-\theta)^2\frac{(\mathbb E X)^2}{\mathbb E[X^2]}
Statistics

Pearson correlation

ρ = Cov(X,Y) / (σₓ σᵧ)

where ρ ∈ [−1, 1]

Measures linear association only. A perfect nonlinear relationship can give ρ = 0.

Worked example: x = [1, 2, 3, 4], y = [2, 4, 5, 9] → 0.964764 ✓ checked

See also: covariance · coefficient of determination R²

LaTeX source
\rho_{XY} = \frac{\operatorname{Cov}(X,Y)}{\sigma_X\,\sigma_Y}
Statistics

percentile (linear interpolation)

h = 1 + (n−1)p/100; interpolate between the neighbouring order statistics

The default of NumPy and R type 7.

Worked example: x = [10, 20, 30, 40], p = 30 → 19 ✓ checked

See also: interquartile range

LaTeX source
x_{(p)}=x_{(\lfloor h\rfloor)}+(h-\lfloor h\rfloor)\big(x_{(\lfloor h\rfloor+1)}-x_{(\lfloor h\rfloor)}\big),\quad h=1+(n-1)\tfrac p{100}
Statistics

permutation test p-value

p = (1 + #{T*_b ≥ T_obs}) / (1 + B)

The +1 counts the observed data as one permutation, so p is never 0.

Worked example: k = 7, B = 999 → 0.008 ✓ checked

See also: bootstrap standard error

LaTeX source
p=\frac{1+\#\{b:\ T^{*}_b\ge T_{\text{obs}}\}}{1+B}
Statistics

phi coefficient (2×2)

φ = (ad − bc)/√((a+b)(c+d)(a+c)(b+d))

where 2×2 table [[a, b], [c, d]]

The same as the Matthews correlation coefficient.

Worked example: a = 20, b = 30, c = 30, d = 20 → -0.2 ✓ checked

See also: Matthews correlation coefficient · Cramér's V

LaTeX source
\phi=\frac{ad-bc}{\sqrt{(a+b)(c+d)(a+c)(b+d)}}
Statistics

Poisson regression log-likelihood

ℓ = Σ [yᵢ log μᵢ − μᵢ − log yᵢ!]

Log link keeps the mean positive.

Worked example: mu = [2, 3], y = [1, 4] → -3.09046 ✓ checked

See also: Poisson distribution · GLM link functions

LaTeX source
\ell=\sum_i\big[y_i\log\mu_i-\mu_i-\log y_i!\big],\quad \mu_i=e^{\mathbf w^{\top}\mathbf x_i}
Statistics

pooled variance

s_p² = ((n₁−1)s₁² + (n₂−1)s₂²) / (n₁ + n₂ − 2)

Assumes equal population variances.

Worked example: n1 = 10, n2 = 15, s1 = 4, s2 = 9 → 7.04348 ✓ checked

See also: two-sample t test (pooled) · Welch's t test

LaTeX source
s_p^2=\frac{(n_1-1)s_1^2+(n_2-1)s_2^2}{n_1+n_2-2}
Statistics

quantile (pinball) loss

ρ_τ(u) = u(τ − 1[u < 0]),  u = y − ŷ

Minimised by the τ-quantile; the loss of quantile regression.

Worked example: y = 3, yh = 5, tau = 0.9 → 0.2 ✓ checked

See also: mean absolute error

LaTeX source
\rho_\tau(u)=u\big(\tau-\mathbf 1[u<0]\big)
Statistics

random walk

xₜ = xₜ₋₁ + εₜ;  Var(xₜ) = tσ²

Non-stationary: variance grows linearly; difference it to get white noise.

Worked example: t = 100, s2 = 2 → 200 ✓ checked

See also: AR(1) process

LaTeX source
x_t=x_{t-1}+\varepsilon_t\ \Rightarrow\ \operatorname{Var}(x_t)=t\,\sigma^2
Statistics

ratio estimator

μ̂_y = (ȳ/x̄) μ_x

where μ_x = known population mean of x

Beats ȳ when x and y are strongly correlated.

Worked example: ybar = 50, xbar = 10, mux = 12 → 60 ✓ checked

See also: variance of a sample mean (simple random sampling)

LaTeX source
\hat\mu_y=\frac{\bar y}{\bar x}\,\mu_x
Statistics

rule of three

upper 95% bound on a rate after zero events ≈ 3/n

Worked example: n = 300 → 0.01 ✓ checked

See also: Wilson score interval

LaTeX source
\text{0 events in }n\text{ trials}\ \Rightarrow\ p<\frac3n\ \text{ with 95\% confidence}
Statistics

running mean and variance (Welford)

δ = xₙ − x̄ₙ₋₁;  x̄ₙ = x̄ₙ₋₁ + δ/n;  Mₙ = Mₙ₋₁ + δ(xₙ − x̄ₙ)

One pass, numerically stable; works for streaming data.

Worked example: x = [2, 4, 4, 4, 5, 5, 7, 9] → [5, 4.57143] ✓ checked

See also: sample variance (Bessel's correction)

LaTeX source
\delta=x_n-\bar x_{n-1},\ \ \bar x_n=\bar x_{n-1}+\frac{\delta}{n},\ \ M_n=M_{n-1}+\delta\,(x_n-\bar x_n),\ \ s^2=\frac{M_n}{n-1}
Statistics

sample covariance matrix

S = (1/(n−1)) Σ (xᵢ − x̄)(xᵢ − x̄)ᵀ

Positive semi-definite; rank at most n − 1.

Worked example: X = [[1, 2], [2, 3], [3, 7]] → [[1, 2.5], [2.5, 7]] ✓ checked

See also: covariance · principal component analysis

LaTeX source
S=\frac1{n-1}\sum_{i=1}^{n}(\mathbf x_i-\bar{\mathbf x})(\mathbf x_i-\bar{\mathbf x})^{\top}
Statistics

sample mean

x̄ = (1/n) Σ xᵢ

The least-squares estimate of a location: it minimises Σ(xᵢ − c)².

Worked example: x = [2, 4, 4, 4, 5, 5, 7, 9] → 5 ✓ checked

See also: weighted mean · median

LaTeX source
\bar x=\frac1n\sum_{i=1}^{n}x_i
Statistics

sample size for comparing two means

n = 2 (z_{1−α/2} + z_{1−β})² σ² / δ²  per group

where δ = smallest difference worth detecting, σ = standard deviation

z = 1.96 for α = 0.05 (two-sided), 0.8416 for 80% power.

Worked example: za = 1.96, zb = 0.8416, s = 1, d = 0.5 → 62.7917 ✓ checked

See also: type I and II errors, and power · Cohen's d (effect size)

LaTeX source
n=\frac{2\,(z_{1-\alpha/2}+z_{1-\beta})^2\,\sigma^2}{\delta^2}\ \text{per group}
Statistics

sample-ratio mismatch check

χ² test on the arm sizes

A tiny p-value means the assignment is broken and results are untrustworthy.

Worked example: O = [5100, 4900], E = [5000, 5000] → 4 ✓ checked

See also: chi-square goodness of fit

LaTeX source
\chi^2=\sum_i\frac{(O_i-E_i)^2}{E_i}\ \ \text{against the intended allocation}
Statistics

sequential probability ratio test

stop as soon as the log-likelihood ratio leaves (ln(β/(1−α)), ln((1−β)/α))

Needs on average fewer samples than any fixed-sample test of the same error rates (Wald–Wolfowitz).

Worked example: a = 0.05, b = 0.2 → [2.77259, -1.55814] ✓ checked

See also: likelihood ratio test

LaTeX source
\Lambda_n=\sum_i\ln\frac{f_1(x_i)}{f_0(x_i)};\quad \text{accept }H_1\text{ if }\Lambda_n\ge\ln\frac{1-\beta}\alpha,\quad \text{accept }H_0\text{ if }\Lambda_n\le\ln\frac\beta{1-\alpha}
Statistics

simple linear regression

β̂₁ = Σ(xᵢ−x̄)(yᵢ−ȳ)/Σ(xᵢ−x̄)² = r·s_y/s_x;  β̂₀ = ȳ − β̂₁x̄

Worked example: x = [1, 2, 3, 4], y = [2, 4, 5, 9] → [2.2, -0.5] ✓ checked

See also: ordinary least squares (normal equations) · Pearson correlation

LaTeX source
\hat\beta_1=\frac{\sum(x_i-\bar x)(y_i-\bar y)}{\sum(x_i-\bar x)^2}=r\frac{s_y}{s_x},\qquad \hat\beta_0=\bar y-\hat\beta_1\bar x
Statistics

skewness

γ₁ = E[((X − μ)/σ)³]

Zero for symmetric distributions; positive means a long right tail.

Worked example: x = [1, 2, 3, 4, 10] → 1.13842 ✓ checked

See also: kurtosis (excess)

LaTeX source
\gamma_1=\mathbb E\Big[\Big(\frac{X-\mu}{\sigma}\Big)^3\Big]
Statistics

Slutsky's theorem

Xₙ → X in distribution, Yₙ → c in probability ⇒ Xₙ + Yₙ → X + c, XₙYₙ → cX

Why replacing σ by s in a z statistic is harmless for large n.

Worked example: c = 2, x = 1.5 → 3 ✓ checked

See also: central limit theorem (standardised mean)

LaTeX source
X_n\xrightarrow{d}X,\ Y_n\xrightarrow{p}c\ \Rightarrow\ X_n+Y_n\xrightarrow{d}X+c,\ \ X_nY_n\xrightarrow{d}cX
Statistics

Spearman's rank correlation

ρ_s = 1 − 6Σdᵢ²/(n(n² − 1))

where dᵢ = rank difference (no ties)

Pearson correlation of the ranks; detects monotone, not just linear, relationships.

Worked example: d2 = 4, n = 5 → 0.8 ✓ checked

See also: Pearson correlation · Kendall's tau

LaTeX source
\rho_s=1-\frac{6\sum_i d_i^2}{n(n^2-1)}
Statistics

standard error of the regression slope

SE(β̂₁) = s/√Σ(xᵢ − x̄)²

Worked example: x = [1, 2, 3, 4], y = [2, 4, 5, 9] → 0.424264 ✓ checked

See also: simple linear regression

LaTeX source
\mathrm{SE}(\hat\beta_1)=\frac{s}{\sqrt{\sum(x_i-\bar x)^2}},\quad s^2=\frac{\sum(y_i-\hat y_i)^2}{n-2}
Statistics

Stouffer's Z method

Z = Σ wᵢzᵢ / √(Σ wᵢ²)

where zᵢ = Φ⁻¹(1 − pᵢ); weights often √nᵢ

Worked example: z = [1.5, 2], w = [1, 1] → 2.47487 ✓ checked

See also: Fisher's method for combining p-values

LaTeX source
Z=\frac{\sum_i w_iz_i}{\sqrt{\sum_i w_i^2}}
Statistics

sufficiency (Fisher–Neyman factorisation)

f(x; θ) = g(T(x), θ) h(x)

For i.i.d. Bernoulli data the count of successes Σ xᵢ is sufficient. Rao–Blackwell: conditioning an estimator on a sufficient statistic never increases its variance.

Worked example: x = [1, 0, 1, 1], p = 0.6 → 0.0864 ✓ checked

See also: likelihood and log-likelihood

LaTeX source
f(x;\theta)=g\big(T(x),\theta\big)\,h(x)\ \iff\ T\text{ is sufficient for }\theta
Statistics

Tukey's HSD

q = (x̄ᵢ − x̄ⱼ)/√(MS_W/n)

where n = per-group size

Post-hoc pairwise comparisons after an ANOVA, controlling the family-wise error.

Worked example: d = 3, msw = 4, n = 9 → 4.5 ✓ checked

See also: one-way ANOVA F statistic · Holm–Bonferroni procedure

LaTeX source
q=\frac{\bar x_i-\bar x_j}{\sqrt{\mathrm{MS}_W/n}}
Statistics

two-proportion z test

z = (p̂₁ − p̂₂)/√(p̂(1−p̂)(1/n₁ + 1/n₂))

A/B tests on conversion rates.

Worked example: x1 = 60, n1 = 200, x2 = 40, n2 = 200 → 2.3094 ✓ checked

See also: standard error of a proportion

LaTeX source
z=\frac{\hat p_1-\hat p_2}{\sqrt{\hat p(1-\hat p)\big(\frac1{n_1}+\frac1{n_2}\big)}},\quad \hat p=\frac{x_1+x_2}{n_1+n_2}
Statistics

two-sample t test (pooled)

t = (x̄₁ − x̄₂)/(s_p√(1/n₁ + 1/n₂))

Assumes equal variances.

Worked example: m1 = 10, m2 = 8, sp2 = 7, n1 = 20, n2 = 30 → 2.61861 ✓ checked

See also: pooled variance · Welch's t test

LaTeX source
t=\frac{\bar x_1-\bar x_2}{s_p\sqrt{1/n_1+1/n_2}},\quad \nu=n_1+n_2-2
Statistics

type I and II errors, and power

α = P(reject H₀ | H₀ true);  β = P(keep H₀ | H₁ true);  power = 1 − β

Type I = false positive, type II = false negative. Lowering α lowers power unless n grows.

Worked example: beta = 0.2 → 0.8 ✓ checked

See also: two-sided p-value from a z statistic · sample size for comparing two means · Bonferroni correction

LaTeX source
\alpha=P(\text{reject }H_0\mid H_0),\quad \beta=P(\text{fail to reject}\mid H_1),\quad \text{power}=1-\beta
Statistics

variance inflation factor

VIFⱼ = 1/(1 − Rⱼ²)

where Rⱼ² = R² from regressing predictor j on the others

Above about 10 signals harmful multicollinearity.

Worked example: r2 = 0.9 → 10 ✓ checked

See also: ordinary least squares (normal equations)

LaTeX source
\mathrm{VIF}_j=\frac1{1-R_j^2}
Statistics

variance of combined groups

σ² = Σ n_g (σ_g² + (μ_g − μ)²) / Σ n_g

where μ = overall mean

Within-group plus between-group spread.

Worked example: n = [10, 20], m = [1, 4], v = [2, 3] → 4.66667 ✓ checked

See also: law of total variance

LaTeX source
\sigma^2=\frac{\sum_g n_g(\sigma_g^2+(\mu_g-\mu)^2)}{\sum_g n_g}
Statistics

Wald interval for a proportion

p̂ ± z√(p̂(1−p̂)/n)

Poor for small n or p near 0 or 1; prefer Wilson.

Worked example: p = 0.3, n = 100, z = 1.96 → [0.210182, 0.389818] ✓ checked

See also: Wilson score interval

LaTeX source
\hat p\pm z_{1-\alpha/2}\sqrt{\frac{\hat p(1-\hat p)}{n}}
Statistics

Wald test

W = (θ̂ − θ₀)²/Var(θ̂)

The square of a z statistic.

Worked example: th = 1.2, t0 = 1, v = 0.01 → 4 ✓ checked

See also: likelihood ratio test

LaTeX source
W=\frac{(\hat\theta-\theta_0)^2}{\widehat{\operatorname{Var}}(\hat\theta)}\ \sim\ \chi^2_1
Statistics

weighted least squares

β̂ = (XᵀWX)⁻¹ XᵀWy

where wᵢ ∝ 1/Var(εᵢ)

Optimal when errors are independent with unequal variances.

Worked example: X = [[1, 0], [1, 1], [1, 2]], y = [1, 3, 5], w = [1, 2, 1] → [1, 2] ✓ checked

See also: ordinary least squares (normal equations) · generalised least squares

LaTeX source
\hat\beta=(X^{\top}WX)^{-1}X^{\top}W\mathbf y,\quad W=\operatorname{diag}(w_i)
Statistics

weighted mean

x̄_w = Σ wᵢxᵢ / Σ wᵢ

where wᵢ = weights

Worked example: x = [1, 2, 3], w = [3, 2, 1] → 1.66667 ✓ checked

See also: sample mean

LaTeX source
\bar x_w=\frac{\sum_i w_ix_i}{\sum_i w_i}
Statistics

Welch's t test

t = (x̄₁ − x̄₂)/√(s₁²/n₁ + s₂²/n₂);  ν = Welch–Satterthwaite

Does not assume equal variances; prefer it by default.

Worked example: m1 = 10, m2 = 8, v1 = 4, v2 = 9, n1 = 20, n2 = 30 → [2.82843, 47.9965] ✓ checked

See also: two-sample t test (pooled)

LaTeX source
t=\frac{\bar x_1-\bar x_2}{\sqrt{s_1^2/n_1+s_2^2/n_2}},\qquad \nu\approx\frac{\big(s_1^2/n_1+s_2^2/n_2\big)^2}{\frac{(s_1^2/n_1)^2}{n_1-1}+\frac{(s_2^2/n_2)^2}{n_2-1}}
Statistics

Wilcoxon signed-rank statistic

W = Σ ranks of positive differences; E[W] = n(n+1)/4

Nonparametric paired test.

Worked example: n = 10 → [27.5, 96.25] ✓ checked

See also: paired t test

LaTeX source
W=\sum_{i:\,d_i>0}R_i,\qquad \mathbb E[W]=\frac{n(n+1)}{4},\ \ \operatorname{Var}(W)=\frac{n(n+1)(2n+1)}{24}
Statistics

Wilson score interval

Wilson: (p̂ + z²/2n ± z√(p̂(1−p̂)/n + z²/4n²)) / (1 + z²/n)

Behaves well for small n and extreme proportions.

Worked example: p = 0.3, n = 100, z = 1.96 → [0.218948, 0.39585] ✓ checked

See also: Wald interval for a proportion

LaTeX source
\frac{\hat p+\frac{z^2}{2n}\pm z\sqrt{\frac{\hat p(1-\hat p)}{n}+\frac{z^2}{4n^2}}}{1+\frac{z^2}n}
Statistics

Yule–Walker equations (AR(2))

[[1, ρ₁], [ρ₁, 1]] [φ₁, φ₂] = [ρ₁, ρ₂]

Estimates AR coefficients from autocorrelations.

Worked example: r1 = 0.6, r2 = 0.4 → [0.5625, 0.0625] ✓ checked

See also: AR(1) process

LaTeX source
\begin{pmatrix}1&\rho_1\\ \rho_1&1\end{pmatrix}\begin{pmatrix}\phi_1\\ \phi_2\end{pmatrix}=\begin{pmatrix}\rho_1\\ \rho_2\end{pmatrix}
Statistics

z-score

z = (x − μ) / σ

Standardises a value to units of standard deviations from the mean.

Worked example: x = 75, mu = 70, s = 10 → 0.5 ✓ checked

See also: normal cumulative distribution

LaTeX source
z=\frac{x-\mu}{\sigma}
Statistics

Šidák correction

α_each = 1 − (1 − α)^(1/m)

Slightly less conservative than Bonferroni (exact for independent tests).

Worked example: alpha = 0.05, m = 10 → 0.0051162 ✓ checked

See also: Bonferroni correction · Holm–Bonferroni procedure

LaTeX source
\alpha_{\text{each}}=1-(1-\alpha)^{1/m}
Information theory

Bhattacharyya coefficient and distance

BC = Σ √(pq);  D_B = −ln BC

Worked example: p = [0.5, 0.5], q = [0.9, 0.1] → 0.111572 ✓ checked

See also: Hellinger distance

LaTeX source
\mathrm{BC}=\sum_x\sqrt{p(x)q(x)},\qquad D_B=-\ln\mathrm{BC}
Information theory

binary entropy

H(p) = −p log p − (1−p) log(1−p)

Peaks at p = ½ (1 bit).

Worked example: p = 0.25 → 0.562335 ✓ checked

See also: Shannon entropy

LaTeX source
H_b(p)=-p\log p-(1-p)\log(1-p)
Information theory

bits and nats

bits = nats / ln 2;  PPL = 2^(bits) = e^(nats)

Most deep-learning libraries report nats; papers on compression report bits.

Worked example: h = 2 → [2.88539, 7.38906] ✓ checked

See also: perplexity

LaTeX source
1\ \text{nat}=\frac1{\ln2}\ \text{bits}\approx1.4427\ \text{bits},\qquad \mathrm{PPL}=2^{H_{\text{bits}}}=e^{H_{\text{nats}}}
Information theory

chain rule for entropy

H(X,Y) = H(X) + H(Y|X)

Generalises to H(X₁…Xₙ) = Σ H(Xᵢ | X₁…Xᵢ₋₁): the basis of autoregressive likelihoods.

Worked example: J = [[0.4, 0.1], [0.1, 0.4]] → 1.19355 ✓ checked

See also: joint entropy · conditional entropy

LaTeX source
H(X,Y)=H(X)+H(Y\mid X)
Information theory

chi-square divergence

χ²(p‖q) = Σ (p − q)²/q

Worked example: p = [0.5, 0.5], q = [0.9, 0.1] → 1.77778 ✓ checked

See also: Kullback–Leibler divergence

LaTeX source
\chi^2(p\|q)=\sum_x\frac{(p(x)-q(x))^2}{q(x)}
Information theory

conditional entropy

H(Y|X) = H(X,Y) − H(X)

Remaining uncertainty about Y once X is known.

Worked example: J = [[0.4, 0.1], [0.1, 0.4]] → 0.500402 ✓ checked

See also: mutual information · Shannon entropy

LaTeX source
H(Y\mid X)=H(X,Y)-H(X)
Information theory

data processing inequality

X → Y → Z  ⇒  I(X;Z) ≤ I(X;Y)

where Markov chain

Processing cannot create information. Example: two binary symmetric channels in a row.

Worked example: e1 = 0.1, e2 = 0.2 → 0.247974 ✓ checked

See also: mutual information

LaTeX source
X\to Y\to Z\ \Rightarrow\ I(X;Z)\le I(X;Y)
Information theory

entropy rate of a Markov chain

H = −Σᵢ πᵢ Σⱼ Pᵢⱼ log Pᵢⱼ

where π = stationary distribution

Worked example: P = [[0.9, 0.1], [0.5, 0.5]], pi = [0.833333, 0.166667] → 0.386427 ✓ checked

See also: stationary distribution of a Markov chain

LaTeX source
H=-\sum_i\pi_i\sum_jP_{ij}\log P_{ij}
Information theory

f-divergence

D_f(p‖q) = Σ q f(p/q)

f(t) = t log t gives KL, ½|t − 1| gives TV, (√t − 1)² gives (twice) squared Hellinger.

Worked example: p = [0.5, 0.5], q = [0.9, 0.1] → 0.510826 ✓ checked

See also: Kullback–Leibler divergence · total variation distance

LaTeX source
D_f(p\|q)=\sum_xq(x)\,f\!\Big(\frac{p(x)}{q(x)}\Big),\quad f\text{ convex},\ f(1)=0
Information theory

Fano's inequality

H(X|Y) ≤ H_b(Pₑ) + Pₑ log(|X| − 1)

where Pₑ = error probability of any estimator of X from Y

Links the error of any classifier to the information left about the label.

Worked example: pe = 0.1, m = 4 → 0.434944 ✓ checked

See also: binary entropy

LaTeX source
H(X\mid Y)\le H_b(P_e)+P_e\log(|\mathcal X|-1)
Information theory

Fisher information

I(θ) = E[(∂ ln f/∂θ)²] = −E[∂² ln f/∂θ²]

For n i.i.d. samples it is n·I(θ).

Worked example: n = 25, s2 = 4 → 6.25 ✓ checked

See also: Fisher information (Bernoulli) · Cramér–Rao bound · natural gradient

LaTeX source
I(\theta)=\mathbb E\Big[\Big(\frac{\partial\ln f(X;\theta)}{\partial\theta}\Big)^2\Big]=-\mathbb E\Big[\frac{\partial^2\ln f(X;\theta)}{\partial\theta^2}\Big]
Information theory

information bottleneck

min I(X;T) − β I(T;Y)

where T = compressed representation of X, β = trade-off

Keep what predicts Y, forget the rest of X.

Worked example: ixt = 1.5, ity = 1.2, b = 2 → -0.9 ✓ checked

See also: mutual information

LaTeX source
\min_{p(t\mid x)}\ I(X;T)-\beta\,I(T;Y)
Information theory

information content (surprisal)

I(x) = −log₂ p(x)

Entropy is the expected surprisal.

Worked example: p = 0.25 → 2 ✓ checked

See also: Shannon entropy

LaTeX source
I(x)=-\log_2p(x)\ \text{bits}
Information theory

Jensen–Shannon divergence

JS(p,q) = ½ KL(p‖m) + ½ KL(q‖m),   m = (p+q)/2

Symmetric and bounded by ln 2 (nats).

Worked example: p = [1, 0], q = [0, 1] → 0.693147 ✓ checked

See also: Kullback–Leibler divergence

LaTeX source
\mathrm{JS}(p,q)=\tfrac12 D_{\mathrm{KL}}(p\|m)+\tfrac12 D_{\mathrm{KL}}(q\|m),\quad m=\tfrac12(p+q)
Information theory

joint entropy

H(X,Y) = −Σ p(x,y) log p(x,y)

Worked example: J = [[0.4, 0.1], [0.1, 0.4]] → 1.19355 ✓ checked

See also: chain rule for entropy

LaTeX source
H(X,Y)=-\sum_{x,y}p(x,y)\log p(x,y)
Information theory

KL divergence between multivariate Gaussians

KL(N₀‖N₁) = ½[tr(Σ₁⁻¹Σ₀) + Δμᵀ Σ₁⁻¹ Δμ − k + ln(|Σ₁|/|Σ₀|)]

Worked example: S0 = [[1, 0], [0, 1]], S1 = [[2, 0], [0, 2]], d = [1, 0] → 0.443147 ✓ checked

See also: KL divergence between two Gaussians

LaTeX source
D_{\mathrm{KL}}=\tfrac12\Big[\operatorname{tr}(\Sigma_1^{-1}\Sigma_0)+(\boldsymbol\mu_1-\boldsymbol\mu_0)^{\top}\Sigma_1^{-1}(\boldsymbol\mu_1-\boldsymbol\mu_0)-k+\ln\frac{|\Sigma_1|}{|\Sigma_0|}\Big]
Information theory

KL divergence between two Gaussians

KL = ln(σ₂/σ₁) + (σ₁² + (μ₁−μ₂)²) / (2σ₂²) − ½

Closed form used in VAEs and variational inference.

Worked example: m1 = 0, s1 = 1, m2 = 1, s2 = 2 → 0.443147 ✓ checked

See also: Kullback–Leibler divergence · VAE KL term (diagonal Gaussian)

LaTeX source
D_{\mathrm{KL}}\big(\mathcal N(\mu_1,\sigma_1^2)\,\|\,\mathcal N(\mu_2,\sigma_2^2)\big)=\ln\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12
Information theory

Kraft inequality

Σ 2^(−ℓᵢ) ≤ 1

where ℓᵢ = codeword lengths

A prefix code with these lengths exists iff it holds.

Worked example: l = [1, 2, 3, 3] → 1 ✓ checked

See also: source coding theorem

LaTeX source
\sum_i2^{-\ell_i}\le1
Information theory

maximum mean discrepancy

MMD² = E k(x,x′) + E k(y,y′) − 2 E k(x,y)

where k = kernel, e.g. RBF

Zero iff the distributions match (for a characteristic kernel).

Worked example: x = [0, 1], y = [2, 3] → 1.16238 ✓ checked

See also: RBF (Gaussian) kernel

LaTeX source
\mathrm{MMD}^2=\mathbb E\,k(x,x')+\mathbb E\,k(y,y')-2\,\mathbb E\,k(x,y)
Information theory

maximum-entropy distribution

p(x) ∝ exp(Σ λₖ fₖ(x))

Fixed mean and variance gives the normal; fixed mean on [0, ∞) gives the exponential; nothing fixed gives the uniform.

Worked example: s = 1 → [1.41894, 0.176485] ✓ checked

See also: Shannon entropy

LaTeX source
\max_pH(p)\ \text{s.t. }\mathbb E[f_k]=c_k\ \Rightarrow\ p(x)\propto\exp\Big(\sum_k\lambda_kf_k(x)\Big)
Information theory

min-entropy

H∞ = −log maxₓ p(x)

The probability of guessing the most likely outcome; used in cryptography.

Worked example: p = [0.7, 0.3] → 0.356675 ✓ checked

See also: Rényi entropy

LaTeX source
H_\infty(X)=-\log\max_xp(x)
Information theory

minimum description length

MDL = L(model) + L(data | model)

where lengths in bits

A model is good if it compresses the data including its own description. BIC is an asymptotic form.

Worked example: lm = 120, ld = 880 → 1000 ✓ checked

See also: Bayesian information criterion

LaTeX source
\mathrm{MDL}=L(\text{model})+L(\text{data}\mid\text{model})
Information theory

mutual information

I(X;Y) = Σ p(x,y) log( p(x,y) / (p(x)p(y)) )

Zero iff X and Y are independent. I(X;Y) = H(X) − H(X|Y).

Worked example: J = [[0.4, 0.1], [0.1, 0.4]] → 0.192745 ✓ checked

See also: Shannon entropy · conditional entropy

LaTeX source
I(X;Y)=\sum_{x,y}p(x,y)\log\frac{p(x,y)}{p(x)\,p(y)}
Information theory

mutual information from entropies

I(X;Y) = H(X) + H(Y) − H(X,Y)

Worked example: hx = 0.693147, hy = 0.693147, hxy = 1.1935 → 0.192794 ✓ checked

See also: mutual information

LaTeX source
I(X;Y)=H(X)+H(Y)-H(X,Y)=H(X)-H(X\mid Y)
Information theory

natural gradient

θ ← θ − η F⁻¹ ∇L

where F = Fisher information matrix

Steepest descent in the geometry of the model's distribution, invariant to reparameterisation.

Worked example: th = [0, 0], F = [[4, 0], [0, 1]], g = [2, 1], lr = 0.1 → [-0.05, -0.1] ✓ checked

See also: Fisher information

LaTeX source
\theta\leftarrow\theta-\eta\,F^{-1}\nabla_\theta L
Information theory

peak signal-to-noise ratio

PSNR = 10 log₁₀(MAX²/MSE)

where MAX = largest pixel value (255 for 8-bit)

Higher is better; common for image and video reconstruction.

Worked example: mx = 255, mse = 100 → 28.1308 ✓ checked

See also: signal-to-noise ratio in decibels · mean squared error

LaTeX source
\mathrm{PSNR}=10\log_{10}\frac{\mathrm{MAX}^2}{\mathrm{MSE}}
Information theory

perplexity

PPL = exp( −(1/N) Σ log q(xᵢ) )

where q(xᵢ) = probability the model gave the observed token

The effective number of equally likely choices per token. Lower is better.

Worked example: q = [0.5, 0.25, 0.125] → 4 ✓ checked

See also: cross-entropy

LaTeX source
\mathrm{PPL}=\exp\!\Big(-\frac1N\sum_{i=1}^{N}\log q(x_i)\Big)
Information theory

Rényi entropy

H_α = (1/(1 − α)) log Σ p(x)^α

where α ≥ 0, α ≠ 1

α → 1 gives Shannon, α = 2 collision entropy, α → ∞ min-entropy.

Worked example: p = [0.7, 0.3], a = 2 → 0.544727 ✓ checked

See also: Shannon entropy · Tsallis entropy · min-entropy

LaTeX source
H_\alpha(X)=\frac1{1-\alpha}\log\sum_xp(x)^\alpha
Information theory

Shannon entropy

H(X) = −Σₓ p(x) log p(x)

where log base 2 gives bits, base e gives nats

Maximised by the uniform distribution (log n). Zero when the outcome is certain.

Worked example: p = [0.5, 0.5] → 0.693147 ✓ checked

See also: cross-entropy · binary entropy

LaTeX source
H(X)=-\sum_x p(x)\log p(x)
Information theory

Sinkhorn iterations (entropic optimal transport)

K = exp(−C/ε);  u ← a/(Kv);  v ← b/(Kᵀu);  P = diag(u) K diag(v)

where a, b = marginals, C = cost matrix

The plan P has marginals a and b at convergence.

Worked example: a = [0.5, 0.5], b = [0.5, 0.5], C = [[0, 1], [1, 0]], eps = 0.5 → [0.5, 0.5] ✓ checked

See also: Wasserstein-1 distance (1-D)

LaTeX source
K=e^{-C/\varepsilon},\quad u\leftarrow\frac{a}{Kv},\quad v\leftarrow\frac{b}{K^{\top}u},\quad P=\operatorname{diag}(u)K\operatorname{diag}(v)
Information theory

source coding theorem

H(X) ≤ L̄ < H(X) + 1

where L̄ = expected code length of an optimal prefix code

Entropy is the compression limit. Equality when all probabilities are powers of ½.

Worked example: p = [0.5, 0.25, 0.125, 0.125], l = [1, 2, 3, 3] → [1.75, 1.75] ✓ checked

See also: Shannon entropy · Kraft inequality

LaTeX source
H(X)\le\bar L<H(X)+1\ \text{bits}
Information theory

total variation distance

TV = ½ Σ |p − q|

The largest difference in probability of any event. Bounded in [0, 1].

Worked example: p = [0.5, 0.5], q = [0.9, 0.1] → 0.4 ✓ checked

See also: Kullback–Leibler divergence · Pinsker's inequality

LaTeX source
\mathrm{TV}(p,q)=\tfrac12\sum_x|p(x)-q(x)|=\sup_A|p(A)-q(A)|
Information theory

Tsallis entropy

S_q = (1 − Σ p(x)^q)/(q − 1)

Non-extensive; q → 1 gives Shannon (in nats).

Worked example: p = [0.7, 0.3], q = 2 → 0.42 ✓ checked

See also: Rényi entropy

LaTeX source
S_q=\frac{1-\sum_xp(x)^q}{q-1}
Linear algebra

2-D rotation matrix

R(θ) = [[cos θ, −sin θ], [sin θ, cos θ]]

where counter-clockwise by θ

Worked example: th = 1.5708 → [6.12323e-17, 1] ✓ checked

See also: orthogonal matrix · Rodrigues' rotation formula

LaTeX source
R(\theta)=\begin{pmatrix}\cos\theta&-\sin\theta\\ \sin\theta&\cos\theta\end{pmatrix}
Linear algebra

Cauchy–Schwarz inequality

|x·y| ≤ ‖x‖ ‖y‖

Equality iff the vectors are parallel.

Worked example: x = [1, 2], y = [3, 4] → 0.18034 ✓ checked

See also: dot product · cosine similarity

LaTeX source
|\mathbf x\cdot\mathbf y|\le\|\mathbf x\|\,\|\mathbf y\|
Linear algebra

Cayley–Hamilton theorem

A² − tr(A)A + det(A)I = 0  (2×2)

A matrix satisfies its own characteristic equation.

Worked example: A = [[1, 2], [3, 4]] → 4.44089e-16 ✓ checked

See also: eigenvalue equation · trace

LaTeX source
p(A)=0,\quad p(\lambda)=\det(\lambda I-A);\ \ \text{for }2\times2:\ A^2-\operatorname{tr}(A)A+\det(A)I=0
Linear algebra

Cholesky decomposition

A = L Lᵀ

Twice as fast as LU for symmetric positive-definite systems; used to sample from N(μ, Σ).

Worked example: A = [[2, 1], [1, 3]] → 4.44089e-16 ✓ checked

See also: LU decomposition and solving · QR decomposition

LaTeX source
A=LL^{\top}\quad(A\succ0,\ L\text{ lower triangular})
Linear algebra

conjugate gradient method

CG: αₖ = rᵀr/(pᵀAp); x += αp; r −= αAp; β = rₙₑwᵀrₙₑw/rᵀr; p = r + βp

where A symmetric positive definite

Solves an n×n system in at most n steps in exact arithmetic.

Worked example: A = [[2, 1], [1, 3]], b = [1, 2] → [0.2, 0.6] ✓ checked

See also: minimiser of a quadratic

LaTeX source
\alpha_k=\frac{\mathbf r_k^{\top}\mathbf r_k}{\mathbf p_k^{\top}A\mathbf p_k},\ \mathbf x_{k+1}=\mathbf x_k+\alpha_k\mathbf p_k,\ \mathbf r_{k+1}=\mathbf r_k-\alpha_kA\mathbf p_k,\ \beta_k=\frac{\mathbf r_{k+1}^{\top}\mathbf r_{k+1}}{\mathbf r_k^{\top}\mathbf r_k},\ \mathbf p_{k+1}=\mathbf r_{k+1}+\beta_k\mathbf p_k
Linear algebra

cosine similarity

cos θ = x·y / (‖x‖‖y‖)

Ignores magnitude; 1 = same direction, 0 = orthogonal.

Worked example: x = [1, 0], y = [1, 1] → 0.707107 ✓ checked

See also: dot product · InfoNCE (contrastive) loss

LaTeX source
\cos\theta=\frac{\mathbf x\cdot\mathbf y}{\|\mathbf x\|\,\|\mathbf y\|}
Linear algebra

Cramer's rule

xᵢ = det(Aᵢ)/det(A)

where Aᵢ = A with column i replaced by b

Elegant, but far slower than elimination for large systems.

Worked example: A = [[2, 1], [1, 3]], b = [3, 5] → [0.8, 1.4] ✓ checked

See also: determinant (2×2)

LaTeX source
x_i=\frac{\det A_i}{\det A}
Linear algebra

cross product and triple product

a × b = (a₂b₃ − a₃b₂, a₃b₁ − a₁b₃, a₁b₂ − a₂b₁)

The triple product a·(b×c) equals det[a b c] = the signed volume of the parallelepiped.

Worked example: a = [1, 0, 0], b = [0, 1, 0], c = [0, 0, 2] → [0, 0, 1, 2] ✓ checked

See also: dot product

LaTeX source
\mathbf a\times\mathbf b=\begin{pmatrix}a_2b_3-a_3b_2\\ a_3b_1-a_1b_3\\ a_1b_2-a_2b_1\end{pmatrix},\quad \|\mathbf a\times\mathbf b\|=\|\mathbf a\|\|\mathbf b\|\sin\theta
Linear algebra

cyclic property of the trace

tr(AB) = tr(BA)

Lets you rearrange quadratic forms: xᵀAx = tr(A xxᵀ).

Worked example: A = [[1, 2], [3, 4]], B = [[0, 1], [1, 0]] → 0 ✓ checked

See also: trace

LaTeX source
\operatorname{tr}(AB)=\operatorname{tr}(BA),\qquad \operatorname{tr}(ABC)=\operatorname{tr}(CAB)
Linear algebra

derivative of a matrix inverse

d(A⁻¹) = −A⁻¹ (dA) A⁻¹

Worked example: A = [[2, 1], [0, 1]], dA = [[1, 0], [0, 2]] → [[-0.25, 1.25], [0, -2]] ✓ checked

See also: gradient of log-determinant

LaTeX source
\frac{d}{dt}A(t)^{-1}=-A^{-1}\frac{dA}{dt}A^{-1}
Linear algebra

determinant (2×2)

det = ad − bc

Zero iff the matrix is singular.

Worked example: A = [[1, 2], [3, 4]] → -2 ✓ checked

See also: inverse (2×2)

LaTeX source
\det\begin{pmatrix}a&b\\c&d\end{pmatrix}=ad-bc
Linear algebra

determinant (3×3, rule of Sarrus)

det = aei + bfg + cdh − ceg − bdi − afh

Worked example: M = [9 values] → 0 ✓ checked

See also: determinant (2×2)

LaTeX source
\det\begin{pmatrix}a&b&c\\d&e&f\\g&h&i\end{pmatrix}=aei+bfg+cdh-ceg-bdi-afh
Linear algebra

determinant of a Kronecker product

det(A ⊗ B) = det(A)ᵐ det(B)ⁿ

Worked example: A = [[2, 0], [0, 3]], B = [[1, 1], [0, 2]] → 144 ✓ checked

See also: Kronecker product

LaTeX source
\det(A\otimes B)=\det(A)^{m}\det(B)^{n}\quad(A\in\mathbb R^{n\times n},\ B\in\mathbb R^{m\times m})
Linear algebra

determinant properties

det(AB) = det A det B;  det(A⁻¹) = 1/det A;  det(cA) = cⁿ det A

Worked example: A = [[1, 2], [3, 4]], B = [[0, 1], [1, 1]] → [2, -0.5, -18] ✓ checked

See also: determinant (2×2)

LaTeX source
\det(AB)=\det A\det B,\quad \det A^{\top}=\det A,\quad \det A^{-1}=\frac1{\det A},\quad \det(cA)=c^n\det A
Linear algebra

dot product

x·y = Σ xᵢyᵢ = ‖x‖‖y‖ cos θ

where θ = angle between the vectors

Zero iff orthogonal.

Worked example: x = [1, 2, 3], y = [4, 5, 6] → 32 ✓ checked

See also: cosine similarity

LaTeX source
\mathbf{x}\cdot\mathbf{y}=\sum_i x_i y_i=\|\mathbf x\|\|\mathbf y\|\cos\theta
Linear algebra

Euclidean (L2) norm

‖x‖₂ = √(Σ xᵢ²)

Worked example: x = [3, 4] → 5 ✓ checked

See also: L1 norm (Manhattan) · Lp norm

LaTeX source
\|\mathbf x\|_2=\sqrt{\sum_i x_i^2}
Linear algebra

Frobenius norm

‖A‖_F = √(Σᵢⱼ Aᵢⱼ²)

Worked example: A = [[1, 2], [3, 4]] → 5.47723 ✓ checked

See also: spectral norm

LaTeX source
\|A\|_F=\sqrt{\sum_{i,j}A_{ij}^2}=\sqrt{\operatorname{tr}(A^\top A)}
Linear algebra

Gershgorin circle theorem

every eigenvalue lies in a disc centred at aᵢᵢ with radius Σⱼ≠ᵢ |aᵢⱼ|

A quick bound on the spectrum; strict diagonal dominance implies invertibility.

Worked example: A = [[4, 1], [1, 2]] → 1 ✓ checked

See also: eigenvalue equation

LaTeX source
\lambda\in\bigcup_i\Big\{z:\ |z-a_{ii}|\le\sum_{j\ne i}|a_{ij}|\Big\}
Linear algebra

gradient of a trace

∂/∂X tr(AX) = Aᵀ;  ∂/∂X tr(XᵀAX) = (A + Aᵀ)X

Worked example: A = [[1, 2], [3, 4]], X = [[1, 0], [2, 1]] → [[1, 3], [2, 4]] ✓ checked

See also: gradient of a quadratic form

LaTeX source
\frac{\partial}{\partial X}\operatorname{tr}(AX)=A^{\top},\qquad \frac{\partial}{\partial X}\operatorname{tr}(X^{\top}AX)=(A+A^{\top})X
Linear algebra

gradient of log-determinant

∂/∂X ln det X = X⁻ᵀ

Appears in Gaussian log-likelihoods.

Worked example: X = [[2, 1], [0, 1]] → [[0.5, 0], [-0.5, 1]] ✓ checked

See also: multivariate normal density

LaTeX source
\frac{\partial}{\partial X}\ln\det X=X^{-\top}
Linear algebra

Gram matrix

G = XᵀX;  Gᵢⱼ = xᵢ·xⱼ

Positive semi-definite. Kernel methods work with G (or K) instead of X.

Worked example: X = [[1, 2], [3, 4], [5, 6]] → 0.264505 ✓ checked

See also: RBF (Gaussian) kernel

LaTeX source
G=X^{\top}X,\quad G_{ij}=\mathbf x_i\cdot\mathbf x_j,\quad G\succeq0
Linear algebra

Gram–Schmidt orthogonalisation

subtract the projections onto earlier vectors, then normalise

Classical Gram–Schmidt is unstable; use modified Gram–Schmidt or Householder QR.

Worked example: v1 = [1, 1], v2 = [1, 0] → 2.77556e-16 ✓ checked

See also: projection onto a vector · QR decomposition

LaTeX source
\mathbf u_k=\mathbf v_k-\sum_{j<k}\operatorname{proj}_{\mathbf u_j}(\mathbf v_k),\qquad \mathbf e_k=\frac{\mathbf u_k}{\|\mathbf u_k\|}
Linear algebra

graph Laplacian

L = D − A;  xᵀLx = Σ over edges (xᵢ − xⱼ)²

where D = degree matrix, A = adjacency

Eigenvalue 0 for each connected component; the second-smallest eigenvalue (Fiedler value) measures connectivity.

Worked example: A = [9 values] → [3.96029e-17, 1, 3] ✓ checked

See also: normalised graph Laplacian

LaTeX source
L=D-A,\qquad \mathbf x^{\top}L\mathbf x=\sum_{(i,j)\in E}(x_i-x_j)^2
Linear algebra

Hadamard (element-wise) product

(A ∘ B)ᵢⱼ = Aᵢⱼ Bᵢⱼ

Schur product theorem: the Hadamard product of two PSD matrices is PSD. Gating in LSTMs and attention masks use it.

Worked example: A = [[1, 2], [3, 4]], B = [[0, 1], [1, 2]] → [[0, 2], [3, 8]] ✓ checked

See also: matrix product (entry)

LaTeX source
(A\circ B)_{ij}=A_{ij}B_{ij}
Linear algebra

Hessian of a quadratic

∇²(½xᵀAx − bᵀx) = A for symmetric A

Convex iff A is positive semi-definite.

Worked example: A = [[2, 1], [1, 3]], b = [1, 1], x = [0.3, -0.2] → [[2, 1], [1, 3]] ✓ checked

See also: gradient of a quadratic form

LaTeX source
\nabla^2\Big(\tfrac12\mathbf x^{\top}A\mathbf x-\mathbf b^{\top}\mathbf x\Big)=\tfrac12(A+A^{\top})
Linear algebra

Householder reflection

H = I − 2vvᵀ/(vᵀv)

Orthogonal and symmetric; used in QR to zero out columns.

Worked example: v = [1, 0], x = [3, 4] → [-3, 4] ✓ checked

See also: QR decomposition

LaTeX source
H=I-2\frac{\mathbf v\mathbf v^{\top}}{\mathbf v^{\top}\mathbf v}
Linear algebra

induced 1- and ∞-norms

‖A‖₁ = max column sum;  ‖A‖∞ = max row sum

Worked example: A = [[1, -2], [3, 4]] → [6, 7] ✓ checked

See also: spectral norm

LaTeX source
\|A\|_1=\max_j\sum_i|a_{ij}|,\qquad \|A\|_\infty=\max_i\sum_j|a_{ij}|
Linear algebra

inverse (2×2)

A⁻¹ = (1/(ad−bc)) · [[d, −b], [−c, a]]

Prefer solving linear systems to forming an inverse numerically.

Worked example: A = [[1, 2], [3, 4]] → [[-2, 1], [1.5, -0.5]] ✓ checked

See also: determinant (2×2)

LaTeX source
\begin{pmatrix}a&b\\c&d\end{pmatrix}^{-1}=\frac{1}{ad-bc}\begin{pmatrix}d&-b\\-c&a\end{pmatrix}
Linear algebra

Jacobi and Gauss–Seidel iteration

xᵢ ← (bᵢ − Σⱼ≠ᵢ aᵢⱼxⱼ)/aᵢᵢ

Guaranteed for strictly diagonally dominant matrices.

Worked example: A = [[4, 1], [2, 5]], b = [9, 12] → [1.83333, 1.66667] ✓ checked

See also: conjugate gradient method · LU decomposition and solving

LaTeX source
x^{(k+1)}_i=\frac1{a_{ii}}\Big(b_i-\sum_{j\ne i}a_{ij}x^{(k)}_j\Big);\qquad \text{converges iff }\rho(M)<1
Linear algebra

Kronecker product

(A ⊗ B)(C ⊗ D) = AC ⊗ BD

(A ⊗ B)⁻¹ = A⁻¹ ⊗ B⁻¹; eigenvalues are products λᵢ(A)μⱼ(B).

Worked example: A = [[1, 2], [0, 1]], B = [[1, 0], [1, 1]], C = [[0, 1], [1, 0]], D = [[2, 0], [0, 1]] → 0 ✓ checked

See also: vec identity · determinant of a Kronecker product

LaTeX source
A\otimes B=\begin{pmatrix}a_{11}B&\cdots&a_{1n}B\\ \vdots&\ddots&\vdots\\ a_{m1}B&\cdots&a_{mn}B\end{pmatrix},\qquad (A\otimes B)(C\otimes D)=AC\otimes BD
Linear algebra

least squares via QR

Rβ = Qᵀy

where X = QR

Avoids squaring the condition number as the normal equations do.

Worked example: X = [[1, 0], [1, 1], [1, 2]], y = [1, 3, 5] → [1, 2] ✓ checked

See also: ordinary least squares (normal equations) · QR decomposition

LaTeX source
\min_\beta\|X\beta-\mathbf y\|\ \Rightarrow\ R\beta=Q^{\top}\mathbf y
Linear algebra

Lp norm

‖x‖ₚ = ( Σ |xᵢ|ᵖ )^(1/p)

where p ≥ 1

p → ∞ gives the max norm.

Worked example: x = [1, 2, 2], p = 3 → 2.57128 ✓ checked

See also: L1 norm (Manhattan) · Euclidean (L2) norm · max (L∞) norm

LaTeX source
\|\mathbf x\|_p=\Big(\sum_i |x_i|^p\Big)^{1/p}
Linear algebra

LU decomposition and solving

PA = LU;  solve Ly = Pb, then Ux = y

O(n³) once, then O(n²) per right-hand side.

Worked example: A = [[2, 1], [1, 3]], b = [3, 5] → [0.8, 1.4] ✓ checked

See also: Cholesky decomposition

LaTeX source
PA=LU,\quad A\mathbf x=\mathbf b\ \Rightarrow\ L\mathbf y=P\mathbf b,\ U\mathbf x=\mathbf y
Linear algebra

Mahalanobis distance

d_M = √((x − μ)ᵀ Σ⁻¹ (x − μ))

Distance in units of standard deviation, accounting for correlations. Σ = I gives the Euclidean distance.

Worked example: x = [2, 1], mu = [0, 0], S = [[4, 0], [0, 1]] → 1.41421 ✓ checked

See also: multivariate normal density · Euclidean (L2) norm

LaTeX source
d_M(\mathbf x,\boldsymbol\mu)=\sqrt{(\mathbf x-\boldsymbol\mu)^{\top}\Sigma^{-1}(\mathbf x-\boldsymbol\mu)}
Linear algebra

matrix determinant lemma

det(A + uvᵀ) = (1 + vᵀA⁻¹u) det A

Worked example: A = [[2, 0], [0, 3]], u = [1, 1], v = [1, 0] → 9 ✓ checked

See also: Sherman–Morrison formula

LaTeX source
\det(A+\mathbf u\mathbf v^{\top})=\big(1+\mathbf v^{\top}A^{-1}\mathbf u\big)\det A
Linear algebra

matrix exponential

e^A = Σ Aᵏ/k!

Solves x′ = Ax: x(t) = e^(tA) x₀.

Worked example: A = [[1, 0], [0, 2]] → [2.71828, 7.38906] ✓ checked

See also: matrix power via eigendecomposition

LaTeX source
e^{A}=\sum_{k=0}^{\infty}\frac{A^k}{k!},\qquad \frac{d}{dt}e^{tA}=Ae^{tA}
Linear algebra

matrix product (entry)

(AB)ᵢⱼ = Σₖ Aᵢₖ Bₖⱼ

where A is m×n, B is n×p, AB is m×p

Not commutative in general.

Worked example: A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]] → 22 ✓ checked

See also: dot product

LaTeX source
(AB)_{ij}=\sum_k A_{ik}B_{kj}
Linear algebra

max (L∞) norm

‖x‖∞ = maxᵢ |xᵢ|

Worked example: x = [1, -7, 3] → 7 ✓ checked

See also: Lp norm

LaTeX source
\|\mathbf x\|_\infty=\max_i |x_i|
Linear algebra

minimiser of a quadratic

x* = A⁻¹b;  f(x*) = −½ bᵀA⁻¹b

where A ≻ 0

Worked example: A = [[2, 1], [1, 3]], b = [1, 2] → [0.2, 0.6, -0.7] ✓ checked

See also: Hessian of a quadratic · conjugate gradient method

LaTeX source
\min_{\mathbf x}\tfrac12\mathbf x^{\top}A\mathbf x-\mathbf b^{\top}\mathbf x\ \Rightarrow\ \mathbf x^*=A^{-1}\mathbf b,\quad f(\mathbf x^*)=-\tfrac12\mathbf b^{\top}A^{-1}\mathbf b
Linear algebra

normalised graph Laplacian

L_sym = I − D^(−1/2) A D^(−1/2)

Eigenvalues in [0, 2]. The GCN propagation matrix is a renormalised version.

Worked example: A = [9 values] → [-1.01113e-16, 1, 2] ✓ checked

See also: graph Laplacian · graph convolution (GCN)

LaTeX source
\mathcal L=I-D^{-1/2}AD^{-1/2}
Linear algebra

nuclear norm

‖A‖_* = Σ σᵢ

The convex surrogate for rank; used in matrix completion.

Worked example: A = [[3, 0], [0, 1]] → 4 ✓ checked

See also: spectral norm · Frobenius norm

LaTeX source
\|A\|_*=\sum_i\sigma_i(A)
Linear algebra

orthogonal matrix

QᵀQ = I;  det Q = ±1;  ‖Qx‖ = ‖x‖

Preserves lengths and angles; all singular values equal 1, so it neither explodes nor vanishes gradients.

Worked example: Q = [[0.6, -0.8], [0.8, 0.6]], x = [3, 4] → 5 ✓ checked

See also: 2-D rotation matrix

LaTeX source
Q^{\top}Q=QQ^{\top}=I,\quad \det Q=\pm1,\quad \|Q\mathbf x\|=\|\mathbf x\|
Linear algebra

orthogonal Procrustes

R = UVᵀ where BAᵀ = UΣVᵀ

The best rotation aligning one point set to another.

Worked example: A = [[1, 0], [0, 1]], B = [[0, -1], [1, 0]] → 0 ✓ checked

See also: singular value decomposition · orthogonal matrix

LaTeX source
\min_{R^{\top}R=I}\|RA-B\|_F\ \Rightarrow\ R=UV^{\top},\quad BA^{\top}=U\Sigma V^{\top}
Linear algebra

orthogonal projection matrix

P = A(AᵀA)⁻¹Aᵀ;  P² = P = Pᵀ

Projects onto the column space of A; I − P projects onto its orthogonal complement.

Worked example: A = [[1, 0], [1, 1], [1, 2]] → 1.11022e-16 ✓ checked

See also: hat matrix and leverage · projection onto a vector

LaTeX source
P=A(A^{\top}A)^{-1}A^{\top},\quad P^2=P=P^{\top}
Linear algebra

PageRank

r = d M r + (1 − d)/N · 1

where M = column-stochastic link matrix, d ≈ 0.85

The stationary distribution of a random surfer who sometimes teleports.

Worked example: M = [[0, 1], [1, 0]], d = 0.85 → [0.5, 0.5] ✓ checked

See also: stationary distribution of a Markov chain · power iteration

LaTeX source
\mathbf r=d\,M\mathbf r+\frac{1-d}{N}\mathbf 1
Linear algebra

parallelogram law

‖x + y‖² + ‖x − y‖² = 2‖x‖² + 2‖y‖²

Holds exactly when the norm comes from an inner product.

Worked example: x = [1, 2], y = [3, -1] → 30 ✓ checked

See also: Euclidean (L2) norm

LaTeX source
\|\mathbf x+\mathbf y\|^2+\|\mathbf x-\mathbf y\|^2=2\|\mathbf x\|^2+2\|\mathbf y\|^2
Linear algebra

Parseval's identity for an orthonormal basis

Σ ⟨x, eᵢ⟩² = ‖x‖²

Energy is preserved by an orthonormal change of basis (and by the unitary DFT).

Worked example: x = [1, 2, 2], Q = [9 values] → 9 ✓ checked

See also: Parseval's theorem (DFT)

LaTeX source
\sum_i\langle\mathbf x,\mathbf e_i\rangle^2=\|\mathbf x\|^2
Linear algebra

Perron–Frobenius theorem

positive matrix ⇒ spectral radius is a simple, positive eigenvalue with a positive eigenvector

Row-stochastic matrices have ρ = 1.

Worked example: P = [[0.9, 0.1], [0.5, 0.5]] → 1 ✓ checked

See also: stationary distribution of a Markov chain

LaTeX source
A>0\ \Rightarrow\ \rho(A)=\lambda_1>0\ \text{simple, with a positive eigenvector}
Linear algebra

power iteration

vₖ₊₁ = Avₖ/‖Avₖ‖

Converges at rate |λ₂/λ₁|. The core of PageRank.

Worked example: A = [[2, 0], [0, 1]] → 2 ✓ checked

See also: Rayleigh quotient · PageRank

LaTeX source
\mathbf v_{k+1}=\frac{A\mathbf v_k}{\|A\mathbf v_k\|}\ \to\ \text{dominant eigenvector}
Linear algebra

principal component analysis

max wᵀΣw  s.t. ‖w‖ = 1  →  w = top eigenvector of Σ

where Σ = covariance matrix

The maximum equals the largest eigenvalue: the variance captured by that direction.

Worked example: S = [[2, 0], [0, 1]] → 2 ✓ checked

See also: eigenvalue equation · singular value decomposition · explained variance ratio

LaTeX source
\max_{\|\mathbf w\|=1}\ \mathbf w^{\top}\Sigma\,\mathbf w\ \Rightarrow\ \mathbf w=\text{top eigenvector of }\Sigma
Linear algebra

projection onto a vector

proj_u(v) = (v·u / u·u) u

Worked example: v = [2, 3], u = [1, 0] → [2, 0] ✓ checked

See also: dot product

LaTeX source
\operatorname{proj}_{\mathbf u}(\mathbf v)=\frac{\mathbf v\cdot\mathbf u}{\mathbf u\cdot\mathbf u}\,\mathbf u
Linear algebra

Pythagorean theorem for orthogonal vectors

x ⊥ y ⇒ ‖x + y‖² = ‖x‖² + ‖y‖²

The reason uncorrelated variances add.

Worked example: x = [3, 0], y = [0, 4] → 25 ✓ checked

See also: dot product

LaTeX source
\mathbf x\perp\mathbf y\ \Rightarrow\ \|\mathbf x+\mathbf y\|^2=\|\mathbf x\|^2+\|\mathbf y\|^2
Linear algebra

QR decomposition

A = QR

The stable way to solve least squares: Rβ = Qᵀy.

Worked example: A = [[1, 2], [3, 4], [5, 6]] → 8.88178e-16 ✓ checked

See also: Cholesky decomposition · least squares via QR

LaTeX source
A=QR\quad(Q^{\top}Q=I,\ R\text{ upper triangular})
Linear algebra

rank–nullity theorem

rank(A) + nullity(A) = n

where n = number of columns

Worked example: A = [[1, 2, 3], [2, 4, 6]] → [1, 2] ✓ checked

See also: singular value decomposition

LaTeX source
\operatorname{rank}(A)+\operatorname{nullity}(A)=n
Linear algebra

Rayleigh quotient

R(x) = xᵀAx / xᵀx

where A symmetric

Its extremes are the extreme eigenvalues; the objective behind PCA.

Worked example: A = [[2, 0], [0, 1]], x = [1, 1] → 1.5 ✓ checked

See also: principal component analysis · power iteration

LaTeX source
R(\mathbf x)=\frac{\mathbf x^{\top}A\mathbf x}{\mathbf x^{\top}\mathbf x},\quad \lambda_{\min}\le R(\mathbf x)\le\lambda_{\max}
Linear algebra

Rodrigues' rotation formula

R = I + sin θ K + (1 − cos θ) K²

where k = unit axis, K = its cross-product matrix

Rotation by θ about an axis in 3-D.

Worked example: th = 1.5708 → [1.11022e-16, 1, 0] ✓ checked

See also: 2-D rotation matrix · cross product and triple product

LaTeX source
R=I+\sin\theta\,K+(1-\cos\theta)K^2,\quad K=[\mathbf k]_\times
Linear algebra

Schatten p-norm

‖A‖_Sp = (Σ σᵢᵖ)^(1/p)

p = 1 nuclear, p = 2 Frobenius, p = ∞ spectral.

Worked example: s = [3, 1], p = 3 → 3.03659 ✓ checked

See also: nuclear norm

LaTeX source
\|A\|_{S_p}=\Big(\sum_i\sigma_i^p\Big)^{1/p}
Linear algebra

Schur complement

det[[A, B], [C, D]] = det(A) det(D − CA⁻¹B)

where D − CA⁻¹B = Schur complement of A

Also appears in block matrix inversion and Gaussian conditioning.

Worked example: A = [[2]], B = [[1]], C = [[1]], D = [[3]] → 8.88178e-16 ✓ checked

See also: multivariate normal: conditional distribution

LaTeX source
\det\begin{pmatrix}A&B\\C&D\end{pmatrix}=\det(A)\,\det\big(D-CA^{-1}B\big)
Linear algebra

Sherman–Morrison formula

(A + uvᵀ)⁻¹ = A⁻¹ − A⁻¹uvᵀA⁻¹ / (1 + vᵀA⁻¹u)

A rank-one update of an inverse in O(n²): the heart of recursive least squares.

Worked example: A = [[2, 0], [0, 3]], u = [1, 1], v = [1, 0] → 5.55112e-17 ✓ checked

See also: Woodbury matrix identity

LaTeX source
(A+\mathbf u\mathbf v^{\top})^{-1}=A^{-1}-\frac{A^{-1}\mathbf u\mathbf v^{\top}A^{-1}}{1+\mathbf v^{\top}A^{-1}\mathbf u}
Linear algebra

singular value decomposition

A = U Σ Vᵀ

where U, V orthogonal; Σ diagonal with σ₁ ≥ σ₂ ≥ … ≥ 0

Best rank-k approximation (Eckart–Young): keep the top k singular values.

Worked example: A = [[1, 2], [3, 4]] → 8.88178e-16 ✓ checked

See also: spectral norm · principal component analysis

LaTeX source
A=U\Sigma V^{\top}
Linear algebra

spectral norm

‖A‖₂ = σ_max(A) = √λ_max(AᵀA)

The largest factor by which A stretches a vector. Bounds the Lipschitz constant of a linear layer.

Worked example: A = [[3, 0], [0, 1]] → 3 ✓ checked

See also: singular value decomposition · Frobenius norm

LaTeX source
\|A\|_2=\sigma_{\max}(A)=\sqrt{\lambda_{\max}(A^\top A)}
Linear algebra

stationary distribution of a Markov chain

πP = π

where P = row-stochastic transition matrix

The left eigenvector for eigenvalue 1. For a two-state chain π = (b, a)/(a + b) with switch rates a, b.

Worked example: P = [[0.9, 0.1], [0.5, 0.5]] → [0.833333, 0.166667] ✓ checked

See also: PageRank · entropy rate of a Markov chain

LaTeX source
\boldsymbol\pi P=\boldsymbol\pi,\quad \sum_i\pi_i=1
Linear algebra

submultiplicativity of matrix norms

‖AB‖ ≤ ‖A‖ ‖B‖

Why the product of layers' spectral norms bounds a network's Lipschitz constant.

Worked example: A = [[1, 2], [0, 1]], B = [[1, 0], [1, 1]] → 0.0419511 ✓ checked

See also: spectral norm · Lipschitz continuity

LaTeX source
\|AB\|\le\|A\|\,\|B\|
Linear algebra

trace

tr(A) = Σ Aᵢᵢ = Σ λᵢ

where λᵢ = eigenvalues

Cyclic: tr(ABC) = tr(BCA).

Worked example: A = [[1, 2], [3, 4]] → 5 ✓ checked

See also: eigenvalue equation

LaTeX source
\operatorname{tr}(A)=\sum_i A_{ii}=\sum_i\lambda_i
Linear algebra

vec identity

vec(AXB) = (Bᵀ ⊗ A) vec(X)

where vec stacks columns

Turns a matrix equation into an ordinary linear system.

Worked example: A = [[1, 2], [3, 4]], X = [[1, 0], [2, 1]], B = [[0, 1], [1, 1]] → 0 ✓ checked

See also: Kronecker product

LaTeX source
\operatorname{vec}(AXB)=\big(B^{\top}\otimes A\big)\operatorname{vec}(X)
Linear algebra

Weyl's eigenvalue perturbation bound

|λᵢ(A + E) − λᵢ(A)| ≤ ‖E‖₂

where A, E symmetric

Eigenvalues of symmetric matrices are well-conditioned.

Worked example: A = [[2, 0], [0, 1]], E = [[0.1, 0], [0, -0.05]] → -8.32667e-17 ✓ checked

See also: spectral norm

LaTeX source
|\lambda_i(A+E)-\lambda_i(A)|\le\|E\|_2
Linear algebra

Woodbury matrix identity

(A + UCV)⁻¹ = A⁻¹ − A⁻¹U(C⁻¹ + VA⁻¹U)⁻¹VA⁻¹

Cheap when the update has low rank k ≪ n. Used in Gaussian processes and Kalman filters.

Worked example: A = [9 values], U = [[1], [0], [1]], C = [[2]], V = [[1, 1, 0]] → 0 ✓ checked

See also: Sherman–Morrison formula

LaTeX source
(A+UCV)^{-1}=A^{-1}-A^{-1}U\big(C^{-1}+VA^{-1}U\big)^{-1}VA^{-1}
Calculus

arithmetic series

Σ (a + kd) = (n/2)(2a + (n − 1)d)

Gauss: 1 + 2 + … + n = n(n + 1)/2.

Worked example: a = 3, d = 2, n = 10 → 120 ✓ checked

See also: sums of powers of integers

LaTeX source
\sum_{k=0}^{n-1}(a+kd)=\frac n2\big(2a+(n-1)d\big)
Calculus

Basel problem and related sums

Σ 1/n² = π²/6;  Σ (−1)ⁿ/(2n + 1) = π/4

Worked example: N = 200000 → [1.64493, 0.785397] ✓ checked

See also: harmonic numbers

LaTeX source
\sum_{n=1}^\infty\frac1{n^2}=\frac{\pi^2}6,\qquad \sum_{n=0}^\infty\frac{(-1)^n}{2n+1}=\frac\pi4
Calculus

Bernoulli's inequality

(1 + x)ⁿ ≥ 1 + nx

Worked example: x = 0.1, n = 5 → 0.11051 ✓ checked

See also: binomial theorem

LaTeX source
(1+x)^n\ge1+nx\quad(x\ge-1,\ n\ge1)
Calculus

beta function

B(x, y) = Γ(x)Γ(y)/Γ(x + y)

Worked example: x = 2, y = 3 → 0.0833333 ✓ checked

See also: gamma function · beta distribution

LaTeX source
B(x,y)=\int_0^1t^{x-1}(1-t)^{y-1}dt=\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}
Calculus

bisection and secant methods

bisection halves the bracket; secant uses a finite-difference slope

Bisection gains one bit per step; secant converges superlinearly (order ≈ 1.618).

Worked example: a = 1, b = 2 → 1.41421 ✓ checked

See also: Newton's method (root finding)

LaTeX source
c=\frac{a+b}2;\qquad x_{n+1}=x_n-f(x_n)\frac{x_n-x_{n-1}}{f(x_n)-f(x_{n-1})}
Calculus

chain rule

d/dx f(g(x)) = f′(g(x)) · g′(x)

Backpropagation is the chain rule applied through a computation graph.

Worked example: x = 1 → 1.0806 ✓ checked

See also: backpropagation (layer error) · Taylor series

LaTeX source
\frac{d}{dx}f(g(x))=f'(g(x))\,g'(x)
Calculus

classic limits

sin x/x → 1;  (1 + 1/n)ⁿ → e;  (eˣ − 1)/x → 1

Worked example: x = 1e-05, n = 1e+07 → [1, 2.71828, 1.00001] ✓ checked

See also: L'Hôpital's rule

LaTeX source
\lim_{x\to0}\frac{\sin x}{x}=1,\quad \lim_{n\to\infty}\Big(1+\frac1n\Big)^n=e,\quad \lim_{x\to0}\frac{e^x-1}{x}=1
Calculus

classical Runge–Kutta (RK4)

yₙ₊₁ = yₙ + (h/6)(k₁ + 2k₂ + 2k₃ + k₄)

Fourth-order accurate: global error O(h⁴).

Worked example: h = 0.1 → 2.71828 ✓ checked

See also: Euler's method

LaTeX source
k_1=f(t,y),\ k_2=f(t+\tfrac h2,y+\tfrac h2k_1),\ k_3=f(t+\tfrac h2,y+\tfrac h2k_2),\ k_4=f(t+h,y+hk_3),\ y_{n+1}=y_n+\tfrac h6(k_1+2k_2+2k_3+k_4)
Calculus

derivatives of exp and log

(eˣ)′ = eˣ;  (aˣ)′ = aˣ ln a;  (ln x)′ = 1/x

Worked example: x = 2, a = 3 → [9.88751, 0.5] ✓ checked

See also: chain rule

LaTeX source
\frac d{dx}e^{x}=e^x,\quad \frac d{dx}a^x=a^x\ln a,\quad \frac d{dx}\ln x=\frac1x,\quad \frac d{dx}\log_ax=\frac1{x\ln a}
Calculus

derivatives of hyperbolic functions

(sinh)′ = cosh;  (cosh)′ = sinh;  (tanh)′ = 1 − tanh²

The tanh derivative is why tanh activations saturate.

Worked example: x = 0.7 → [1.25517, 0.758584, 0.63474] ✓ checked

See also: hyperbolic tangent

LaTeX source
(\sinh x)'=\cosh x,\quad (\cosh x)'=\sinh x,\quad (\tanh x)'=1-\tanh^2x=\operatorname{sech}^2x
Calculus

derivatives of trigonometric functions

(sin x)′ = cos x;  (cos x)′ = −sin x;  (tan x)′ = sec² x;  (arctan x)′ = 1/(1 + x²)

Worked example: x = 0.5 → [0.877583, -0.479426, 1.29845, 1.1547, 0.8] ✓ checked

See also: chain rule

LaTeX source
(\sin x)'=\cos x,\ (\cos x)'=-\sin x,\ (\tan x)'=\sec^2x,\ (\arcsin x)'=\frac1{\sqrt{1-x^2}},\ (\arctan x)'=\frac1{1+x^2}
Calculus

directional derivative

D_u f = ∇f · u

Steepest ascent is along ∇f with rate ‖∇f‖.

Worked example: g = [3, 4], u = [0.6, 0.8] → 5 ✓ checked

See also: gradient, divergence and curl

LaTeX source
D_{\mathbf u}f=\nabla f\cdot\mathbf u,\quad \|\mathbf u\|=1
Calculus

divergence theorem and Stokes' theorem

∭ ∇·F dV = ∯ F·dS;  ∬ (∇×F)·dS = ∮ F·dr

Green's theorem is the planar case.

Worked example: R = 1 → 3.14159 ✓ checked

See also: gradient, divergence and curl

LaTeX source
\iiint_V\nabla\!\cdot\mathbf F\,dV=\oint_{\partial V}\mathbf F\cdot d\mathbf S,\qquad \iint_S(\nabla\times\mathbf F)\cdot d\mathbf S=\oint_{\partial S}\mathbf F\cdot d\mathbf r
Calculus

error function

erf(x) = (2/√π) ∫₀ˣ e^(−t²) dt

Worked example: x = 1 → 0.842701 ✓ checked

See also: normal cumulative distribution

LaTeX source
\operatorname{erf}(x)=\frac2{\sqrt\pi}\int_0^xe^{-t^2}dt,\qquad \Phi(x)=\tfrac12\big[1+\operatorname{erf}(x/\sqrt2)\big]
Calculus

Euler's method

yₙ₊₁ = yₙ + h f(tₙ, yₙ)

First-order accurate: global error O(h).

Worked example: h = 0.1 → 2.59374 ✓ checked

See also: classical Runge–Kutta (RK4)

LaTeX source
y_{n+1}=y_n+h\,f(t_n,y_n)
Calculus

Euler–Maclaurin formula

Σ f(k) = ∫ f + (f(a) + f(b))/2 + (1/12)(f′(b) − f′(a)) − …

Links sums and integrals; the trapezoid rule with correction terms from Bernoulli numbers. The series is asymptotic, so start the sum where f is smooth.

Worked example: a = 10, b = 100 → 0.0952165 ✓ checked

See also: trapezoid and Simpson's rules

LaTeX source
\sum_{k=a}^{b}f(k)=\int_a^bf(x)\,dx+\frac{f(a)+f(b)}2+\frac1{12}\big(f^{(1)}(b)-f^{(1)}(a)\big)-\frac1{720}\big(f^{(3)}(b)-f^{(3)}(a)\big)+\cdots
Calculus

finite differences

forward, central and second differences

Gradient checking in deep learning uses the central difference with h ≈ 1e-5.

Worked example: x = 1, h = 0.0001 → [2.71828, 2.71828] ✓ checked

See also: Richardson extrapolation

LaTeX source
f'(x)\approx\frac{f(x+h)-f(x)}h\ (O(h)),\quad \frac{f(x+h)-f(x-h)}{2h}\ (O(h^2)),\quad f''(x)\approx\frac{f(x+h)-2f(x)+f(x-h)}{h^2}
Calculus

first-order linear ODE

integrating factor μ = e^(∫p dx)

Worked example: k = -0.5, y0 = 2, t = 2 → 0.735757 ✓ checked

See also: second-order linear ODE with constant coefficients

LaTeX source
y'+p(x)y=q(x)\ \Rightarrow\ y=\frac1\mu\Big(\int\mu q\,dx+C\Big),\ \ \mu=e^{\int p\,dx};\qquad y'=ky\Rightarrow y=y_0e^{kt}
Calculus

Fourier transform pairs

f̂(ξ) = ∫ f(x) e^(−2πixξ) dx;  Gaussian ↔ Gaussian;  box ↔ sinc

A narrow function has a wide spectrum (uncertainty principle).

Worked example: xi = 0.5 → 0.455938 ✓ checked

See also: discrete Fourier transform · convolution theorem

LaTeX source
\hat f(\xi)=\int f(x)e^{-2\pi ix\xi}dx;\quad e^{-\pi x^2}\leftrightarrow e^{-\pi\xi^2};\ \ \mathbf 1_{[-\frac12,\frac12]}\leftrightarrow\operatorname{sinc}(\xi)
Calculus

fundamental theorem of calculus

∫ₐᵇ f′ = f(b) − f(a)

Worked example: a = 0, b = 1 → 1 ✓ checked

See also: integration by parts

LaTeX source
\int_a^bf'(x)\,dx=f(b)-f(a),\qquad \frac d{dx}\int_a^xf(t)\,dt=f(x)
Calculus

gamma function

Γ(z) = ∫ t^(z−1) e^(−t) dt;  Γ(z + 1) = zΓ(z);  Γ(n) = (n − 1)!

The factorial for real numbers.

Worked example: z = 3.5 → 3.32335 ✓ checked

See also: beta function · Stirling's approximation

LaTeX source
\Gamma(z)=\int_0^\infty t^{z-1}e^{-t}\,dt,\quad \Gamma(z+1)=z\,\Gamma(z),\quad \Gamma(n)=(n-1)!,\quad \Gamma(\tfrac12)=\sqrt\pi
Calculus

Gaussian integrals

∫ e^(−ax²) dx = √(π/a);  ∫ x² e^(−ax²) dx = √π/(2a^(3/2))

Worked example: a = 2 → [1.25331, 0.313329] ✓ checked

See also: Gaussian integral

LaTeX source
\int_{-\infty}^{\infty}e^{-ax^2}dx=\sqrt{\frac\pi a},\quad \int_{-\infty}^{\infty}x^2e^{-ax^2}dx=\frac{\sqrt\pi}{2a^{3/2}}
Calculus

generalised binomial series

(1 + x)^α = Σ C(α, k) xᵏ

First-order: (1 + x)^α ≈ 1 + αx.

Worked example: x = 0.2, a = 0.5 → 1.09545 ✓ checked

See also: binomial theorem

LaTeX source
(1+x)^\alpha=\sum_{k=0}^{\infty}\binom\alpha kx^k\quad(|x|<1),\qquad \binom\alpha k=\frac{\alpha(\alpha-1)\cdots(\alpha-k+1)}{k!}
Calculus

gradient, divergence and curl

∇f, ∇·F, ∇×F

Laplacian: ∇²f = ∇·∇f.

Worked example: x = 1, y = 2 → 6 ✓ checked

See also: divergence theorem and Stokes' theorem

LaTeX source
\nabla f=\Big(\frac{\partial f}{\partial x_i}\Big),\quad \nabla\!\cdot\mathbf F=\sum_i\frac{\partial F_i}{\partial x_i},\quad \nabla\times\mathbf F=\Big(\partial_yF_z-\partial_zF_y,\ \partial_zF_x-\partial_xF_z,\ \partial_xF_y-\partial_yF_x\Big)
Calculus

harmonic numbers

Hₙ = Σ 1/k ≈ ln n + γ + 1/(2n)

Diverges, but only logarithmically. The coupon-collector expectation is nHₙ.

Worked example: n = 1000 → 7.48547 ✓ checked

See also: coupon collector

LaTeX source
H_n=\sum_{k=1}^n\frac1k\approx\ln n+\gamma+\frac1{2n},\quad \gamma\approx0.5772
Calculus

Hessian matrix and second-derivative test

Hᵢⱼ = ∂²f/∂xᵢ∂xⱼ;  ∇f = 0 and H ≻ 0 ⇒ local minimum

Eigenvalues of H give the curvature along principal directions; a mix of signs means a saddle.

Worked example: x = 1, y = 2 → [4, 2, 12] ✓ checked

See also: Newton's method (multivariate)

LaTeX source
H_{ij}=\frac{\partial^2f}{\partial x_i\partial x_j};\quad \nabla f=0,\ H\succ0\Rightarrow\text{local minimum}
Calculus

implicit differentiation

dy/dx = −F_x/F_y

Worked example: x = 3, y = 4 → -0.75 ✓ checked

See also: chain rule

LaTeX source
F(x,y)=0\ \Rightarrow\ \frac{dy}{dx}=-\frac{F_x}{F_y}
Calculus

integral of a power

∫ xⁿ dx = xⁿ⁺¹/(n + 1) + C;  ∫ dx/x = ln|x| + C

Worked example: a = 1, b = 3, n = 2 → [8.66667, 1.09861] ✓ checked

See also: integrals of exp and trigonometric functions

LaTeX source
\int x^n\,dx=\frac{x^{n+1}}{n+1}+C\ (n\ne-1),\qquad \int\frac{dx}{x}=\ln|x|+C
Calculus

integrals of exp and trigonometric functions

∫ e^(ax) = e^(ax)/a;  ∫ sin = −cos;  ∫ cos = sin;  ∫ 1/(1 + x²) = arctan x

Worked example: b = 1 → [3.19453, 0.459698, 0.841471, 0.785398] ✓ checked

See also: integral of a power

LaTeX source
\int e^{ax}dx=\frac{e^{ax}}a,\ \int\sin x\,dx=-\cos x,\ \int\cos x\,dx=\sin x,\ \int\frac{dx}{1+x^2}=\arctan x
Calculus

Jacobian matrix

Jᵢⱼ = ∂fᵢ/∂xⱼ

The best linear approximation of a vector function; backpropagation multiplies Jacobians.

Worked example: x = 1, y = 2 → [[2, 1], [1, 4]] ✓ checked

See also: multivariable chain rule

LaTeX source
J_{ij}=\frac{\partial f_i}{\partial x_j}
Calculus

L'Hôpital's rule

lim f/g = lim f′/g′

Worked example: x = 0.0001 → 0.5 ✓ checked

See also: classic limits

LaTeX source
\lim_{x\to a}\frac{f(x)}{g(x)}=\lim_{x\to a}\frac{f'(x)}{g'(x)}\quad\text{(for }0/0\text{ or }\infty/\infty)
Calculus

Lagrange interpolation

p(x) = Σ yᵢ Π_{j≠i} (x − xⱼ)/(xᵢ − xⱼ)

The unique degree-n polynomial through n + 1 points.

Worked example: xs = [0, 1, 2], ys = [1, 3, 7], x = 3 → 13 ✓ checked

See also: Newton divided differences

LaTeX source
p(x)=\sum_{i}y_i\prod_{j\ne i}\frac{x-x_j}{x_i-x_j}
Calculus

Laplace transform pairs

L{1} = 1/s;  L{eᵃᵗ} = 1/(s − a);  L{tⁿ} = n!/sⁿ⁺¹;  L{sin ωt} = ω/(s² + ω²)

Worked example: s = 2 → [0.5, 0.25, 0.230769] ✓ checked

See also: first-order linear ODE

LaTeX source
\mathcal L\{f\}(s)=\int_0^\infty f(t)e^{-st}dt;\ \ \mathcal L\{1\}=\frac1s,\ \mathcal L\{e^{at}\}=\frac1{s-a},\ \mathcal L\{t^n\}=\frac{n!}{s^{n+1}},\ \mathcal L\{\sin\omega t\}=\frac\omega{s^2+\omega^2}
Calculus

Leibniz integral rule

differentiate under the integral sign

Worked example: t = 1 → -0.26426 ✓ checked

See also: fundamental theorem of calculus

LaTeX source
\frac d{dt}\int_{a(t)}^{b(t)}f(x,t)\,dx=f(b,t)b'-f(a,t)a'+\int_{a}^{b}\frac{\partial f}{\partial t}dx
Calculus

mean value theorem

f′(c) = (f(b) − f(a))/(b − a)

Worked example: a = 0, b = 2 → 2 ✓ checked

See also: Taylor series

LaTeX source
f'(c)=\frac{f(b)-f(a)}{b-a}\ \text{for some }c\in(a,b)
Calculus

Minkowski inequality (triangle inequality in Lp)

‖f + g‖_p ≤ ‖f‖_p + ‖g‖_p

Worked example: x = [1, -2, 3], y = [2, 1, -1], p = 3 → 2.15443 ✓ checked

See also: Lp norm

LaTeX source
\|f+g\|_p\le\|f\|_p+\|g\|_p\quad(p\ge1)
Calculus

multivariable chain rule

∂z/∂t = Σ (∂z/∂xᵢ)(∂xᵢ/∂t);  J_{f∘g} = J_f J_g

Worked example: t = 1 → 10.3781 ✓ checked

See also: Jacobian matrix · chain rule

LaTeX source
\frac{\partial z}{\partial t}=\sum_i\frac{\partial z}{\partial x_i}\frac{\partial x_i}{\partial t},\qquad J_{f\circ g}=J_f(g)\,J_g
Calculus

natural cubic spline conditions

piecewise cubics with continuous value, slope and curvature

Worked example: h = 1 → 1 ✓ checked

See also: Lagrange interpolation

LaTeX source
S\in C^2,\ \ S_i(x_i)=y_i,\ \ S''(x_0)=S''(x_n)=0
Calculus

Newton divided differences

p(x) = f[x₀] + f[x₀,x₁](x − x₀) + …

Worked example: x = 3 → 13 ✓ checked

See also: Lagrange interpolation

LaTeX source
p(x)=f[x_0]+f[x_0,x_1](x-x_0)+f[x_0,x_1,x_2](x-x_0)(x-x_1)+\cdots,\quad f[x_i,x_j]=\frac{f_j-f_i}{x_j-x_i}
Calculus

Newton's method (root finding)

xₙ₊₁ = xₙ − f(xₙ)/f′(xₙ)

For minimisation apply it to f′: x ← x − f′/f″. Converges quadratically near a simple root.

Worked example: x = 1 → 1.5 ✓ checked

See also: Taylor series

LaTeX source
x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}
Calculus

power rule

d/dx xⁿ = n xⁿ⁻¹

Holds for any real n.

Worked example: x = 2, n = 3 → 12 ✓ checked

See also: product rule

LaTeX source
\frac{d}{dx}x^n=n\,x^{n-1}
Calculus

product rule

(fg)′ = f′g + fg′

Worked example: x = 1 → 2.22324 ✓ checked

See also: quotient rule · chain rule

LaTeX source
(fg)'=f'g+fg'
Calculus

quotient rule

(f/g)′ = (f′g − fg′)/g²

Worked example: x = 1 → -0.150584 ✓ checked

See also: product rule

LaTeX source
\Big(\frac fg\Big)'=\frac{f'g-fg'}{g^2}
Calculus

ratio and root tests

L = lim |aₙ₊₁/aₙ| : L < 1 converges, L > 1 diverges

Worked example: n = 20 → 0.047619 ✓ checked

See also: geometric series

LaTeX source
L=\lim\Big|\frac{a_{n+1}}{a_n}\Big|\ \text{or}\ \lim|a_n|^{1/n}:\ L<1\Rightarrow\text{converges},\ L>1\Rightarrow\text{diverges}
Calculus

Richardson extrapolation

D ≈ (4D(h/2) − D(h))/3

Worked example: x = 1, h = 0.1 → 2.71828 ✓ checked

See also: finite differences

LaTeX source
D\approx\frac{4D(h/2)-D(h)}{3}\quad(\text{cancels the }h^2\text{ term})
Calculus

second-order linear ODE with constant coefficients

characteristic roots r = (−b ± √(b² − 4ac))/2a

Complex roots α ± iβ give e^(αx)(C₁ cos βx + C₂ sin βx): damped oscillation.

Worked example: a = 1, b = 0, c = 4, x = 1 → -0.416151 ✓ checked

See also: first-order linear ODE

LaTeX source
ay''+by'+cy=0:\ r=\frac{-b\pm\sqrt{b^2-4ac}}{2a};\ \ y=C_1e^{r_1x}+C_2e^{r_2x}
Calculus

standard Taylor (Maclaurin) series

eˣ, sin, cos, ln(1 + x), 1/(1 − x), (1 + x)^α

ln(1 + x) and 1/(1 − x) need |x| < 1; the others hold for all x.

Worked example: x = 0.3 → [1.34986, 0.29552, 0.955336, 0.262364, 1.42857] ✓ checked

See also: Taylor series

LaTeX source
e^x=\sum\frac{x^n}{n!},\ \sin x=\sum\frac{(-1)^nx^{2n+1}}{(2n+1)!},\ \cos x=\sum\frac{(-1)^nx^{2n}}{(2n)!},\ \ln(1+x)=\sum\frac{(-1)^{n+1}x^n}{n},\ \frac1{1-x}=\sum x^n
Calculus

sums of powers of integers

Σk = n(n+1)/2;  Σk² = n(n+1)(2n+1)/6;  Σk³ = (n(n+1)/2)²

Worked example: n = 10 → [55, 385, 3025] ✓ checked

See also: arithmetic series

LaTeX source
\sum_{k=1}^nk=\frac{n(n+1)}2,\quad \sum k^2=\frac{n(n+1)(2n+1)}6,\quad \sum k^3=\Big(\frac{n(n+1)}2\Big)^2
Calculus

Taylor remainder (Lagrange form)

Rₙ(x) = f⁽ⁿ⁺¹⁾(ξ)/(n + 1)! · (x − a)ⁿ⁺¹

Bounds the error of a Taylor polynomial.

Worked example: x = 0.5, n = 3 → 0.00288794 ✓ checked

See also: Taylor series

LaTeX source
R_n(x)=\frac{f^{(n+1)}(\xi)}{(n+1)!}(x-a)^{n+1}\ \text{for some }\xi\text{ between }a,x
Calculus

Taylor series

f(x) ≈ Σₙ f⁽ⁿ⁾(a) (x−a)ⁿ / n!

where expansion about a

Remainder is O((x−a)^(N+1)).

Worked example: x = 0.5 → 1.64844 ✓ checked

See also: chain rule · Newton's method (root finding)

LaTeX source
f(x)\approx\sum_{n=0}^{N}\frac{f^{(n)}(a)}{n!}(x-a)^n
Calculus

trapezoid and Simpson's rules

trapezoid: h/2 [f₀ + 2Σfᵢ + fₙ];  Simpson: h/3 [f₀ + 4f₁ + 2f₂ + … + fₙ]

Errors O(h²) and O(h⁴).

Worked example: n = 10 → 1.71828 ✓ checked

See also: Euler–Maclaurin formula

LaTeX source
\int_a^bf\approx\frac h2\Big[f(a)+2\sum_{i=1}^{n-1}f(x_i)+f(b)\Big],\qquad \int_a^bf\approx\frac h3\Big[f_0+4f_1+2f_2+\cdots+4f_{n-1}+f_n\Big]
Calculus

useful exponential inequalities

1 + x ≤ eˣ;  ln x ≤ x − 1

Used constantly in proofs of concentration bounds.

Worked example: x = 0.5 → [0.148721, 0.193147] ✓ checked

See also: Jensen's inequality

LaTeX source
1+x\le e^x,\qquad \ln x\le x-1,\qquad e^x\ge1+x+\tfrac{x^2}2\ (x\ge0),\qquad 1-x\le e^{-x}
Calculus

Wallis product

π/2 = Π 4n²/(4n² − 1)

Worked example: N = 100000 → 1.57079 ✓ checked

See also: Basel problem and related sums

LaTeX source
\frac\pi2=\prod_{n=1}^{\infty}\frac{4n^2}{4n^2-1}
Calculus

Young's inequality

ab ≤ aᵖ/p + bᵠ/q

p = q = 2 gives ab ≤ (a² + b²)/2.

Worked example: a = 2, b = 3, p = 3, q = 1.5 → 0.130768 ✓ checked

See also: Cauchy–Schwarz and Hölder inequalities

LaTeX source
ab\le\frac{a^p}p+\frac{b^q}q\quad\Big(\frac1p+\frac1q=1\Big)
Numerical methods

Amdahl's law

S = 1/((1 − p) + p/s)

where p = parallelisable fraction, s = speed-up of that part

The serial fraction caps the speed-up at 1/(1 − p).

Worked example: p = 0.9, s = 10 → 5.26316 ✓ checked

See also: Gustafson's law

LaTeX source
S=\frac1{(1-p)+p/s}
Numerical methods

antithetic variates

average f(U) and f(1 − U)

Reduces variance when f is monotone, since the pair is negatively correlated.

Worked example: u = 0.2 → 1.72347 ✓ checked

See also: control variates

LaTeX source
\hat\theta=\frac1{2N}\sum_i\big[f(U_i)+f(1-U_i)\big]
Numerical methods

Bayes error and optimal classifier

h*(x) = argmax P(y = k | x);  R* = 1 − E max P(y|x)

No classifier can beat it.

Worked example: p = [0.9, 0.6, 0.8] → 0.233333 ✓ checked

See also: Bayes' theorem

LaTeX source
h^*(x)=\arg\max_kP(y=k\mid x),\qquad R^*=1-\mathbb E_x\Big[\max_kP(y=k\mid x)\Big]
Numerical methods

Box–Muller transform

Z₀ = √(−2 ln U₁) cos(2πU₂),  Z₁ = √(−2 ln U₁) sin(2πU₂)

where U₁, U₂ ~ Uniform(0, 1)

Two independent standard normals from two uniforms.

Worked example: u1 = 0.5, u2 = 0 → 1.17741 ✓ checked

See also: inverse-transform sampling

LaTeX source
Z_0=\sqrt{-2\ln U_1}\,\cos(2\pi U_2),\qquad Z_1=\sqrt{-2\ln U_1}\,\sin(2\pi U_2)
Numerical methods

condition number of a function

κ = |x f′(x)/f(x)|

How much a relative input error is amplified. √x has κ = ½; subtracting nearby numbers has huge κ.

Worked example: x = 4 → 0.5 ✓ checked

See also: condition number

LaTeX source
\kappa_f(x)=\Big|\frac{x\,f'(x)}{f(x)}\Big|,\qquad \frac{\delta f}{f}\approx\kappa_f\frac{\delta x}x
Numerical methods

control variates

variance shrinks by a factor (1 − ρ²)

Worked example: rho = 0.9 → 0.19 ✓ checked

See also: antithetic variates

LaTeX source
\hat\theta=\bar Y-c\big(\bar Z-\mathbb E Z\big),\ \ c^*=\frac{\operatorname{Cov}(Y,Z)}{\operatorname{Var}Z},\ \ \operatorname{Var}\hat\theta=(1-\rho^2)\operatorname{Var}\bar Y
Numerical methods

cosine distance and angular distance

d = 1 − cos θ

Not a metric (no triangle inequality); angular distance is.

Worked example: x = [1, 0], y = [1, 1] → 0.292893 ✓ checked

See also: cosine similarity

LaTeX source
d_{\cos}=1-\cos\theta,\qquad d_{\text{ang}}=\frac{\arccos(\cos\theta)}\pi
Numerical methods

effective sample size

ESS = (Σwᵢ)²/Σwᵢ²

N when the weights are equal, 1 when one weight dominates.

Worked example: w = [1, 1, 1, 1] → 4 ✓ checked

See also: importance sampling

LaTeX source
\mathrm{ESS}=\frac{\big(\sum_iw_i\big)^2}{\sum_iw_i^2}
Numerical methods

FFT complexity

DFT O(N²) → FFT O(N log₂ N)

Worked example: N = 1024 → [1.04858e+06, 10240] ✓ checked

See also: discrete Fourier transform

LaTeX source
\text{DFT: }O(N^2)\ \ \longrightarrow\ \ \text{FFT: }O(N\log_2N)
Numerical methods

floating-point formats

x = (−1)ˢ (1.m)₂ 2^(e − bias)

bfloat16 keeps float32's range with less precision, which is why it needs no loss scaling.

Worked example → [65504, 3.40282e+38] ✓ checked

See also: machine epsilon and floating-point precision

LaTeX source
x=(-1)^s\,(1.m)_2\,2^{e-\text{bias}};\quad \text{float16: 1+5+10 bits, max }65504;\ \ \text{bfloat16: 1+8+7 bits;}\ \ \text{float32: 1+8+23}
Numerical methods

Gelman–Rubin R̂

R̂ = √((n − 1)/n + B/(nW))

where B = between-chain variance, W = within-chain variance, n = chain length

Values close to 1 (below about 1.01) indicate convergence.

Worked example: n = 1000, B = 0.5, W = 1 → 0.99975 ✓ checked

See also: MCMC effective sample size

LaTeX source
\hat R=\sqrt{\frac{n-1}n+\frac{B}{nW}}
Numerical methods

Gustafson's law

S = (1 − p) + pN

where N = processors, p = parallel fraction of the scaled workload

Worked example: p = 0.9, N = 100 → 90.1 ✓ checked

See also: Amdahl's law

LaTeX source
S=(1-p)+pN
Numerical methods

Hamiltonian Monte Carlo leapfrog step

half-step momentum, full-step position, half-step momentum

where U = −log π

Reversible and volume-preserving; the accept step corrects the small energy error.

Worked example: q = 1, p = 0, e = 0.1 → [0.995, -0.09975] ✓ checked

See also: Metropolis–Hastings acceptance · Langevin dynamics

LaTeX source
p\leftarrow p-\tfrac\varepsilon2\nabla U(q),\quad q\leftarrow q+\varepsilon p,\quad p\leftarrow p-\tfrac\varepsilon2\nabla U(q)
Numerical methods

Hamming distance

d_H = number of positions where a and b differ

Worked example: a = 'karolin', b = 'kathrin' → 3 ✓ checked

See also: Levenshtein distance recurrence

LaTeX source
d_H(a,b)=\sum_i\mathbf 1[a_i\ne b_i]
Numerical methods

histogram bin width rules

k = ⌈log₂ n⌉ + 1;  h = 2 IQR n^(−1/3)

Worked example: n = 1000, iqr = 2 → [11, 0.4] ✓ checked

See also: kernel density estimate and Silverman's rule

LaTeX source
\text{Sturges: }k=\lceil\log_2n\rceil+1,\qquad \text{Freedman–Diaconis: }h=2\,\mathrm{IQR}\,n^{-1/3}
Numerical methods

importance sampling

E_p[f] ≈ (1/N) Σ f(xᵢ) p(xᵢ)/q(xᵢ)

where q must cover the support of p·f

The self-normalised form divides by Σw. Off-policy RL uses the same trick.

Worked example: x = [0.5, 1.5, 2.5], w = [0.5, 1, 2] → 2.25 ✓ checked

See also: effective sample size · Horvitz–Thompson estimator

LaTeX source
\mathbb E_p[f]=\mathbb E_q\Big[f(x)\frac{p(x)}{q(x)}\Big]\approx\frac1N\sum_if(x_i)\,w_i,\quad w_i=\frac{p(x_i)}{q(x_i)}
Numerical methods

kernel density estimate and Silverman's rule

f̂(x) = (1/nh) Σ K((x − xᵢ)/h)

where K = kernel, e.g. Gaussian

Worked example: x = [0, 1], pt = 0.5, h = 0.5 → 0.483941 ✓ checked

See also: histogram bin width rules

LaTeX source
\hat f(x)=\frac1{nh}\sum_iK\Big(\frac{x-x_i}h\Big),\qquad h=0.9\min\Big(\hat\sigma,\frac{\mathrm{IQR}}{1.34}\Big)n^{-1/5}
Numerical methods

Langevin dynamics

x ← x − (ε/2)∇U(x) + √ε ξ

Samples from exp(−U); the score-based view of diffusion models uses ∇log p in place of −∇U.

Worked example: x = 1, e = 0.01, noise = 0 → 0.995 ✓ checked

See also: Hamiltonian Monte Carlo leapfrog step · denoising score matching

LaTeX source
x_{k+1}=x_k-\tfrac\varepsilon2\nabla U(x_k)+\sqrt\varepsilon\,\xi_k,\quad \xi_k\sim\mathcal N(0,I)
Numerical methods

machine epsilon and floating-point precision

ε = 2^(−52) (float64), 2^(−23) (float32), 2^(−10) (float16)

The gap between 1 and the next representable number. Relative rounding error is at most ε/2.

Worked example → [2.22045e-16, 1.19209e-07, 0.000976562] ✓ checked

See also: catastrophic cancellation and stable rewrites

LaTeX source
\epsilon_{\text{mach}}=2^{-p+1}:\ \ \text{float64 }2^{-52}\approx2.2\times10^{-16},\ \ \text{float32 }2^{-23}\approx1.2\times10^{-7},\ \ \text{float16 }2^{-10}\approx9.8\times10^{-4}
Numerical methods

matrix-multiplication cost

FLOPs = 2·m·n·p

A multiply and an add per term. Strassen: O(n^{log₂7}) ≈ O(n^{2.807}).

Worked example: m = 1024, n = 4096, p = 4096 → 3.43597e+10 ✓ checked

See also: transformer parameter count

LaTeX source
\text{FLOPs}(A_{m\times n}B_{n\times p})=2mnp
Numerical methods

min–max, standardisation and robust scaling

min–max to [0, 1];  z-score;  robust scaling

Fit the statistics on the training set only.

Worked example: x = [2, 4, 6, 10] → [0.5, 0.169031] ✓ checked

See also: z-score · interquartile range

LaTeX source
x'=\frac{x-x_{\min}}{x_{\max}-x_{\min}},\qquad z=\frac{x-\mu}\sigma,\qquad x'=\frac{x-\operatorname{median}}{\mathrm{IQR}}
Numerical methods

Monte Carlo standard error

SE = σ/√N

Error falls as N^(−½) whatever the dimension: ten times the accuracy costs a hundred times the samples.

Worked example: s = 2, N = 10000 → 0.02 ✓ checked

See also: standard error of the mean

LaTeX source
\mathrm{SE}=\frac\sigma{\sqrt N}
Numerical methods

rejection sampling

accept if u ≤ f(x)/(M g(x));  acceptance rate = 1/M

where f ≤ M g everywhere

Worked example: M = 2.5 → 0.4 ✓ checked

See also: importance sampling

LaTeX source
\text{draw }x\sim g,\ u\sim\mathrm U(0,1);\ \text{accept if }u\le\frac{f(x)}{M\,g(x)};\qquad \text{acceptance rate}=\frac1M
Numerical methods

reservoir sampling

P(item in sample) = k/n

Keep item i with probability k/i, replacing a random slot: uniform sample of a stream of unknown length.

Worked example: k = 10, n = 1000 → 0.01 ✓ checked

See also: Monte Carlo standard error

LaTeX source
P(\text{item }i\text{ is in the sample of size }k)=\frac kn
Numerical methods

roofline model

P = min(P_peak, β·I)

where β = memory bandwidth, I = arithmetic intensity

Below the ridge point a kernel is memory-bound; above it compute-bound.

Worked example: peak = 1e+14, bw = 2e+12, I = 25 → 5e+13 ✓ checked

See also: matrix-multiplication cost

LaTeX source
P=\min\big(P_{\text{peak}},\ \beta\cdot I\big),\qquad I=\frac{\text{FLOPs}}{\text{bytes moved}}
Numerical methods

simple and weighted moving average

average of the last w values

An FIR low-pass filter. Exponential smoothing weights recent values more.

Worked example: x = [1, 2, 3, 4, 5], w = 3 → 4 ✓ checked

See also: simple exponential smoothing · FIR and IIR filters

LaTeX source
\mathrm{SMA}_t=\frac1w\sum_{i=0}^{w-1}x_{t-i},\qquad \mathrm{WMA}_t=\frac{\sum_iw_ix_{t-i}}{\sum_iw_i}
Numerical methods

stable softmax and log-sum-exp

subtract max(z) before exponentiating

Without it, exp(1000) overflows to infinity.

Worked example: z = [1000, 999] → [0.731059, 0.268941] ✓ checked

See also: log-sum-exp · softmax

LaTeX source
\operatorname{softmax}(z)_i=\frac{e^{z_i-m}}{\sum_je^{z_j-m}},\qquad \operatorname{LSE}(z)=m+\ln\sum_je^{z_j-m},\quad m=\max_jz_j
Signal processing

analytic signal and envelope

envelope = |x + jH{x}|

Worked example: t = 0.3 → 1 ✓ checked

See also: discrete Fourier transform

LaTeX source
x_a(t)=x(t)+j\mathcal H\{x\}(t),\qquad \text{envelope}=|x_a(t)|,\quad \text{phase}=\arg x_a
Signal processing

bandpass sampling

2f_H/n ≤ fs ≤ 2f_L/(n − 1)

Worked example: fh = 25, fl = 20, n = 4 → [12.5, 13.3333] ✓ checked

See also: Nyquist rate and aliasing

LaTeX source
\frac{2f_H}{n}\le f_s\le\frac{2f_L}{n-1},\quad 1\le n\le\Big\lfloor\frac{f_H}{B}\Big\rfloor
Signal processing

bilinear transform

s = (2/T)(z − 1)/(z + 1)

Maps the analogue left half-plane into the unit disc, preserving stability.

Worked example: T = 0.1, z = 0.9 → -1.05263 ✓ checked

See also: z-transform and stability

LaTeX source
s=\frac2T\,\frac{z-1}{z+1}
Signal processing

Butterworth magnitude response

|H|² = 1/(1 + (ω/ωc)^(2n))

Maximally flat in the pass band; −3 dB at ωc.

Worked example: w = 2, wc = 1, n = 2 → 0.0588235 ✓ checked

See also: first-order low-pass filter

LaTeX source
|H(j\omega)|^2=\frac1{1+(\omega/\omega_c)^{2n}}
Signal processing

convolution theorem

DFT(f ∗ g) = DFT(f) · DFT(g)  (circular convolution)

FFT convolution costs O(N log N) instead of O(N²).

Worked example: f = [1, 2, 3, 0], g = [0, 1, 0.5, 0] → 0 ✓ checked

See also: discrete convolution · discrete Fourier transform

LaTeX source
\mathcal F\{f*g\}=\mathcal F\{f\}\cdot\mathcal F\{g\}
Signal processing

cross-correlation

r_xy[k] = Σ x[n] y[n + k]

The peak lag gives the delay between two signals. Wiener–Khinchin: the PSD is the Fourier transform of the autocorrelation.

Worked example: x = [1, 2, 3], y = [0, 1, 2], k = 1 → 5 ✓ checked

See also: autocorrelation function · matched filter

LaTeX source
r_{xy}[k]=\sum_nx[n]\,y[n+k]
Signal processing

DFT frequency bins

Δf = fs/N;  fₖ = kΔf

Zero-padding interpolates the spectrum but does not add resolution.

Worked example: fs = 44100, N = 4096, k = 100 → [10.7666, 1076.66] ✓ checked

See also: short-time Fourier transform

LaTeX source
\Delta f=\frac{f_s}N,\qquad f_k=k\,\Delta f
Signal processing

FIR and IIR filters

y[n] = Σ bₖ x[n − k] (− Σ aₖ y[n − k] for IIR)

FIR filters are always stable and can have linear phase.

Worked example: b = [0.5, 0.5], x = [1, 3, 5] → [0.5, 2, 4] ✓ checked

See also: discrete convolution · z-transform and stability

LaTeX source
y[n]=\sum_{k=0}^{M}b_kx[n-k]\ \ (\text{FIR}),\qquad y[n]=\sum_kb_kx[n-k]-\sum_{k\ge1}a_ky[n-k]\ \ (\text{IIR})
Signal processing

first-order low-pass filter

fc = 1/(2πRC);  yₙ = yₙ₋₁ + α(xₙ − yₙ₋₁)

The digital version is an exponential moving average.

Worked example: R = 1000, C = 1e-06 → 159.155 ✓ checked

See also: simple exponential smoothing

LaTeX source
f_c=\frac1{2\pi RC},\qquad y_n=y_{n-1}+\alpha(x_n-y_{n-1}),\ \ \alpha=\frac{\Delta t}{RC+\Delta t}
Signal processing

Fourier series of a square wave

square wave = (4/π) Σ sin(kωt)/k over odd k

The partial sums overshoot by about 8.9% at the jump (Gibbs phenomenon).

Worked example: N = 200 → 1.17899 ✓ checked

See also: discrete Fourier transform

LaTeX source
x(t)=\frac4\pi\sum_{k\ \text{odd}}\frac{\sin(k\omega t)}{k},\qquad c_n=\frac1T\int_0^Tx(t)e^{-jn\omega t}dt
Signal processing

Haar wavelet transform

a = (x₁ + x₂)/√2;  d = (x₁ − x₂)/√2

Orthonormal: energy is preserved. Recurse on the averages for a multi-level decomposition.

Worked example: x1 = 3, x2 = 1 → [2.82843, 1.41421] ✓ checked

See also: Parseval's theorem (DFT)

LaTeX source
a=\frac{x_1+x_2}{\sqrt2},\qquad d=\frac{x_1-x_2}{\sqrt2}
Signal processing

linear chirp

f(t) = f₀ + kt;  phase = 2π(f₀t + ½kt²)

Worked example: f0 = 10, k = 4, t = 2 → [18, 175.929] ✓ checked

See also: short-time Fourier transform

LaTeX source
f(t)=f_0+kt,\qquad \phi(t)=2\pi\Big(f_0t+\tfrac12kt^2\Big)
Signal processing

matched filter

h(t) = s(T − t);  SNR_max = 2E/N₀

Maximises the output SNR for a known signal in white noise.

Worked example: E = 4, N0 = 0.5 → 16 ✓ checked

See also: cross-correlation

LaTeX source
h(t)=s(T-t),\qquad \mathrm{SNR}_{\max}=\frac{2E_s}{N_0}
Signal processing

mel scale

m = 2595 log₁₀(1 + f/700)

Approximates how pitch is perceived; 1000 Hz ≈ 1000 mel.

Worked example: f = 1000 → 999.986 ✓ checked

See also: mel-frequency cepstral coefficients

LaTeX source
m=2595\log_{10}\Big(1+\frac f{700}\Big),\qquad f=700\big(10^{m/2595}-1\big)
Signal processing

mel-frequency cepstral coefficients

DCT-II of the log mel-band energies

Worked example: logE = [1, 2, 3], k = 1 → -1.73205 ✓ checked

See also: mel scale

LaTeX source
c_k=\sum_{m=1}^{M}\ln E_m\,\cos\!\Big[\frac{\pi k}{M}\big(m-\tfrac12\big)\Big]
Signal processing

periodogram and power spectral density

Ŝ = |X_k|²/(N·fs)

Welch's method averages periodograms of windowed segments to cut the variance.

Worked example: X = 8, N = 64, fs = 1 → 1 ✓ checked

See also: short-time Fourier transform

LaTeX source
\hat S_{xx}(f_k)=\frac1{N f_s}\,|X_k|^2
Signal processing

time–frequency uncertainty principle

Δt·Δf ≥ 1/(4π)

Equality for a Gaussian pulse: you cannot localise a signal in both time and frequency.

Worked example: dt = 0.01 → 7.95775 ✓ checked

See also: Fourier transform pairs

LaTeX source
\Delta t\,\Delta f\ge\frac1{4\pi}
Signal processing

Whittaker–Shannon interpolation

x(t) = Σ x[n] sinc((t − nT)/T)

Perfect reconstruction of a band-limited signal from its samples.

Worked example: x = [1, 0, 0], t = 0 → 1 ✓ checked

See also: Nyquist rate and aliasing

LaTeX source
x(t)=\sum_nx[n]\,\operatorname{sinc}\!\Big(\frac{t-nT}T\Big)
Signal processing

window functions

Hann: ½(1 − cos(2πn/(N − 1)));  Hamming: 0.54 − 0.46 cos(2πn/(N − 1))

Tapering the edges reduces spectral leakage.

Worked example: n = 4, N = 9 → [1, 1] ✓ checked

See also: short-time Fourier transform

LaTeX source
w_{\text{Hann}}[n]=\tfrac12\Big(1-\cos\frac{2\pi n}{N-1}\Big),\quad w_{\text{Hamming}}[n]=0.54-0.46\cos\frac{2\pi n}{N-1}
Signal processing

z-transform and stability

causal LTI system is stable iff its poles lie inside the unit circle

Worked example: a1 = -0.9 → 0.9 ✓ checked

See also: FIR and IIR filters

LaTeX source
X(z)=\sum_nx[n]z^{-n},\qquad H(z)=\frac{\sum b_kz^{-k}}{1+\sum a_kz^{-k}},\ \ \text{stable iff all poles satisfy }|z|<1
Geometry and algebra

angle addition formulas

sin(a ± b), cos(a ± b), tan(a + b)

Worked example: a = 0.4, b = 0.9 → [-1.11022e-16, 5.55112e-17, 2.22045e-15] ✓ checked

See also: double- and half-angle formulas

LaTeX source
\sin(a\pm b)=\sin a\cos b\pm\cos a\sin b,\quad \cos(a\pm b)=\cos a\cos b\mp\sin a\sin b,\quad \tan(a+b)=\frac{\tan a+\tan b}{1-\tan a\tan b}
Geometry and algebra

arc length and sector area

s = rθ;  sector area = ½r²θ

Degrees to radians: θ = d·π/180.

Worked example: r = 2, th = 1.5708 → [3.14159, 3.14159] ✓ checked

See also: circle and sphere

LaTeX source
s=r\theta,\qquad A_{\text{sector}}=\tfrac12r^2\theta\qquad(\theta\text{ in radians})
Geometry and algebra

circle and sphere

circle: C = 2πr, A = πr²;  sphere: S = 4πr², V = (4/3)πr³

Worked example: r = 2 → [12.5664, 12.5664, 50.2655, 33.5103] ✓ checked

See also: volume and surface of the n-ball

LaTeX source
C=2\pi r,\ \ A=\pi r^2;\qquad S=4\pi r^2,\ \ V=\tfrac43\pi r^3
Geometry and algebra

cylinder, cone and pyramid

cylinder πr²h;  cone ⅓πr²h;  pyramid ⅓A_b h

Worked example: r = 3, h = 4 → [113.097, 37.6991, 47.1239] ✓ checked

See also: circle and sphere

LaTeX source
V_{\text{cyl}}=\pi r^2h,\quad V_{\text{cone}}=\tfrac13\pi r^2h,\quad V_{\text{pyr}}=\tfrac13A_bh,\quad A_{\text{cone side}}=\pi r\sqrt{r^2+h^2}
Geometry and algebra

distance and midpoint

Euclidean distance, midpoint, point-to-line distance

Worked example: x = [0, 0], y = [3, 4], abc = [3, 4, -10], p = [0, 0] → [5, 2] ✓ checked

See also: Euclidean (L2) norm

LaTeX source
d=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2},\quad M=\Big(\frac{x_1+x_2}2,\frac{y_1+y_2}2\Big),\quad d_{\text{pt-line}}=\frac{|ax_0+by_0+c|}{\sqrt{a^2+b^2}}
Geometry and algebra

double- and half-angle formulas

sin 2θ = 2 sin θ cos θ;  cos 2θ = cos²θ − sin²θ;  sin²(θ/2) = (1 − cos θ)/2

Worked example: t = 0.7 → [-1.11022e-16, -2.77556e-17, 2.77556e-17] ✓ checked

See also: Pythagorean trigonometric identities

LaTeX source
\sin2\theta=2\sin\theta\cos\theta,\quad \cos2\theta=\cos^2\theta-\sin^2\theta=1-2\sin^2\theta,\quad \sin^2\tfrac\theta2=\frac{1-\cos\theta}2
Geometry and algebra

ellipse

area πab;  perimeter ≈ π[3(a + b) − √((3a + b)(a + 3b))] (Ramanujan)

Worked example: a = 5, b = 3 → [47.1239, 25.527, 0.8] ✓ checked

See also: circle and sphere

LaTeX source
A=\pi ab,\qquad P\approx\pi\Big[3(a+b)-\sqrt{(3a+b)(a+3b)}\Big],\qquad e=\sqrt{1-\frac{b^2}{a^2}}
Geometry and algebra

haversine distance

great-circle distance between two latitude/longitude points

where R = 6371 km

Worked example: lat1 = 0, lon1 = 0, lat2 = 0, lon2 = 90, R = 6371 → 10007.5 ✓ checked

See also: arc length and sector area

LaTeX source
d=2R\arcsin\sqrt{\sin^2\!\frac{\Delta\varphi}2+\cos\varphi_1\cos\varphi_2\sin^2\!\frac{\Delta\lambda}2}
Geometry and algebra

Heron's formula

A = √(s(s − a)(s − b)(s − c))

Worked example: a = 3, b = 4, c = 5 → 6 ✓ checked

See also: law of sines and cosines

LaTeX source
A=\sqrt{s(s-a)(s-b)(s-c)},\quad s=\tfrac{a+b+c}2;\qquad A=\tfrac12ab\sin C
Geometry and algebra

law of sines and cosines

a/sin A = b/sin B = c/sin C;  c² = a² + b² − 2ab cos C

where R = circumradius

Worked example: a = 3, b = 4, C = 1.5708 → 5 ✓ checked

See also: Heron's formula

LaTeX source
\frac a{\sin A}=\frac b{\sin B}=\frac c{\sin C}=2R,\qquad c^2=a^2+b^2-2ab\cos C
Geometry and algebra

logarithm and exponent rules

log(ab) = log a + log b;  log aⁿ = n log a

Worked example: a = 6, b = 4, n = 3 → [4.44089e-16, 0] ✓ checked

See also: change of base for logarithms

LaTeX source
\log(ab)=\log a+\log b,\quad \log\frac ab=\log a-\log b,\quad \log a^n=n\log a,\quad a^{m+n}=a^ma^n,\quad (a^m)^n=a^{mn}
Geometry and algebra

point-to-plane distance and plane equation

d = |ax₀ + by₀ + cz₀ + d|/√(a² + b² + c²)

The same formula gives the margin of a linear classifier.

Worked example: n = [1, 2, 2], d = -3, p = [0, 0, 0] → 1 ✓ checked

See also: distance and midpoint · SVM margin width

LaTeX source
d=\frac{|ax_0+by_0+cz_0+d|}{\sqrt{a^2+b^2+c^2}},\qquad \mathbf n\cdot(\mathbf x-\mathbf x_0)=0
Geometry and algebra

product-to-sum and sum-to-product

sin a cos b = ½[sin(a + b) + sin(a − b)]

Worked example: a = 0.4, b = 0.9 → [0, 0] ✓ checked

See also: angle addition formulas

LaTeX source
\sin a\cos b=\tfrac12[\sin(a+b)+\sin(a-b)],\qquad \cos a+\cos b=2\cos\frac{a+b}2\cos\frac{a-b}2
Geometry and algebra

quadratic discriminant and vertex

Δ = b² − 4ac;  vertex at x = −b/2a;  sum of roots −b/a, product c/a

Worked example: a = 1, b = -3, c = 2 → [1, 1.5, 3, 2] ✓ checked

See also: quadratic formula

LaTeX source
\Delta=b^2-4ac,\qquad \text{vertex}\ \Big(-\frac b{2a},\ c-\frac{b^2}{4a}\Big),\qquad x_1+x_2=-\frac ba,\ x_1x_2=\frac ca
Geometry and algebra

regular polygon

A = (n/4)s² cot(π/n);  diagonals = n(n − 3)/2

Worked example: n = 6, s = 2 → [10.3923, 120, 9] ✓ checked

See also: shoelace formula (polygon area)

LaTeX source
A=\frac n4s^2\cot\frac\pi n,\qquad \text{interior angle}=\frac{(n-2)\pi}n,\qquad \text{diagonals}=\frac{n(n-3)}2
Geometry and algebra

shoelace formula (polygon area)

A = ½|Σ (xᵢyᵢ₊₁ − xᵢ₊₁yᵢ)|

Worked example: x = [0, 4, 4, 0], y = [0, 0, 3, 3] → 12 ✓ checked

See also: Heron's formula

LaTeX source
A=\tfrac12\Big|\sum_{i=1}^{n}\big(x_iy_{i+1}-x_{i+1}y_i\big)\Big|
Geometry and algebra

Vieta's formulas (cubic)

relations between the roots and the coefficients of ax³ + bx² + cx + d

Worked example: a = 1, b = -6, c = 11, d = -6 → [6, 11, 6] ✓ checked

See also: quadratic discriminant and vertex

LaTeX source
x_1+x_2+x_3=-\frac ba,\quad x_1x_2+x_1x_3+x_2x_3=\frac ca,\quad x_1x_2x_3=-\frac da
Geometry and algebra

volume and surface of the n-ball

Vₙ = π^(n/2) rⁿ/Γ(n/2 + 1)

In high dimensions nearly all of the volume sits near the surface, and the unit ball's volume tends to 0.

Worked example: n = 3, r = 1 → 4.18879 ✓ checked

See also: circle and sphere · gamma function

LaTeX source
V_n(r)=\frac{\pi^{n/2}}{\Gamma\big(\frac n2+1\big)}r^n,\qquad S_{n-1}(r)=\frac{2\pi^{n/2}}{\Gamma(n/2)}r^{n-1}
Discrete maths

0/1 knapsack recurrence

V[i][w] = max(V[i − 1][w], vᵢ + V[i − 1][w − wᵢ])

O(nW) dynamic programming.

Worked example: v = [60, 100, 120], w = [1, 2, 3], W = 5 → 220 ✓ checked

See also: longest common subsequence

LaTeX source
V[i][w]=\max\big(V[i-1][w],\ v_i+V[i-1][w-w_i]\big)
Discrete maths

A* search

f = g + h

A consistent heuristic never needs to re-open a node.

Worked example: g = 7, h = 5 → 12 ✓ checked

See also: Dijkstra and Bellman–Ford relaxation

LaTeX source
f(n)=g(n)+h(n),\quad h\ \text{admissible: }h(n)\le h^*(n)\ \Rightarrow\ \text{optimal}
Discrete maths

absorbing Markov chains

fundamental matrix N = (I − Q)⁻¹

where Q = transient-to-transient block, R = transient-to-absorbing

Worked example: Q = [[0, 0.5], [0.5, 0]] → [2, 2] ✓ checked

See also: stationary distribution of a Markov chain

LaTeX source
N=(I-Q)^{-1},\quad \mathbb E[\text{steps to absorption}]=N\mathbf 1,\quad B=NR
Discrete maths

amortised cost of a doubling array

doubling the capacity gives O(1) amortised appends

Worked example: n = 1000 → 1023 ✓ checked

See also: union–find complexity

LaTeX source
\text{total copy cost for }n\text{ appends}\le2n,\qquad \text{amortised }O(1)
Discrete maths

binomial coefficient identities

Pascal's rule, row sum 2ⁿ, hockey stick, Vandermonde

Worked example: n = 10, k = 4 → [0, 0, 0] ✓ checked

See also: binomial theorem

LaTeX source
\binom nk=\binom{n-1}{k-1}+\binom{n-1}k,\quad \sum_k\binom nk=2^n,\quad \sum_{i=k}^{n}\binom ik=\binom{n+1}{k+1},\quad \sum_k\binom mk\binom n{r-k}=\binom{m+n}r
Discrete maths

birthday problem

P = 1 − Π (365 − i)/365

23 people give about 50.7%.

Worked example: k = 23 → 0.507297 ✓ checked

See also: hash collisions (birthday bound)

LaTeX source
P(\text{shared})=1-\prod_{i=0}^{k-1}\frac{365-i}{365}\approx1-e^{-k(k-1)/730}
Discrete maths

Bloom filter false-positive rate

p ≈ (1 − e^(−kn/m))ᵏ;  best k = (m/n) ln 2

where m bits, n items, k hashes

About 9.6 bits per item gives 1% false positives.

Worked example: m = 9.58506e+06, n = 1e+06, k = 7 → 0.0100392 ✓ checked

See also: hash collisions (birthday bound)

LaTeX source
p\approx\Big(1-e^{-kn/m}\Big)^k,\qquad k^*=\frac mn\ln2,\qquad m=-\frac{n\ln p}{(\ln2)^2}
Discrete maths

Catalan numbers

Cₙ = C(2n, n)/(n + 1)

Counts balanced parentheses, binary trees with n nodes, and triangulations of an (n + 2)-gon.

Worked example: n = 5 → 42 ✓ checked

See also: binomial theorem

LaTeX source
C_n=\frac1{n+1}\binom{2n}n,\qquad C_{n+1}=\sum_{i=0}^{n}C_iC_{n-i}
Discrete maths

Chinese remainder theorem

unique solution mod N = Π nᵢ

Worked example: a = [2, 3, 2], n = [3, 5, 7] → 23 ✓ checked

See also: modular inverse and fast exponentiation

LaTeX source
x\equiv a_i\pmod{n_i}\ (\gcd(n_i,n_j)=1)\ \Rightarrow\ x\equiv\sum_ia_iN_i\,(N_i^{-1}\bmod n_i)\pmod N,\ \ N_i=N/n_i
Discrete maths

comparison-sorting lower bound

any comparison sort needs ≥ log₂(n!) comparisons

Worked example: n = 1000 → [8529.4, 8523.08] ✓ checked

See also: Stirling's approximation

LaTeX source
\#\text{comparisons}\ge\log_2(n!)\approx n\log_2n-1.44\,n
Discrete maths

counting in graphs

handshake lemma, complete graph, tree and Cayley's formula

Worked example: n = 6 → [15, 5, 1296] ✓ checked

See also: Euler's formula for planar graphs

LaTeX source
\sum_v\deg v=2|E|,\quad |E_{K_n}|=\frac{n(n-1)}2,\quad \text{tree: }|E|=n-1,\quad \#\text{labelled trees}=n^{n-2}
Discrete maths

coupon collector

E[T] = n Hₙ

Collecting all 50 types takes about 225 draws.

Worked example: n = 50 → 224.96 ✓ checked

See also: harmonic numbers

LaTeX source
\mathbb E[T]=nH_n\approx n\ln n+\gamma n,\qquad \operatorname{Var}(T)\le\frac{\pi^2}6n^2
Discrete maths

De Morgan's laws and set identities

¬(A ∨ B) = ¬A ∧ ¬B;  ¬(A ∧ B) = ¬A ∨ ¬B;  |P(S)| = 2^|S|

Worked example: n = 5 → [32, 32] ✓ checked

See also: inclusion–exclusion

LaTeX source
\overline{A\cup B}=\overline A\cap\overline B,\quad \overline{A\cap B}=\overline A\cup\overline B,\quad |\mathcal P(S)|=2^{|S|}
Discrete maths

derangements

Dₙ = n! Σ (−1)ᵏ/k! ≈ n!/e

The chance a random permutation has no fixed point tends to 1/e.

Worked example: n = 6 → 265 ✓ checked

See also: inclusion–exclusion

LaTeX source
D_n=n!\sum_{k=0}^{n}\frac{(-1)^k}{k!}\approx\frac{n!}e,\qquad D_n=(n-1)(D_{n-1}+D_{n-2})
Discrete maths

Dijkstra and Bellman–Ford relaxation

relax each edge: d[v] = min(d[v], d[u] + w)

Dijkstra O((V + E) log V) for non-negative weights; Bellman–Ford O(VE) allows negative weights.

Worked example: W = [9 values] → [0, 3, 1] ✓ checked

See also: Floyd–Warshall

LaTeX source
d[v]\leftarrow\min\big(d[v],\ d[u]+w(u,v)\big)
Discrete maths

divisor functions

number and sum of divisors from the prime factorisation

Worked example: n = 60 → [12, 168] ✓ checked

See also: Euler's totient function

LaTeX source
\sigma_k(n)=\sum_{d\mid n}d^k,\quad \tau(n)=\prod(e_i+1)\ \text{for }n=\prod p_i^{e_i},\quad \sigma(n)=\prod\frac{p_i^{e_i+1}-1}{p_i-1}
Discrete maths

Erlang B

blocking probability of c servers with offered load a

Worked example: c = 3, a = 2 → 0.210526 ✓ checked

See also: M/M/1 queue

LaTeX source
B(c,a)=\frac{a\,B(c-1,a)}{c+a\,B(c-1,a)},\quad B(0,a)=1
Discrete maths

Euclid's algorithm and Bézout

gcd(a, b) = gcd(b, a mod b);  lcm = ab/gcd

The extended algorithm finds x, y: the modular inverse when gcd = 1.

Worked example: a = 240, b = 46 → [2, 5520] ✓ checked

See also: modular inverse and fast exponentiation

LaTeX source
\gcd(a,b)=\gcd(b,a\bmod b),\qquad ax+by=\gcd(a,b),\qquad \operatorname{lcm}(a,b)=\frac{ab}{\gcd(a,b)}
Discrete maths

Euler's formula for planar graphs

V − E + F = 2;  E ≤ 3V − 6

A cube has V = 8, E = 12, F = 6.

Worked example: V = 8, E = 12 → 6 ✓ checked

See also: counting in graphs

LaTeX source
V-E+F=2,\qquad E\le3V-6\ \ (V\ge3)
Discrete maths

Fibonacci numbers (Binet)

Fₙ = (φⁿ − ψⁿ)/√5

Worked example: n = 20 → 6765 ✓ checked

See also: linear recurrences

LaTeX source
F_n=\frac{\varphi^n-\psi^n}{\sqrt5},\quad \varphi=\frac{1+\sqrt5}2,\ \psi=\frac{1-\sqrt5}2,\quad F_n=F_{n-1}+F_{n-2}
Discrete maths

Floyd–Warshall

all-pairs shortest paths in O(V³)

Worked example: W = [9 values] → 3 ✓ checked

See also: Dijkstra and Bellman–Ford relaxation

LaTeX source
d_{ij}^{(k)}=\min\big(d_{ij}^{(k-1)},\ d_{ik}^{(k-1)}+d_{kj}^{(k-1)}\big)
Discrete maths

gambler's ruin

P(win) = (1 − (q/p)ⁱ)/(1 − (q/p)^N)

Worked example: p = 0.45, i = 10, N = 20 → 0.118501 ✓ checked

See also: random walk

LaTeX source
P(\text{reach }N\text{ from }i)=\frac{1-(q/p)^i}{1-(q/p)^N}\ (p\ne q),\qquad \frac iN\ (p=q)
Discrete maths

hash collisions (birthday bound)

expected collisions ≈ n²/(2m)

A 64-bit hash collides among about 5 billion items.

Worked example: n = 1000, m = 1e+06 → 0.4995 ✓ checked

See also: birthday problem

LaTeX source
\mathbb E[\text{collisions}]=\binom n2\frac1m\approx\frac{n^2}{2m},\qquad n\approx\sqrt{2m\ln2}\ \text{for a 50\% chance}
Discrete maths

Huffman coding

merge the two smallest weights until one remains

Worked example: p = [0.4, 0.3, 0.2, 0.1] → 1.9 ✓ checked

See also: source coding theorem · Kraft inequality

LaTeX source
\text{repeatedly merge the two least probable symbols;}\quad \bar L=\sum_ip_i\ell_i,\ \ H\le\bar L<H+1
Discrete maths

HyperLogLog and count-min sketch errors

HLL error 1.04/√m;  count-min error e/w with probability 1 − e^(−d)

Worked example: m = 16384 → 0.008125 ✓ checked

See also: Bloom filter false-positive rate

LaTeX source
\text{HLL standard error}\approx\frac{1.04}{\sqrt m},\qquad \text{CMS: }\varepsilon=\frac ew,\ \ \delta=e^{-d}
Discrete maths

inclusion–exclusion

|A ∪ B| = |A| + |B| − |A ∩ B|

Worked example: a = 30, b = 20, ab = 8 → 42 ✓ checked

See also: derangements

LaTeX source
|A\cup B|=|A|+|B|-|A\cap B|,\qquad |A\cup B\cup C|=\sum|A_i|-\sum|A_i\cap A_j|+|A\cap B\cap C|
Discrete maths

Kelly criterion

f* = p − q/b

where p = win probability, q = 1 − p, b = net odds

Maximises the long-run growth rate of capital; half-Kelly is less volatile.

Worked example: p = 0.6, b = 1 → 0.2 ✓ checked

See also: gambler's ruin

LaTeX source
f^*=p-\frac qb=\frac{bp-q}b,\qquad f^*=\frac{\mu-r}{\sigma^2}\ \text{(continuous)}
Discrete maths

M/M/1 queue

ρ = λ/μ;  L = ρ/(1 − ρ);  W = 1/(μ − λ)  (Little's law L = λW)

where λ = arrival rate, μ = service rate

Waiting explodes as ρ → 1.

Worked example: lam = 8, mu = 10 → [0.8, 4, 0.5, 3.2] ✓ checked

See also: Erlang B

LaTeX source
\rho=\frac\lambda\mu,\quad L=\frac\rho{1-\rho},\quad W=\frac1{\mu-\lambda},\quad L_q=\frac{\rho^2}{1-\rho},\quad L=\lambda W
Discrete maths

master theorem

compare d with log_b a

Merge sort: a = 2, b = 2, d = 1 gives Θ(n log n).

Worked example: a = 2, b = 2, d = 1 → 0 ✓ checked

See also: FFT complexity

LaTeX source
T(n)=aT(n/b)+\Theta(n^d)\ \Rightarrow\ T(n)=\begin{cases}\Theta(n^d)&d>\log_ba\\ \Theta(n^d\log n)&d=\log_ba\\ \Theta(n^{\log_ba})&d<\log_ba\end{cases}
Discrete maths

matrix-chain multiplication cost

optimal parenthesisation by dynamic programming

(AB)C versus A(BC) can differ enormously in cost.

Worked example: p = [10, 30, 5, 60] → 4500 ✓ checked

See also: matrix-multiplication cost

LaTeX source
m[i][j]=\min_{i\le k<j}\big(m[i][k]+m[k+1][j]+p_{i-1}p_kp_j\big)
Discrete maths

max-flow min-cut theorem

the value of a maximum flow equals the capacity of a minimum cut

Ford–Fulkerson / Edmonds–Karp find it by augmenting paths.

Worked example: caps = [3, 2, 4] → 3 ✓ checked

See also: Dijkstra and Bellman–Ford relaxation

LaTeX source
\max\ \text{flow}=\min\ \text{cut capacity}
Discrete maths

Monty Hall

switching wins with probability 2/3

Bayes: P(car behind the other door | host opens a goat door) = 2/3.

Worked example: pa = 0.333333 → 0.666667 ✓ checked

See also: Bayes' theorem

LaTeX source
P(\text{win by switching})=\frac23,\qquad P(\text{stay})=\frac13
Discrete maths

order statistics of uniforms

E[X₍ₖ₎] = k/(n + 1)

Worked example: n = 9, k = 3 → [0.3, 0.9, 0.0190909] ✓ checked

See also: continuous uniform distribution: mean

LaTeX source
\mathbb E[X_{(k)}]=\frac k{n+1},\qquad \mathbb E[\max]=\frac n{n+1},\qquad \operatorname{Var}(X_{(k)})=\frac{k(n+1-k)}{(n+1)^2(n+2)}
Discrete maths

permutations with repetition

n!/(n₁! n₂! … n_k!)

MISSISSIPPI has 11!/(4!4!2!1!) = 34 650 arrangements.

Worked example: n = 11 → 34650 ✓ checked

See also: combinations and permutations

LaTeX source
\frac{n!}{n_1!\,n_2!\cdots n_k!},\qquad n^k\ \text{(sequences of length }k\text{ from }n\text{ symbols)}
Discrete maths

pigeonhole principle

some box holds ≥ ⌈n/m⌉ items

Worked example: n = 25, m = 12 → 3 ✓ checked

See also: birthday problem

LaTeX source
n\text{ items in }m\text{ boxes}\ \Rightarrow\ \text{some box has at least }\Big\lceil\frac nm\Big\rceil
Discrete maths

prime number theorem

π(x) ≈ x/ln x

There are about 1/ln x primes near x.

Worked example: x = 100000 → 8685.89 ✓ checked

See also: Stirling's approximation

LaTeX source
\pi(x)\sim\frac x{\ln x},\qquad p_n\sim n\ln n
Discrete maths

RSA

n = pq;  e·d ≡ 1 (mod φ(n));  c = mᵉ mod n;  m = cᵈ mod n

Security rests on the difficulty of factoring n.

Worked example: p = 61, q = 53, e = 17, m = 65 → [2753, 2790, 65] ✓ checked

See also: Euler's totient function · modular inverse and fast exponentiation

LaTeX source
n=pq,\quad ed\equiv1\pmod{\varphi(n)},\quad c=m^e\bmod n,\quad m=c^d\bmod n
Discrete maths

secretary problem

reject the first n/e, then take the next record: success probability → 1/e

Worked example: n = 100 → [36.7879, 0.367879] ✓ checked

See also: birthday problem

LaTeX source
\text{reject the first }n/e\text{ candidates, then take the next best;}\quad P(\text{best})\to\frac1e\approx0.368
Discrete maths

Shapley value

average marginal contribution over all orderings

The basis of SHAP feature attributions.

Worked example: v1 = 10, v2 = 20, v12 = 50 → [20, 30] ✓ checked

See also: mixed Nash equilibrium (2×2 zero-sum)

LaTeX source
\varphi_i=\sum_{S\subseteq N\setminus\{i\}}\frac{|S|!\,(n-|S|-1)!}{n!}\big(v(S\cup\{i\})-v(S)\big)
Discrete maths

stars and bars

C(n + k − 1, k − 1)

Worked example: n = 10, k = 3 → [66, 36] ✓ checked

See also: combinations and permutations

LaTeX source
\binom{n+k-1}{k-1}\ \text{(non-negative solutions of }x_1+\cdots+x_k=n),\qquad \binom{n-1}{k-1}\ \text{(positive)}
Discrete maths

Stirling numbers of the second kind

S(n, k) = kS(n − 1, k) + S(n − 1, k − 1)

S(n, k) counts partitions of n items into k non-empty sets.

Worked example: n = 5 → [15, 52] ✓ checked

See also: Catalan numbers

LaTeX source
S(n,k)=kS(n-1,k)+S(n-1,k-1),\qquad \text{Bell: }B_n=\sum_kS(n,k)
Discrete maths

sum of a geometric sequence and compound growth

geometric sum; compound interest (n times a year) and continuous compounding

Worked example: P = 1000, r = 0.05, t = 10, n = 12 → [1647.01, 1648.72] ✓ checked

See also: geometric series

LaTeX source
S_n=a\frac{r^n-1}{r-1},\qquad A=P\Big(1+\frac rn\Big)^{nt},\qquad A=Pe^{rt}
Discrete maths

system reliability

series multiplies, parallel multiplies the failure probabilities

Worked example: R = [0.9, 0.95], mtbf = 1000, mttr = 10 → [0.855, 0.995, 0.990099] ✓ checked

See also: hazard and survival functions

LaTeX source
R_{\text{series}}=\prod_iR_i,\qquad R_{\text{parallel}}=1-\prod_i(1-R_i),\qquad A=\frac{\mathrm{MTBF}}{\mathrm{MTBF}+\mathrm{MTTR}}
Discrete maths

union–find complexity

nearly constant amortised time per operation

where α = inverse Ackermann

Worked example: n = 10 → 9 ✓ checked

See also: amortised cost of a doubling array

LaTeX source
m\text{ operations on }n\text{ elements: }O\big(m\,\alpha(n)\big),\quad \alpha(n)\le4\ \text{for any practical }n
Science and finance

allometric scaling

Y = a M^b;  Kleiber's law B ∝ M^(3/4)

Linear in log–log coordinates: log Y = log a + b log M.

Worked example: M = 16 → 8 ✓ checked

See also: Pareto (type I) distribution: density

LaTeX source
Y=aM^{b},\qquad \text{Kleiber: }B\propto M^{3/4}
Science and finance

Arrhenius equation

k = A e^(−Ea/RT)

Worked example: Ea = 50000, R = 8.314, T1 = 300, T2 = 310 → 1.90916 ✓ checked

See also: first-order kinetics and half-life

LaTeX source
k=Ae^{-E_a/RT},\qquad \ln\frac{k_2}{k_1}=\frac{E_a}R\Big(\frac1{T_1}-\frac1{T_2}\Big)
Science and finance

Bernoulli's equation and continuity

p + ½ρv² + ρgh = const;  A₁v₁ = A₂v₂;  Re = ρvL/μ

Re ≲ 2000 laminar, ≳ 4000 turbulent in a pipe.

Worked example: rho = 1000, v = 2, L = 0.05, mu = 0.001 → 100000 ✓ checked

See also: Navier–Stokes (incompressible)

LaTeX source
p+\tfrac12\rho v^2+\rho gh=\text{const},\qquad A_1v_1=A_2v_2,\qquad \mathrm{Re}=\frac{\rho vL}\mu
Science and finance

Black–Scholes option price

call price and put–call parity

Worked example: S = 100, K = 100, r = 0.05, s = 0.2, T = 1 → 10.4506 ✓ checked

See also: normal cumulative distribution

LaTeX source
C=S\,\Phi(d_1)-Ke^{-rT}\Phi(d_2),\quad d_{1,2}=\frac{\ln(S/K)+(r\pm\sigma^2/2)T}{\sigma\sqrt T},\quad C-P=S-Ke^{-rT}
Science and finance

Boltzmann entropy and the partition function

S = k ln W;  pᵢ = e^(−Eᵢ/kT)/Z;  F = −kT ln Z

The softmax is a Boltzmann distribution with temperature T; entropy S = −kΣ p ln p.

Worked example: E = [0, 1], kT = 1 → [0.731059, 0.268941] ✓ checked

See also: softmax · Shannon entropy · softmax with temperature

LaTeX source
S=k_B\ln W,\qquad Z=\sum_ie^{-E_i/k_BT},\qquad p_i=\frac{e^{-E_i/k_BT}}Z,\qquad F=-k_BT\ln Z
Science and finance

CAPM and value at risk

E[R] = r_f + β(E[R_m] − r_f)

Worked example: rf = 0.02, beta = 1.5, rm = 0.08 → 0.11 ✓ checked

See also: portfolio return, variance and Sharpe ratio

LaTeX source
\mathbb E[R_i]=r_f+\beta_i\big(\mathbb E[R_m]-r_f\big),\qquad \mathrm{VaR}_\alpha=\mu+z_\alpha\sigma
Science and finance

Coulomb's law and electric field

F = kq₁q₂/r²;  E = kq/r²;  V = kq/r

Worked example: q1 = 1e-06, q2 = 1e-06, r = 0.1 → 0.898755 ✓ checked

See also: Newtonian gravitation

LaTeX source
F=\frac{kq_1q_2}{r^2},\quad E=\frac{kq}{r^2},\quad V=\frac{kq}r,\quad k=\frac1{4\pi\varepsilon_0}\approx8.99\times10^9
Science and finance

diversity indices

Shannon index H′ = −Σ pᵢ ln pᵢ;  Simpson D = 1 − Σ pᵢ²

Shannon entropy by another name.

Worked example: p = [0.5, 0.3, 0.2] → [1.02965, 0.62] ✓ checked

See also: Shannon entropy · Gini impurity

LaTeX source
H'=-\sum_ip_i\ln p_i,\qquad D=1-\sum_ip_i^2,\qquad \text{Hill number }{}^qD=\Big(\sum p_i^q\Big)^{\frac1{1-q}}
Science and finance

doubling time and the rule of 72

t_d = ln 2/r ≈ 72/r%

Worked example: r = 0.07 → [9.9021, 10.2857] ✓ checked

See also: logistic growth

LaTeX source
t_d=\frac{\ln2}r\approx\frac{72}{r\%},\qquad N=N_0e^{rt}
Science and finance

elasticity and the Cobb–Douglas function

ε = (dQ/dP)(P/Q);  Y = A K^α L^(1 − α)

Worked example: A = 1, K = 8, L = 27, a = 0.333333 → 18 ✓ checked

See also: allometric scaling

LaTeX source
\varepsilon=\frac{\partial\ln Q}{\partial\ln P}=\frac{dQ}{dP}\frac PQ,\qquad Y=AK^{\alpha}L^{1-\alpha}
Science and finance

equations of constant acceleration

v = u + at;  s = ut + ½at²;  v² = u² + 2as

Worked example: u = 2, a = 3, t = 4 → [14, 32, 14] ✓ checked

See also: projectile motion

LaTeX source
v=u+at,\qquad s=ut+\tfrac12at^2,\qquad v^2=u^2+2as
Science and finance

expected utility and CRRA

U = W^(1−γ)/(1 − γ);  certainty equivalent

Worked example: w = [50, 150], g = 0.5 → [93.3013, 6.69873] ✓ checked

See also: Jensen's inequality · Kelly criterion

LaTeX source
U(W)=\frac{W^{1-\gamma}}{1-\gamma},\qquad \mathrm{CE}=U^{-1}\big(\mathbb E\,U(W)\big),\qquad \text{risk premium}=\mathbb E W-\mathrm{CE}
Science and finance

first-order kinetics and half-life

[A] = [A]₀ e^(−kt);  t½ = ln 2/k

Also radioactive decay: N = N₀ e^(−λt).

Worked example: k = 0.1, t = 10 → [0.367879, 6.93147] ✓ checked

See also: Arrhenius equation

LaTeX source
[A]=[A]_0e^{-kt},\qquad t_{1/2}=\frac{\ln2}k
Science and finance

Gibbs free energy and equilibrium constant

ΔG = ΔH − TΔS;  ΔG⁰ = −RT ln K

Worked example: dH = -50000, dS = -100, T = 300 → -20000 ✓ checked

See also: Nernst equation

LaTeX source
\Delta G=\Delta H-T\Delta S,\qquad \Delta G^0=-RT\ln K
Science and finance

Gini coefficient and Lorenz curve

G = ΣΣ|xᵢ − xⱼ|/(2n²x̄)

0 is perfect equality; 1 is maximal inequality. Also the Herfindahl index H = Σ sᵢ² for market concentration.

Worked example: x = [1, 2, 3, 4] → 0.25 ✓ checked

See also: Gini impurity

LaTeX source
G=\frac{\sum_i\sum_j|x_i-x_j|}{2n^2\bar x}=1-2\int_0^1L(p)\,dp
Science and finance

heat, wave and Laplace equations

heat u_t = αu_xx;  wave u_tt = c²u_xx;  Laplace ∇²u = 0

Separation of variables turns each into ordinary differential equations. The heat kernel is a Gaussian with variance 2αt.

Worked example: a = 1, t = 0.5, x = 1 → 6.45248e-09 ✓ checked

See also: Navier–Stokes (incompressible)

LaTeX source
u_t=\alpha\,u_{xx},\qquad u_{tt}=c^2u_{xx},\qquad \nabla^2u=0
Science and finance

Hooke's law and the spring-mass oscillator

F = −kx;  ω = √(k/m);  T = 2π√(m/k)

Worked example: k = 100, m = 1 → [10, 0.628319] ✓ checked

See also: simple pendulum

LaTeX source
F=-kx,\quad U=\tfrac12kx^2,\quad \omega=\sqrt{k/m},\quad T=2\pi\sqrt{m/k},\quad x(t)=A\cos(\omega t+\phi)
Science and finance

ideal gas law and kinetic theory

PV = nRT;  v_rms = √(3kT/m)

where R = 8.314 J/(mol K)

Worked example: n = 1, T = 273.15, P = 101325 → 0.022414 ✓ checked

See also: Maxwell–Boltzmann speeds

LaTeX source
PV=nRT=Nk_BT,\qquad v_{\text{rms}}=\sqrt{\frac{3k_BT}m},\qquad \bar K=\tfrac32k_BT
Science and finance

leaky integrate-and-fire neuron

τ dV/dt = −(V − V_rest) + RI

The basic unit of spiking neural networks.

Worked example: tau = 10, R = 10, I = 2, t = 10 → 12.6424 ✓ checked

See also: RC and RL circuits

LaTeX source
\tau_m\frac{dV}{dt}=-(V-V_{\text{rest}})+RI,\qquad \text{spike when }V\ge V_{\text{th}},\ \text{then reset}
Science and finance

logistic growth

dN/dt = rN(1 − N/K);  N(t) = K/(1 + ((K − N₀)/N₀) e^(−rt))

Exponential growth N₀e^(rt) while N ≪ K; the sigmoid shape of adoption curves.

Worked example: K = 1000, N0 = 10, r = 0.5, t = 10 → 599.86 ✓ checked

See also: sigmoid (logistic function) · doubling time and the rule of 72

LaTeX source
\frac{dN}{dt}=rN\Big(1-\frac NK\Big),\qquad N(t)=\frac K{1+\frac{K-N_0}{N_0}e^{-rt}}
Science and finance

Lorentz force

F = q(E + v × B);  gyroradius r = mv/(qB)

Worked example: q = 1.6e-19, v = [1e+06, 0, 0], B = [0, 0, 1] → [0, -1.6e-13, 0] ✓ checked

See also: cross product and triple product

LaTeX source
\mathbf F=q\big(\mathbf E+\mathbf v\times\mathbf B\big),\qquad r=\frac{mv}{qB},\qquad \omega_c=\frac{qB}m
Science and finance

Lotka–Volterra predator–prey

prey x, predators y;  equilibrium (γ/δ, α/β)

Worked example: a = 1, b = 0.1, d = 0.02, g = 0.4 → [20, 10] ✓ checked

See also: logistic growth

LaTeX source
\dot x=\alpha x-\beta xy,\quad \dot y=\delta xy-\gamma y,\qquad (x^*,y^*)=\Big(\frac\gamma\delta,\frac\alpha\beta\Big)
Science and finance

Maxwell's equations

Gauss, Gauss for magnetism, Faraday, Ampère–Maxwell

The speed of light is c = 1/√(μ₀ε₀).

Worked example: mu0 = 1.25664e-06, e0 = 8.85419e-12 → 2.99792e+08 ✓ checked

See also: gradient, divergence and curl

LaTeX source
\nabla\cdot\mathbf E=\frac\rho{\varepsilon_0},\quad \nabla\cdot\mathbf B=0,\quad \nabla\times\mathbf E=-\frac{\partial\mathbf B}{\partial t},\quad \nabla\times\mathbf B=\mu_0\mathbf J+\mu_0\varepsilon_0\frac{\partial\mathbf E}{\partial t}
Science and finance

Nernst equation

E = E⁰ − (RT/nF) ln Q

In neuroscience it gives the equilibrium potential of an ion.

Worked example: R = 8.314, T = 310, z = 1, F = 96485, out = 5, in_ = 140 → -0.089011 ✓ checked

See also: Gibbs free energy and equilibrium constant

LaTeX source
E=E^0-\frac{RT}{nF}\ln Q,\qquad E_{\text{ion}}=\frac{RT}{zF}\ln\frac{[\mathrm{ion}]_{out}}{[\mathrm{ion}]_{in}}
Science and finance

net present value and annuities

NPV = Σ Cₜ/(1 + r)ᵗ;  annuity PV = C(1 − (1 + r)⁻ⁿ)/r

Worked example: C = [-100, 60, 60], r = 0.1 → 4.13223 ✓ checked

See also: sum of a geometric sequence and compound growth

LaTeX source
\mathrm{NPV}=\sum_{t=0}^{T}\frac{C_t}{(1+r)^t},\qquad PV_{\text{annuity}}=C\,\frac{1-(1+r)^{-n}}r,\qquad \text{perpetuity }\frac Cr
Science and finance

Newtonian gravitation

F = Gm₁m₂/r²;  v_orb = √(GM/r);  v_esc = √(2GM/r)

where G = 6.674×10⁻¹¹ N m²/kg²

Worked example: G = 6.674e-11, M = 5.972e+24, r = 6.371e+06 → [7909.5, 11185.7] ✓ checked

See also: work, kinetic and potential energy

LaTeX source
F=\frac{Gm_1m_2}{r^2},\quad v_{\text{orb}}=\sqrt{\frac{GM}r},\quad v_{\text{esc}}=\sqrt{\frac{2GM}r},\quad T^2=\frac{4\pi^2a^3}{GM}
Science and finance

Ohm's law and resistor networks

V = IR;  P = IV;  series add, parallel add reciprocals

Worked example: R = [100, 200, 300], V = 12 → [600, 54.5455, 0.02] ✓ checked

See also: RC and RL circuits

LaTeX source
V=IR,\quad P=IV=I^2R,\quad R_{\text{series}}=\sum R_i,\quad \frac1{R_{\text{par}}}=\sum\frac1{R_i}
Science and finance

pH and the Henderson–Hasselbalch equation

pH = −log₁₀[H⁺];  pH = pKa + log₁₀([A⁻]/[HA])

Worked example: h = 0.001, pka = 4.76, ratio = 10 → [3, 5.76] ✓ checked

See also: Arrhenius equation

LaTeX source
\mathrm{pH}=-\log_{10}[\mathrm H^+],\qquad \mathrm{pH}=\mathrm{p}K_a+\log_{10}\frac{[\mathrm A^-]}{[\mathrm{HA}]}
Science and finance

photon energy and de Broglie wavelength

E = hf = hc/λ;  λ = h/p;  ΔxΔp ≥ ħ/2

where h = 6.626×10⁻³⁴ J s

Worked example: h = 6.62607e-34, c = 2.99792e+08, lam = 5e-07 → 3.97289e-19 ✓ checked

See also: time–frequency uncertainty principle

LaTeX source
E=hf=\frac{hc}\lambda,\qquad \lambda=\frac hp,\qquad \Delta x\,\Delta p\ge\frac\hbar2
Science and finance

Planck, Stefan–Boltzmann and Wien laws

blackbody spectrum;  P = σAT⁴;  λ_max = b/T

where σ = 5.670×10⁻⁸, b = 2.898×10⁻³ m K

Worked example: T = 5772 → [5.02039e-07, 6.29386e+07] ✓ checked

See also: photon energy and de Broglie wavelength

LaTeX source
B_\lambda=\frac{2hc^2}{\lambda^5}\frac1{e^{hc/\lambda k_BT}-1},\qquad P=\sigma AT^4,\qquad \lambda_{\max}=\frac bT
Science and finance

portfolio return, variance and Sharpe ratio

μ_p = wᵀμ;  σ_p² = wᵀΣw;  Sharpe = (μ_p − r_f)/σ_p

Diversification: the covariance terms, not the variances, set the portfolio risk.

Worked example: w = [0.5, 0.5], mu = [0.08, 0.12], S = [[0.04, 0.01], [0.01, 0.09]], rf = 0.02 → [0.1, 0.0375, 0.413118] ✓ checked

See also: variance and standard deviation · covariance

LaTeX source
\mu_p=\mathbf w^{\top}\boldsymbol\mu,\qquad \sigma_p^2=\mathbf w^{\top}\Sigma\mathbf w,\qquad \mathrm{Sharpe}=\frac{\mu_p-r_f}{\sigma_p}
Science and finance

projectile motion

range v²sin 2θ/g;  height v²sin²θ/(2g);  time 2v sin θ/g

Maximum range at 45° (no drag).

Worked example: v = 20, th = 0.785398, g = 9.80665 → [40.7886, 10.1972, 2.88419] ✓ checked

See also: equations of constant acceleration

LaTeX source
R=\frac{v_0^2\sin2\theta}g,\qquad H=\frac{v_0^2\sin^2\theta}{2g},\qquad T=\frac{2v_0\sin\theta}g
Science and finance

RC and RL circuits

V(t) = V₀(1 − e^(−t/RC));  τ = RC

63% charged after one time constant.

Worked example: V0 = 5, R = 1000, C = 1e-06, t = 0.001 → 3.1606 ✓ checked

See also: Ohm's law and resistor networks · first-order low-pass filter

LaTeX source
V_C(t)=V_0\big(1-e^{-t/RC}\big),\quad \tau=RC,\quad E_C=\tfrac12CV^2,\quad E_L=\tfrac12LI^2
Science and finance

rotational dynamics

τ = Iα;  L = Iω;  K = ½Iω²

Worked example: m = 2, r = 0.5, w = 10 → [0.25, 12.5, 2.5] ✓ checked

See also: work, kinetic and potential energy

LaTeX source
\tau=I\alpha,\quad L=I\omega,\quad K_{\text{rot}}=\tfrac12I\omega^2,\quad I_{\text{disk}}=\tfrac12mr^2,\quad I_{\text{sphere}}=\tfrac25mr^2
Science and finance

Schrödinger equation

iħ ∂ψ/∂t = Ĥψ;  Ĥψ = Eψ

|ψ|² is the probability density.

Worked example: n = 1, L = 1 → 1 ✓ checked

See also: particle in a box and hydrogen levels

LaTeX source
i\hbar\frac{\partial\psi}{\partial t}=\hat H\psi,\qquad \hat H\psi=E\psi,\quad \hat H=-\frac{\hbar^2}{2m}\nabla^2+V
Science and finance

SIR epidemic model

R₀ = β/γ;  herd-immunity threshold 1 − 1/R₀

An outbreak grows iff R₀ S/N > 1.

Worked example: beta = 0.3, gamma = 0.1 → [3, 0.666667] ✓ checked

See also: logistic growth

LaTeX source
\dot S=-\beta SI,\quad \dot I=\beta SI-\gamma I,\quad \dot R=\gamma I,\qquad R_0=\frac\beta\gamma,\quad \text{herd immunity }1-\frac1{R_0}
Science and finance

special relativity

E = mc²;  γ = 1/√(1 − v²/c²);  time dilation, length contraction

Worked example: b = 0.6 → [1.25, 12.5, 8] ✓ checked

See also: Lorentz force

LaTeX source
E=mc^2,\quad \gamma=\frac1{\sqrt{1-v^2/c^2}},\quad \Delta t=\gamma\Delta t_0,\quad L=\frac{L_0}\gamma,\quad E^2=(pc)^2+(mc^2)^2
Science and finance

waves, Doppler effect and Snell's law

v = fλ;  Doppler;  Snell;  thin lens

Worked example: f = 440, v = 343, vs = 30 → [0.779545, 482.173] ✓ checked

See also: Maxwell's equations

LaTeX source
v=f\lambda,\quad f'=f\frac{v\pm v_o}{v\mp v_s},\quad n_1\sin\theta_1=n_2\sin\theta_2,\quad \frac1f=\frac1{d_o}+\frac1{d_i}
Science and finance

work, kinetic and potential energy

W = Fd cos θ;  K = ½mv²;  U = mgh

Work–energy theorem: W = ΔK.

Worked example: m = 2, v = 3, h = 10 → [9, 196.133] ✓ checked

See also: Newton's second law, momentum and impulse

LaTeX source
W=Fd\cos\theta,\quad K=\tfrac12mv^2,\quad U=mgh,\quad P=\frac{dW}{dt}=\mathbf F\cdot\mathbf v
Control

controllability and observability

full-rank controllability / observability matrix

Worked example: A = [[0, 1], [0, 0]], B = [[0], [1]] → 2 ✓ checked

See also: linear-quadratic regulator

LaTeX source
\operatorname{rank}\big[B,\ AB,\ \dots,\ A^{n-1}B\big]=n,\qquad \operatorname{rank}\big[C;\ CA;\ \dots;\ CA^{n-1}\big]=n
Control

linear-quadratic regulator

optimal feedback gain from the algebraic Riccati equation

Scalar case: P = (a + √(a² + b²q/r))·r/b².

Worked example: a = 1, b = 1, q = 1, r = 1 → [2.41421, 2.41421, 0] ✓ checked

See also: Kalman filter

LaTeX source
\min\int(\mathbf x^{\top}Q\mathbf x+\mathbf u^{\top}R\mathbf u)dt\ \Rightarrow\ \mathbf u=-K\mathbf x,\ K=R^{-1}B^{\top}P,\ \ A^{\top}P+PA-PBR^{-1}B^{\top}P+Q=0
Control

Lyapunov stability

stable iff every eigenvalue of A has negative real part

Worked example: A = [[-1, 0], [0, -2]] → 1 ✓ checked

See also: eigenvalue equation

LaTeX source
\dot{\mathbf x}=A\mathbf x\ \text{stable}\iff\exists P\succ0:\ A^{\top}P+PA=-Q\ (Q\succ0)
Control

PID controller

u = Kp·e + Ki·∫e + Kd·de/dt

Worked example: Kp = 2, Ki = 0.5, Kd = 0.1, e = 1, ie = 4, de = -2 → 3.8 ✓ checked

See also: first- and second-order step responses

LaTeX source
u(t)=K_pe(t)+K_i\int_0^te\,d\tau+K_d\frac{de}{dt}
Control

stability region of the Euler method

forward Euler is stable for |1 + hλ| < 1

For λ = −100 the step must be below 0.02. Stiff problems need implicit methods.

Worked example: lam = -100, h = 0.019 → 0.9 ✓ checked

See also: Euler's method · gradient descent step

LaTeX source
y'=\lambda y:\ \ y_{n+1}=(1+h\lambda)y_n,\quad \text{stable iff }|1+h\lambda|<1
Optimisation

accelerated gradient rate

f(xₖ) − f* ≤ 2L‖x₀ − x*‖²/(k + 1)²

Optimal for first-order methods on smooth convex functions; plain gradient descent only gets O(1/k).

Worked example: L = 2, R2 = 1, k = 9 → 0.04 ✓ checked

See also: Nesterov accelerated gradient

LaTeX source
f(x_k)-f^*\le\frac{2L\|x_0-x^*\|^2}{(k+1)^2}
Optimisation

AdaDelta

Δθ = −√(E[Δθ²] + ε)/√(E[g²] + ε) · g

No learning rate needed.

Worked example: g = 2, rho = 0.9, eps = 1e-06 → -0.00316227 ✓ checked

See also: RMSProp · AdaGrad

LaTeX source
E[g^2]\leftarrow\rho E[g^2]+(1-\rho)g^2,\quad \Delta\theta=-\frac{\sqrt{E[\Delta\theta^2]+\epsilon}}{\sqrt{E[g^2]+\epsilon}}\,g,\quad E[\Delta\theta^2]\leftarrow\rho E[\Delta\theta^2]+(1-\rho)\Delta\theta^2
Optimisation

AdaGrad

G ← G + g²;  θ ← θ − η g / (√G + ε)

Per-parameter step shrinks as gradients accumulate; good for sparse features.

Worked example: G0 = 0, g = 2, theta = 1, lr = 0.1, eps = 1e-12 → 0.9 ✓ checked

See also: RMSProp · Adam

LaTeX source
G\leftarrow G+g^2,\quad \theta\leftarrow\theta-\frac{\eta\,g}{\sqrt G+\epsilon}
Optimisation

Adam

m ← β₁m + (1−β₁)g
v ← β₂v + (1−β₂)g²
m̂ = m/(1−β₁ᵗ)   v̂ = v/(1−β₂ᵗ)
θ ← θ − η m̂ / (√v̂ + ε)

where defaults β₁ = 0.9, β₂ = 0.999, ε = 1e-8

The bias correction matters in the first steps.

Worked example: g = 2, t = 1, theta = 1, lr = 0.001, b1 = 0.9, b2 = 0.999, eps = 1e-08 → 0.999 ✓ checked

See also: AdamW (decoupled weight decay) · momentum (heavy ball) · RMSProp

LaTeX source
m\leftarrow\beta_1m+(1-\beta_1)g,\ v\leftarrow\beta_2v+(1-\beta_2)g^2,\ \hat m=\tfrac{m}{1-\beta_1^t},\ \hat v=\tfrac{v}{1-\beta_2^t},\ \theta\leftarrow\theta-\eta\frac{\hat m}{\sqrt{\hat v}+\epsilon}
Optimisation

AdamW (decoupled weight decay)

θ ← θ − η ( m̂/(√v̂+ε) + λθ )

where λ = weight decay

Decay is applied to the weights, not folded into the gradient.

Worked example: g = 2, t = 1, theta = 1, lr = 0.001, b1 = 0.9, b2 = 0.999, eps = 1e-08, wd = 0.01 → 0.99899 ✓ checked

See also: Adam · L2 penalty (weight decay)

LaTeX source
\theta\leftarrow\theta-\eta\left(\frac{\hat m}{\sqrt{\hat v}+\epsilon}+\lambda\theta\right)
Optimisation

ADMM (scaled form, lasso)

x-update (ridge solve), z-update (soft-threshold), u-update (dual)

Splits a hard problem into easy ones; good for distributed and constrained problems.

Worked example: A = [[1, 0], [0, 1]], b = [3, 0.2], lam = 0.5, rho = 1 → [1, 0, 0.5, 0.1] ✓ checked

See also: ISTA (proximal gradient for the lasso) · proximal operator of the L1 norm

LaTeX source
x\leftarrow(A^{\top}A+\rho I)^{-1}\big(A^{\top}b+\rho(z-u)\big),\quad z\leftarrow S_{\lambda/\rho}(x+u),\quad u\leftarrow u+x-z
Optimisation

AMSGrad

v̂ₜ = max(v̂ₜ₋₁, vₜ)

Keeps the second-moment estimate non-decreasing, fixing a convergence gap in Adam.

Worked example: vprev = 4, v = 1 → 4 ✓ checked

See also: Adam

LaTeX source
\hat v_t=\max(\hat v_{t-1},v_t),\quad \theta\leftarrow\theta-\eta\frac{m_t}{\sqrt{\hat v_t}+\epsilon}
Optimisation

Armijo (sufficient decrease) condition

f(x + tp) ≤ f(x) + c₁ t ∇fᵀp

where c₁ ≈ 10⁻⁴

Backtracking: shrink t by a factor until it holds.

Worked example: x = 1, p = -2, t = 0.5, c = 0.0001 → 1 ✓ checked

See also: Wolfe curvature condition

LaTeX source
f(x+tp)\le f(x)+c_1\,t\,\nabla f(x)^{\top}p
Optimisation

BFGS update

H₊ = (I − ρsyᵀ) H (I − ρysᵀ) + ρssᵀ

where s = x₊ − x, y = ∇f₊ − ∇f

Satisfies the secant equation H₊y = s.

Worked example: H = [[1, 0], [0, 1]], s = [1, 0.5], y = [2, 1] → [1, 0.5] ✓ checked

See also: Newton's method (multivariate)

LaTeX source
H_{k+1}=\Big(I-\rho s y^{\top}\Big)H_k\Big(I-\rho y s^{\top}\Big)+\rho ss^{\top},\quad \rho=\frac1{y^{\top}s}
Optimisation

convexity and strong convexity

convex: f(θx + (1−θ)y) ≤ θf(x) + (1−θ)f(y);  μ-strongly convex: f(y) ≥ f(x) + ∇f·(y−x) + (μ/2)‖y − x‖²

Worked example: x = 1, y = 3, t = 0.25 → 0.75 ✓ checked

See also: descent lemma (L-smoothness)

LaTeX source
f(\theta x+(1-\theta)y)\le\theta f(x)+(1-\theta)f(y);\quad f(y)\ge f(x)+\nabla f(x)^{\top}(y-x)+\tfrac\mu2\|y-x\|^2
Optimisation

cosine annealing with warm restarts (SGDR)

η_t = η_min + ½(η_max − η_min)(1 + cos(πT_cur/T_i))

where T_cur = steps since the last restart

Worked example: hi = 0.1, lo = 0, tcur = 25, ti = 100 → 0.0853553 ✓ checked

See also: cosine learning-rate schedule

LaTeX source
\eta_t=\eta_{\min}+\tfrac12(\eta_{\max}-\eta_{\min})\Big(1+\cos\frac{\pi T_{\text{cur}}}{T_i}\Big)
Optimisation

Euclidean projection onto the simplex

sort v descending as u; ρ as above; subtract τ and clip

Used to keep probabilities valid in constrained optimisation.

Worked example: v = [0.5, 1.2, -0.3] → [0.15, 0.85, 0] ✓ checked

See also: projected gradient descent

LaTeX source
\Pi(v)=\max(v-\tau,0),\quad \tau=\frac{\sum_{i\le\rho}u_i-1}{\rho},\ \ \rho=\max\Big\{j:u_j-\frac{\sum_{i\le j}u_i-1}j>0\Big\}
Optimisation

exponential moving average

θ̄ ← β θ̄ + (1−β) θ

where β ≈ 0.99–0.9999

Used for weights (EMA models) and running statistics.

Worked example: avg = 1, theta = 2, beta = 0.99 → 1.01 ✓ checked

See also: momentum (heavy ball)

LaTeX source
\bar\theta\leftarrow\beta\bar\theta+(1-\beta)\theta
Optimisation

FISTA momentum

tₖ₊₁ = (1 + √(1 + 4tₖ²))/2;  yₖ₊₁ = xₖ + ((tₖ − 1)/tₖ₊₁)(xₖ − xₖ₋₁)

Worked example: t = 1 → 1.61803 ✓ checked

See also: ISTA (proximal gradient for the lasso) · accelerated gradient rate

LaTeX source
t_{k+1}=\frac{1+\sqrt{1+4t_k^2}}2,\qquad y_{k+1}=x_k+\frac{t_k-1}{t_{k+1}}(x_k-x_{k-1})
Optimisation

Frank–Wolfe (conditional gradient)

s = argmin ⟨∇f, s⟩;  x ← (1 − γ)x + γs

Projection-free: only a linear minimisation over the constraint set. On the simplex s is a vertex.

Worked example: g = [3, 1, 2], x = [0.333333, 0.333333, 0.333333], k = 0 → [0, 1, 0] ✓ checked

See also: projected gradient descent

LaTeX source
s_k=\arg\min_{s\in\mathcal C}\langle\nabla f(x_k),s\rangle,\qquad x_{k+1}=(1-\gamma_k)x_k+\gamma_ks_k,\ \gamma_k=\frac2{k+2}
Optimisation

Gauss–Newton and Levenberg–Marquardt

Δ = −(JᵀJ)⁻¹Jᵀr;  LM adds λI

where r = residuals, J = their Jacobian

Exact in one step for linear least squares; LM interpolates toward gradient descent.

Worked example: J = [[1, 0], [1, 1], [1, 2]], y = [1, 3, 5], x = [0, 0] → [1, 2] ✓ checked

See also: ordinary least squares (normal equations) · Newton's method (multivariate)

LaTeX source
\Delta=-(J^{\top}J)^{-1}J^{\top}r,\qquad \Delta_{LM}=-(J^{\top}J+\lambda I)^{-1}J^{\top}r
Optimisation

gradient accumulation

average K micro-batch gradients before stepping

Gives a large effective batch on small memory; scale each loss by 1/K.

Worked example: K = 8, B = 32 → 256 ✓ checked

See also: learning-rate scaling with batch size

LaTeX source
g=\frac1K\sum_{k=1}^{K}\nabla L_{B_k},\qquad B_{\text{effective}}=K\cdot B
Optimisation

gradient check (relative error)

relative error ‖g_a − g_n‖/max(‖g_a‖, ‖g_n‖) ≲ 1e-6

Compare backprop with the central difference.

Worked example: ga = [1, 2], gn = [1, 2] → 6.32455e-08 ✓ checked

See also: finite differences

LaTeX source
\frac{\|g_{\text{analytic}}-g_{\text{numeric}}\|}{\max(\|g_{\text{analytic}}\|,\|g_{\text{numeric}}\|)}\ \lesssim 10^{-6}
Optimisation

gradient descent rate (strongly convex)

‖x_k − x*‖² ≤ (1 − μ/L)ᵏ ‖x₀ − x*‖²

where μ-strongly convex, L-smooth, step η = 1/L; μ/L = 1/κ

Linear convergence; rate is governed by the condition number.

Worked example: mu = 1, L = 4, k = 2, d0 = 1 → 0.5625 ✓ checked

See also: condition number · descent lemma (L-smoothness)

LaTeX source
\|x_k-x^*\|^2\le\left(1-\frac{\mu}{L}\right)^{k}\|x_0-x^*\|^2
Optimisation

gradient noise scale

B_noise = tr(Σ)/‖G‖²

where Σ = per-example gradient covariance, G = true gradient

The batch size beyond which larger batches stop helping (critical batch size).

Worked example: trS = 100, G2 = 0.25 → 400 ✓ checked

See also: learning-rate scaling with batch size

LaTeX source
\mathcal B_{\text{noise}}=\frac{\operatorname{tr}(\Sigma)}{\|G\|^2}
Optimisation

gradient norm clipping

g ← g · min(1, c / ‖g‖₂)

where c = clip threshold

Rescales the whole gradient, keeping its direction.

Worked example: g = [3, 4], c = 1 → [0.6, 0.8] ✓ checked

See also: gradient descent step

LaTeX source
g\leftarrow g\cdot\min\!\left(1,\frac{c}{\|g\|_2}\right)
Optimisation

Hessian–vector product

Hv ≈ (∇f(x + εv) − ∇f(x))/ε

Needs only gradients; reverse-mode autodiff computes it exactly in about twice the cost of a gradient.

Worked example: A = [[2, 1], [1, 3]], x = [1, 1], v = [1, 0], e = 1e-06 → [2, 1] ✓ checked

See also: Hessian matrix and second-derivative test · conjugate gradient method

LaTeX source
H\mathbf v\approx\frac{\nabla f(x+\varepsilon\mathbf v)-\nabla f(x)}{\varepsilon}=\nabla_x\big(\nabla f(x)^{\top}\mathbf v\big)
Optimisation

ISTA (proximal gradient for the lasso)

x ← S_{ηλ}(x − ηAᵀ(Ax − b))

FISTA adds Nesterov momentum for an O(1/k²) rate.

Worked example: A = [[1, 0], [0, 1]], b = [3, 0.2], x = [0, 0], lam = 0.5, eta = 1 → [2.5, 0] ✓ checked

See also: FISTA momentum · proximal operator of the L1 norm

LaTeX source
x\leftarrow\operatorname{prox}_{\eta\lambda\|\cdot\|_1}\big(x-\eta A^{\top}(Ax-b)\big)
Optimisation

KKT stationarity (inequality constraints)

∇f + Σ μᵢ∇gᵢ = 0;  μᵢ ≥ 0;  gᵢ ≤ 0;  μᵢgᵢ = 0

where gᵢ(x) ≤ 0 constraints, μᵢ multipliers

Complementary slackness: a constraint is active or its multiplier is zero.

Worked example: mu = 0.5, g = 0 → 0 ✓ checked

See also: Lagrange multipliers · support vector machine (soft margin)

LaTeX source
\nabla f(x)+\sum_i\mu_i\nabla g_i(x)=0,\quad \mu_i\ge0,\quad g_i(x)\le0,\quad \mu_i g_i(x)=0
Optimisation

Lagrange multipliers

L(x,λ) = f(x) + λ g(x);  ∇ₓL = 0,  g(x) = 0

where equality constraint g(x) = 0

Example: min x²+y² subject to x+y=1 gives x=y=½, λ=−1.

Worked example: x = 0.5, lam = -1 → 0 ✓ checked

See also: KKT stationarity (inequality constraints)

LaTeX source
\mathcal L(x,\lambda)=f(x)+\lambda\,g(x),\quad \nabla_x\mathcal L=0,\ g(x)=0
Optimisation

Lagrangian dual

g(λ) = inf_x L(x, λ);  d* ≤ p*  (weak duality)

Strong duality (d* = p*) holds for convex problems under Slater's condition. Example: min x² s.t. x ≥ 1 has g(λ) = λ − λ²/4, maximised at λ = 2.

Worked example: lam = 2 → 1 ✓ checked

See also: KKT stationarity (inequality constraints) · SVM dual problem

LaTeX source
g(\lambda)=\inf_x\ \mathcal L(x,\lambda),\quad d^*=\max_{\lambda\ge0}g(\lambda)\le p^*
Optimisation

layer-wise trust ratio (LARS / LAMB)

λ_ℓ = η‖θ_ℓ‖/(‖g_ℓ‖ + β‖θ_ℓ‖)

Scales each layer's step to its weight norm; enables very large batches.

Worked example: w = 10, g = 2, b = 0, lr = 0.1 → 0.5 ✓ checked

See also: AdamW (decoupled weight decay) · learning-rate scaling with batch size

LaTeX source
\lambda_\ell=\eta\,\frac{\|\theta_\ell\|}{\|g_\ell\|+\beta\|\theta_\ell\|},\qquad \theta_\ell\leftarrow\theta_\ell-\lambda_\ell\big(g_\ell+\beta\theta_\ell\big)
Optimisation

learning-rate scaling with batch size

η′ = η·B′/B

Valid up to a critical batch size; combine with warm-up.

Worked example: lr = 0.1, B = 256, B2 = 1024 → [0.4, 0.2] ✓ checked

See also: gradient noise scale

LaTeX source
\eta'=\eta\,\frac{B'}{B}\ \ (\text{SGD}),\qquad \eta'=\eta\sqrt{\frac{B'}{B}}\ \ (\text{Adam, common heuristic})
Optimisation

linear learning-rate warm-up

η_t = η_max · t / T_w

where T_w = warm-up steps

Stabilises early training of large models.

Worked example: lr = 0.001, t = 100, tw = 1000 → 0.0001 ✓ checked

See also: cosine learning-rate schedule

LaTeX source
\eta_t=\eta_{\max}\,\frac{t}{T_w}\quad(t\le T_w)
Optimisation

Lion optimizer

u = sign(β₁m + (1−β₁)g);  θ ← θ − η(u + λθ)

Sign updates make every coordinate move by the same magnitude; found by program search.

Worked example: m = 0.5, g = -2, b1 = 0.9, th = 1, lr = 0.01, wd = 0.1 → 0.989 ✓ checked

See also: AdamW (decoupled weight decay)

LaTeX source
\mathbf u=\operatorname{sign}\big(\beta_1m+(1-\beta_1)g\big),\quad \theta\leftarrow\theta-\eta(\mathbf u+\lambda\theta),\quad m\leftarrow\beta_2m+(1-\beta_2)g
Optimisation

Lookahead optimizer

slow ← slow + α(fast − slow) every k steps

Worked example: slow = 1, fast = 2, a = 0.5 → 1.5 ✓ checked

See also: exponential moving average

LaTeX source
\phi\leftarrow\phi+\alpha(\theta_k-\phi)
Optimisation

momentum (heavy ball)

v ← μv + g;  θ ← θ − ηv

where μ ≈ 0.9 = momentum coefficient

Accumulates a velocity that smooths noisy gradients.

Worked example: v = 0.1, g = 0.5, mu = 0.9, theta = 1, lr = 0.1 → 0.941 ✓ checked

See also: gradient descent step · Adam

LaTeX source
v\leftarrow\mu v+g,\quad \theta\leftarrow\theta-\eta v
Optimisation

Nesterov accelerated gradient

v ← μv − η∇f(θ + μv);  θ ← θ + v

Evaluates the gradient at the look-ahead point; O(1/k²) for smooth convex f.

Worked example: th = 1, v = 0.1, mu = 0.9, lr = 0.1 → [0.981, -0.019] ✓ checked

See also: momentum (heavy ball) · accelerated gradient rate

LaTeX source
\mathbf v\leftarrow\mu\mathbf v-\eta\nabla f(\theta+\mu\mathbf v),\quad \theta\leftarrow\theta+\mathbf v
Optimisation

Polyak–Łojasiewicz condition

½‖∇f‖² ≥ μ(f − f*)  ⇒  linear rate (1 − μ/L)ᵏ

Linear convergence without convexity; holds for many over-parameterised networks.

Worked example: mu = 1, L = 4, k = 3, gap0 = 8 → 3.375 ✓ checked

See also: gradient descent rate (strongly convex)

LaTeX source
\tfrac12\|\nabla f(x)\|^2\ge\mu\big(f(x)-f^*\big)\ \Rightarrow\ f(x_k)-f^*\le\Big(1-\frac\mu L\Big)^k\big(f(x_0)-f^*\big)
Optimisation

polynomial learning-rate decay

η_t = (η₀ − η_end)(1 − t/T)ᵖ + η_end

p = 1 is linear decay.

Worked example: lr0 = 0.1, end = 0, t = 50, T = 100, p = 2 → 0.025 ✓ checked

See also: cosine learning-rate schedule

LaTeX source
\eta_t=(\eta_0-\eta_{\text{end}})\Big(1-\frac tT\Big)^p+\eta_{\text{end}}
Optimisation

RMSProp

s ← βs + (1−β)g²;  θ ← θ − η g / (√s + ε)

where β ≈ 0.9

Worked example: s0 = 0, g = 2, beta = 0.9, theta = 1, lr = 0.1, eps = 1e-12 → 0.683772 ✓ checked

See also: AdaGrad · Adam

LaTeX source
s\leftarrow\beta s+(1-\beta)g^2,\quad\theta\leftarrow\theta-\frac{\eta\,g}{\sqrt s+\epsilon}
Optimisation

SGD rate (convex, bounded gradients)

E f(x̄_T) − f* ≤ R G/√T

where R = ‖x₀ − x*‖, G = bound on gradient norm

Worked example: R = 2, G = 3, T = 10000 → 0.06 ✓ checked

See also: subgradient method bound

LaTeX source
\mathbb E\big[f(\bar x_T)\big]-f^*\le\frac{R\,G}{\sqrt T}\quad\big(\eta=\tfrac{R}{G\sqrt T}\big)
Optimisation

sharpness-aware minimisation

ε = ρ∇L/‖∇L‖;  w ← w − η∇L(w + ε)

where ρ = neighbourhood radius

Seeks flat minima by taking the gradient at the worst nearby point.

Worked example: w = 1, rho = 0.1, lr = 0.1 → 0.89 ✓ checked

See also: gradient descent step

LaTeX source
\varepsilon=\rho\frac{\nabla L(w)}{\|\nabla L(w)\|},\qquad w\leftarrow w-\eta\,\nabla L(w+\varepsilon)
Optimisation

subgradient method bound

min f(xᵢ) − f* ≤ R²/(2αk) + αG²/2

where constant step size α

Worked example: R = 2, G = 1, al = 0.1, k = 100 → 0.25 ✓ checked

See also: SGD rate (convex, bounded gradients)

LaTeX source
\min_{i\le k}f(x_i)-f^*\le\frac{R^2}{2\alpha k}+\frac{\alpha G^2}{2}
Optimisation

SVM dual problem

max Σαᵢ − ½ ΣΣ αᵢαⱼyᵢyⱼ k(xᵢ, xⱼ)

Only support vectors have αᵢ > 0. Replace the dot product by a kernel.

Worked example: al = 0.5 → 0.5 ✓ checked

See also: support vector machine (soft margin) · RBF (Gaussian) kernel

LaTeX source
\max_\alpha\ \sum_i\alpha_i-\tfrac12\sum_{i,j}\alpha_i\alpha_jy_iy_j\,k(\mathbf x_i,\mathbf x_j)\quad\text{s.t. }0\le\alpha_i\le C,\ \sum_i\alpha_iy_i=0
Optimisation

Transformer learning-rate schedule

η_t = d^(−½) min(t^(−½), t·t_w^(−3/2))

Linear warm-up for t_w steps, then decay as 1/√t ("Attention Is All You Need").

Worked example: d = 512, tw = 4000, t = 1000 → 0.000174693 ✓ checked

See also: linear learning-rate warm-up

LaTeX source
\eta_t=d_{\text{model}}^{-1/2}\min\big(t^{-1/2},\ t\,t_w^{-3/2}\big)
Optimisation

trust-region ratio

ρ = actual reduction / predicted reduction

where m = local quadratic model

ρ near 1: model is good, enlarge the region; ρ small: shrink it.

Worked example: act = 0.8, pred = 1 → 0.8 ✓ checked

See also: Newton's method (multivariate)

LaTeX source
\rho=\frac{f(x)-f(x+p)}{m(0)-m(p)}
Optimisation

variance of a minibatch gradient

Var(ĝ_B) = Σ/B

Halving the noise needs four times the batch.

Worked example: s = 4, B = 64 → 0.0625 ✓ checked

See also: gradient noise scale

LaTeX source
\operatorname{Var}\big(\hat g_B\big)=\frac{\Sigma}{B}\quad\text{(sampling with replacement)}
Optimisation

Wolfe curvature condition

∇f(x + tp)ᵀp ≥ c₂ ∇f(x)ᵀp

Together with Armijo it rules out too-short steps; required for BFGS.

Worked example: x = 1, p = -2, t = 0.1, c2 = 0.9 → 1 ✓ checked

See also: Armijo (sufficient decrease) condition

LaTeX source
\nabla f(x+tp)^{\top}p\ge c_2\,\nabla f(x)^{\top}p,\quad 0<c_1<c_2<1
ML losses and metrics

0–1 loss and risk

ℓ = 1[y ≠ ŷ];  risk = error rate

Non-differentiable, so surrogates (log, hinge, exponential) replace it in training.

Worked example: y = [0, 1, 1, 0], yh = [0, 1, 0, 0] → 0.25 ✓ checked

See also: Bayes error and optimal classifier

LaTeX source
\ell(y,\hat y)=\mathbf 1[y\ne\hat y],\qquad R(h)=\mathbb E\,\ell(y,h(x))
ML losses and metrics

adjusted R²

R²_adj = 1 − (1−R²)(n−1)/(n−p−1)

where n samples, p predictors

Penalises adding useless predictors.

Worked example: r2 = 0.97, n = 20, p = 3 → 0.964375 ✓ checked

See also: coefficient of determination R²

LaTeX source
R^2_{\mathrm{adj}}=1-(1-R^2)\frac{n-1}{n-p-1}
ML losses and metrics

area under the ROC curve (AUC)

AUC = P(score⁺ > score⁻) + ½ P(tie)

where s⁺, s⁻ = scores of a random positive and negative

Threshold-free ranking quality; 0.5 is chance.

Worked example: pos = [0.8, 0.6], neg = [0.5, 0.6] → 0.875 ✓ checked

See also: recall

LaTeX source
\mathrm{AUC}=P\big(s^{+}>s^{-}\big)+\tfrac12P\big(s^{+}=s^{-}\big)
ML losses and metrics

average precision (PR-AUC)

AP = Σ (Rₙ − Rₙ₋₁) Pₙ

where precision and recall at each threshold

Preferred to ROC-AUC for heavy class imbalance.

Worked example: labels = [1, 0, 1, 0, 1] → 0.755556 ✓ checked

See also: area under the ROC curve (AUC)

LaTeX source
\mathrm{AP}=\sum_n(R_n-R_{n-1})\,P_n
ML losses and metrics

balanced accuracy

BA = (TPR + TNR)/2

Accuracy that does not reward predicting the majority class.

Worked example: tp = 8, fn = 2, tn = 70, fp = 20 → 0.788889 ✓ checked

See also: recall · specificity, NPV, FPR and FNR

LaTeX source
\mathrm{BA}=\tfrac12\Big(\frac{TP}{TP+FN}+\frac{TN}{TN+FP}\Big)
ML losses and metrics

BLEU brevity penalty

BP = 1 if c > r, else e^(1 − r/c)

where c = candidate length, r = reference length

Worked example: c = 8, r = 10 → 0.778801 ✓ checked

See also: BLEU score

LaTeX source
\mathrm{BP}=\begin{cases}1&c>r\\ e^{1-r/c}&c\le r\end{cases}
ML losses and metrics

BLEU score

BLEU = BP · exp( Σ wₙ log pₙ )

where pₙ = n-gram precision, r/c = reference/candidate length

Worked example: p1 = 0.8, p2 = 0.6 → 0.69282 ✓ checked

See also: perplexity

LaTeX source
\mathrm{BLEU}=\mathrm{BP}\cdot\exp\!\Big(\sum_{n=1}^{N}w_n\log p_n\Big),\quad \mathrm{BP}=\min\big(1,e^{1-r/c}\big)
ML losses and metrics

Brier score

BS = (1/n) Σᵢ Σₖ (pᵢₖ − 1[k = yᵢ])²

A proper scoring rule: lowest in expectation only when the probabilities are honest.

Worked example: p = [[0.8, 0.2], [0.3, 0.7]], y = [0, 1] → 0.13 ✓ checked

See also: expected calibration error (ECE) · binary cross-entropy (log loss)

LaTeX source
\mathrm{BS}=\frac1n\sum_i\sum_k\big(p_{ik}-\mathbf{1}[k=y_i]\big)^2
ML losses and metrics

Brier score decomposition

BS = REL − RES + UNC;  UNC = ō(1 − ō)

where ō = base rate

REL is the calibration error part: lower is better.

Worked example: o = 0.3 → 0.21 ✓ checked

See also: Brier score · expected calibration error (ECE)

LaTeX source
\mathrm{BS}=\underbrace{\mathrm{REL}}_{\text{reliability}}-\underbrace{\mathrm{RES}}_{\text{resolution}}+\underbrace{\mathrm{UNC}}_{\text{uncertainty}},\quad \mathrm{UNC}=\bar o(1-\bar o)
ML losses and metrics

Calinski–Harabasz index

CH = (SS_B/(k − 1)) / (SS_W/(n − k))

The ANOVA F ratio applied to clusters; higher is better.

Worked example: ssb = 40, ssw = 10, k = 3, n = 33 → 60 ✓ checked

See also: one-way ANOVA F statistic

LaTeX source
\mathrm{CH}=\frac{\mathrm{SS}_B/(k-1)}{\mathrm{SS}_W/(n-k)}
ML losses and metrics

classification accuracy and confusion-matrix rates

accuracy = (TP + TN)/N;  prevalence = (TP + FN)/N

Misleading when classes are imbalanced: always predicting the majority class can score highly.

Worked example: tp = 40, tn = 45, fp = 5, fn = 10 → [0.85, 0.5, 0.15] ✓ checked

See also: balanced accuracy · specificity, NPV, FPR and FNR · precision · recall

LaTeX source
\mathrm{Acc}=\frac{TP+TN}{TP+TN+FP+FN},\qquad \text{prevalence}=\frac{TP+FN}N
ML losses and metrics

cluster purity

purity = (1/n) Σ_k max_j |c_k ∩ t_j|

Biased toward many small clusters.

Worked example: m = [8, 7], n = 20 → 0.75 ✓ checked

See also: normalised mutual information

LaTeX source
\mathrm{purity}=\frac1n\sum_k\max_j|c_k\cap t_j|
ML losses and metrics

coefficient of determination R²

R² = 1 − SS_res / SS_tot

1 is perfect; can be negative for a bad model.

Worked example: y = [1, 2, 3], yh = [1.1, 1.9, 3.2] → 0.97 ✓ checked

See also: adjusted R² · mean squared error

LaTeX source
R^2=1-\frac{\sum(y_i-\hat y_i)^2}{\sum(y_i-\bar y)^2}
ML losses and metrics

contrastive loss (Hadsell)

L = y d² + (1 − y) max(0, m − d)²

where y = 1 for similar pairs

Worked example: d = 0.4, y = 0, m = 1 → 0.36 ✓ checked

See also: triplet loss

LaTeX source
L=y\,d^2+(1-y)\max(0,\,m-d)^2
ML losses and metrics

Davies–Bouldin index

DB = (1/k) Σᵢ maxⱼ≠ᵢ (sᵢ + sⱼ)/dᵢⱼ

where s = within-cluster scatter, d = centroid distance

Lower is better.

Worked example: s = [1, 1], d = 4 → 0.5 ✓ checked

See also: silhouette coefficient

LaTeX source
\mathrm{DB}=\frac1k\sum_i\max_{j\ne i}\frac{s_i+s_j}{d_{ij}}
ML losses and metrics

DCG and NDCG

DCG = Σ (2^relᵢ − 1)/log₂(i + 1);  NDCG = DCG/IDCG

Rewards relevant items near the top.

Worked example: rel = [3, 2, 3, 0] → 0.959454 ✓ checked

See also: mean reciprocal rank

LaTeX source
\mathrm{DCG}@k=\sum_{i=1}^{k}\frac{2^{rel_i}-1}{\log_2(i+1)},\qquad \mathrm{NDCG}@k=\frac{\mathrm{DCG}@k}{\mathrm{IDCG}@k}
ML losses and metrics

Dice coefficient

Dice = 2|A ∩ B| / (|A| + |B|)

Worked example: inter = 3, a = 5, b = 5 → 0.6 ✓ checked

See also: intersection over union (Jaccard)

LaTeX source
\mathrm{Dice}=\frac{2|A\cap B|}{|A|+|B|}
ML losses and metrics

Dice loss

L = 1 − (2Σpᵢgᵢ + ε)/(Σpᵢ + Σgᵢ + ε)

Directly optimises overlap; standard for segmentation with small foregrounds.

Worked example: p = [0.9, 0.1, 0.8], g = [1, 0, 1] → 0.105263 ✓ checked

See also: Dice coefficient · Tversky index

LaTeX source
L=1-\frac{2\sum p_ig_i+\epsilon}{\sum p_i+\sum g_i+\epsilon}
ML losses and metrics

epistemic and aleatoric uncertainty (ensembles)

H(mean p) = mean H(pₘ) + mutual information

Epistemic uncertainty is the disagreement between ensemble members.

Worked example: P = [[0.9, 0.1], [0.1, 0.9]] → [0.693147, 0.325083, 0.368064] ✓ checked

See also: Shannon entropy · mutual information

LaTeX source
\underbrace{H\big(\bar p\big)}_{\text{total}}=\underbrace{\mathbb E_m H(p_m)}_{\text{aleatoric}}+\underbrace{I(y;m)}_{\text{epistemic}},\quad \bar p=\frac1M\sum_mp_m
ML losses and metrics

expected calibration error (ECE)

ECE = Σ_b (n_b/n) · |acc(b) − conf(b)|

where B confidence bins, n_b examples in bin b, acc(b) = fraction correct, conf(b) = mean confidence

Measures whether stated confidence matches how often the model is right. Depends on the binning; 15 bins is common.

Worked example: conf = [0.9, 0.9, 0.6, 0.6], ok = [1, 0, 1, 1], B = 10 → 0.4 ✓ checked

See also: Brier score · softmax with temperature · maximum calibration error (MCE)

LaTeX source
\mathrm{ECE}=\sum_{b=1}^{B}\frac{n_b}{n}\,\big|\operatorname{acc}(b)-\operatorname{conf}(b)\big|
ML losses and metrics

explained variance score

EV = 1 − Var(y − ŷ)/Var(y)

Like R² but ignores a constant bias in the residuals.

Worked example: y = [1, 2, 3], yh = [1.5, 2.5, 3.5] → 1 ✓ checked

See also: coefficient of determination R²

LaTeX source
\mathrm{EV}=1-\frac{\operatorname{Var}(y-\hat y)}{\operatorname{Var}(y)}
ML losses and metrics

exponential loss

L = exp(−y f(x))

where y ∈ {−1, +1}

The loss AdaBoost minimises.

Worked example: y = 1, f = 0.5 → 0.606531 ✓ checked

See also: AdaBoost

LaTeX source
L=e^{-yf(x)}
ML losses and metrics

F1 score

F₁ = 2PR / (P + R)

where P = precision, R = recall

Harmonic mean of precision and recall.

Worked example: p = 0.8, r = 0.666667 → 0.727273 ✓ checked

See also: precision · recall · Fβ score

LaTeX source
F_1=\frac{2PR}{P+R}=\frac{2TP}{2TP+FP+FN}
ML losses and metrics

focal loss

FL = −α (1 − pₜ)^γ ln pₜ

where pₜ = probability of the true class, γ ≈ 2

Down-weights easy examples so rare hard ones dominate; used for dense detection.

Worked example: p = 0.9, g = 2, al = 0.25 → 0.000263401 ✓ checked

See also: binary cross-entropy (log loss)

LaTeX source
\mathrm{FL}(p_t)=-\alpha_t(1-p_t)^{\gamma}\ln p_t
ML losses and metrics

Fréchet inception distance

FID = ‖μ₁ − μ₂‖² + tr(Σ₁ + Σ₂ − 2(Σ₁Σ₂)^½)

where Gaussian fits to Inception features of real and generated images

Lower is better. It is the squared Wasserstein-2 distance between the two Gaussians.

Worked example: m1 = [0, 0], m2 = [1, 0], S1 = [[1, 0], [0, 1]], S2 = [[4, 0], [0, 1]] → 2 ✓ checked

See also: Wasserstein-2 distance between Gaussians (1-D)

LaTeX source
\mathrm{FID}=\|\mu_1-\mu_2\|^2+\operatorname{tr}\big(\Sigma_1+\Sigma_2-2(\Sigma_1\Sigma_2)^{1/2}\big)
ML losses and metrics

Fβ score

F_β = (1+β²) P R / (β² P + R)

where β > 1 favours recall, β < 1 favours precision

Worked example: p = 0.8, r = 0.666667, b = 2 → 0.689655 ✓ checked

See also: F1 score

LaTeX source
F_\beta=\frac{(1+\beta^2)\,PR}{\beta^2P+R}
ML losses and metrics

GELU

GELU(x) = x Φ(x)

where Φ = standard normal cdf

The activation in BERT and GPT-style transformers.

Worked example: x = 1 → 0.841345 ✓ checked

See also: ReLU and leaky ReLU · normal cumulative distribution · Swish / SiLU

LaTeX source
\operatorname{GELU}(x)=x\,\Phi(x)=\tfrac{x}{2}\left[1+\operatorname{erf}\!\left(\tfrac{x}{\sqrt2}\right)\right]
ML losses and metrics

hinge loss

L = max(0, 1 − y f(x))

where y ∈ {−1,+1}

The SVM loss.

Worked example: y = 1, f = 0.3 → 0.7 ✓ checked

See also: support vector machine (soft margin)

LaTeX source
L=\max\big(0,\,1-y\,f(x)\big)
ML losses and metrics

Huber loss

L(a) = ½a² if |a| ≤ δ, else δ(|a| − ½δ)

where a = residual y − ŷ

Quadratic near zero, linear in the tails.

Worked example: a = 3, d = 1 → 2.5 ✓ checked

See also: mean squared error · mean absolute error

LaTeX source
L_\delta(a)=\begin{cases}\tfrac12a^2&|a|\le\delta\\ \delta\big(|a|-\tfrac12\delta\big)&|a|>\delta\end{cases}
ML losses and metrics

hyperbolic tangent

tanh x = (eˣ − e⁻ˣ)/(eˣ + e⁻ˣ)

Zero-centred, range (−1, 1).

Worked example: x = 1 → 0.761594 ✓ checked

See also: sigmoid (logistic function)

LaTeX source
\tanh x=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}=2\sigma(2x)-1
ML losses and metrics

inception score

IS = exp(E KL(p(y|x) ‖ p(y)))

High when each image is classified confidently and the classes are diverse.

Worked example: P = [[1, 0], [0, 1]] → 2 ✓ checked

See also: Fréchet inception distance

LaTeX source
\mathrm{IS}=\exp\Big(\mathbb E_x\,D_{\mathrm{KL}}\big(p(y\mid x)\,\|\,p(y)\big)\Big)
ML losses and metrics

intersection over union (Jaccard)

IoU = |A ∩ B| / |A ∪ B|

Standard for detection and segmentation.

Worked example: inter = 3, a = 5, b = 5 → 0.428571 ✓ checked

See also: Dice coefficient

LaTeX source
\mathrm{IoU}=\frac{|A\cap B|}{|A\cup B|}
ML losses and metrics

k-fold cross-validation estimate

average the error over k held-out folds

k = 5 or 10 is typical; leave-one-out is k = n.

Worked example: e = [0.1, 0.12, 0.08, 0.11, 0.09] → [0.1, 0.00707107] ✓ checked

See also: leave-one-out residual shortcut · bootstrap standard error

LaTeX source
\widehat{\mathrm{Err}}=\frac1k\sum_{i=1}^{k}\mathrm{Err}_i,\qquad \mathrm{SE}\approx\frac{s}{\sqrt k}
ML losses and metrics

KL-divergence loss (distillation)

L = τ² KL(softmax(z_t/τ) ‖ softmax(z_s/τ))

where t = teacher, s = student, τ = temperature

The τ² factor keeps gradient magnitudes comparable as τ changes.

Worked example: zt = [2, 0], zs = [1, 0], tau = 2 → 0.105378 ✓ checked

See also: Kullback–Leibler divergence · softmax with temperature

LaTeX source
L=\tau^2\,D_{\mathrm{KL}}\big(\operatorname{softmax}(z_t/\tau)\,\|\,\operatorname{softmax}(z_s/\tau)\big)
ML losses and metrics

label smoothing

y′ₖ = (1−ε)·1[k=y] + ε/K

where K classes, ε ≈ 0.1

Softens one-hot targets to discourage overconfidence.

Worked example: eps = 0.1, K = 4, y = 0 → [0.925, 0.025, 0.025, 0.025] ✓ checked

See also: softmax cross-entropy (from logits)

LaTeX source
y'_k=(1-\varepsilon)\,\mathbf{1}[k=y]+\frac{\varepsilon}{K}
ML losses and metrics

Levenshtein distance recurrence

dᵢⱼ = min(dᵢ₋₁,ⱼ + 1, dᵢ,ⱼ₋₁ + 1, dᵢ₋₁,ⱼ₋₁ + 1[aᵢ ≠ bⱼ])

Dynamic programming, O(mn).

Worked example: a = 'kitten', b = 'sitting' → 3 ✓ checked

See also: word error rate

LaTeX source
d_{i,j}=\min\big(d_{i-1,j}+1,\ d_{i,j-1}+1,\ d_{i-1,j-1}+\mathbf 1[a_i\ne b_j]\big)
ML losses and metrics

likelihood ratios and diagnostic odds

LR⁺ = TPR/FPR;  LR⁻ = FNR/TNR

Multiply the prior odds by LR to get the posterior odds.

Worked example: tpr = 0.8, fpr = 0.1 → [8, 0.222222] ✓ checked

See also: Bayes factor and posterior odds · specificity, NPV, FPR and FNR

LaTeX source
\mathrm{LR}^+=\frac{\mathrm{TPR}}{\mathrm{FPR}},\quad \mathrm{LR}^-=\frac{\mathrm{FNR}}{\mathrm{TNR}},\quad \mathrm{DOR}=\frac{\mathrm{LR}^+}{\mathrm{LR}^-}
ML losses and metrics

log-cosh loss

L = ln cosh(ŷ − y)

Behaves like ½a² near 0 and |a| − ln 2 in the tails; smooth everywhere.

Worked example: a = 2 → 1.325 ✓ checked

See also: Huber loss

LaTeX source
L=\ln\cosh(\hat y-y)
ML losses and metrics

log-sum-exp

LSE(z) = m + log Σ exp(zⱼ − m)

A smooth maximum: max(z) ≤ LSE(z) ≤ max(z) + log n.

Worked example: z = [0, 0] → 0.693147 ✓ checked

See also: softmax

LaTeX source
\operatorname{LSE}(z)=\log\sum_j e^{z_j}=m+\log\sum_j e^{z_j-m},\ m=\max_j z_j
ML losses and metrics

MAPE and sMAPE

MAPE = (100/n) Σ |(y − ŷ)/y|

MAPE explodes when y ≈ 0 and penalises over-forecasts less than under-forecasts.

Worked example: y = [100, 200], yh = [110, 180] → [10, 10.0251] ✓ checked

See also: mean absolute error

LaTeX source
\mathrm{MAPE}=\frac{100}n\sum\Big|\frac{y-\hat y}y\Big|,\qquad \mathrm{sMAPE}=\frac{100}n\sum\frac{2|y-\hat y|}{|y|+|\hat y|}
ML losses and metrics

margin ranking loss

L = max(0, −y(x₁ − x₂) + m)

where y = +1 if x₁ should rank higher

Worked example: x1 = 0.3, x2 = 0.5, y = 1, m = 0.2 → 0.4 ✓ checked

See also: hinge loss

LaTeX source
L=\max\big(0,\,-y(x_1-x_2)+m\big)
ML losses and metrics

Matthews correlation coefficient

MCC = (TP·TN − FP·FN) / √((TP+FP)(TP+FN)(TN+FP)(TN+FN))

Balanced even for imbalanced classes; ranges −1 to 1.

Worked example: tp = 8, fp = 2, fn = 4, tn = 6 → 0.408248 ✓ checked

See also: F1 score

LaTeX source
\mathrm{MCC}=\frac{TP\cdot TN-FP\cdot FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}}
ML losses and metrics

maximum calibration error (MCE)

MCE = max_b |acc(b) − conf(b)|

where same bins as ECE

The worst bin, however few examples it holds.

Worked example: gaps = [0.4, 0.4, 0.05] → 0.4 ✓ checked

See also: expected calibration error (ECE)

LaTeX source
\mathrm{MCE}=\max_{b}\big|\operatorname{acc}(b)-\operatorname{conf}(b)\big|
ML losses and metrics

mean absolute error

MAE = (1/n) Σ |yᵢ − ŷᵢ|

More robust to outliers than MSE.

Worked example: y = [1, 2, 3], yh = [1, 2, 5] → 0.666667 ✓ checked

See also: mean squared error · Huber loss

LaTeX source
\mathrm{MAE}=\frac1n\sum_i|y_i-\hat y_i|
ML losses and metrics

mean absolute scaled error

MASE = MAE / (MAE of the naive one-step forecast)

Below 1 beats the naive forecast; scale-free.

Worked example: y = [10, 12, 11, 15], yh = [11, 11, 12, 14] → 0.428571 ✓ checked

See also: MAPE and sMAPE

LaTeX source
\mathrm{MASE}=\frac{\frac1n\sum|y_t-\hat y_t|}{\frac1{n-1}\sum|y_t-y_{t-1}|}
ML losses and metrics

mean reciprocal rank

MRR = mean(1/rank of the first relevant result)

Worked example: ranks = [1, 3, 2] → 0.611111 ✓ checked

See also: DCG and NDCG

LaTeX source
\mathrm{MRR}=\frac1{|Q|}\sum_{q}\frac1{\mathrm{rank}_q}
ML losses and metrics

multi-class hinge loss (Weston–Watkins)

L = Σ_{j≠y} max(0, sⱼ − s_y + Δ)

where s = class scores

Worked example: s = [3.2, 5.1, -1.7], y = 0, d = 1 → 2.9 ✓ checked

See also: hinge loss

LaTeX source
L=\sum_{j\ne y}\max\big(0,\ s_j-s_y+\Delta\big)
ML losses and metrics

precision

Precision = TP / (TP + FP)

where TP/FP = true/false positives

Of the items flagged, how many were right.

Worked example: tp = 8, fp = 2 → 0.8 ✓ checked

See also: recall · F1 score

LaTeX source
\mathrm{Precision}=\frac{TP}{TP+FP}
ML losses and metrics

precision@k and recall@k

P@k, R@k

Worked example: rel = [1, 0, 1, 1, 0], k = 3, total = 4 → [0.666667, 0.5] ✓ checked

See also: average precision (PR-AUC)

LaTeX source
P@k=\frac{|\text{relevant in top }k|}k,\qquad R@k=\frac{|\text{relevant in top }k|}{|\text{relevant}|}
ML losses and metrics

Rand index and adjusted Rand index

RI = (agreeing pairs)/C(n, 2)

where a = pairs together in both, b = apart in both

ARI is 0 for random labelings and 1 for identical ones.

Worked example: a = 4, b = 8, n = 6 → 0.8 ✓ checked

See also: normalised mutual information

LaTeX source
\mathrm{RI}=\frac{a+b}{\binom n2},\qquad \mathrm{ARI}=\frac{\mathrm{RI}-\mathbb E[\mathrm{RI}]}{\max\mathrm{RI}-\mathbb E[\mathrm{RI}]}
ML losses and metrics

recall

Recall = TP / (TP + FN)

where FN = false negatives

Of the real positives, how many were found. Also called sensitivity or TPR.

Worked example: tp = 8, fn = 4 → 0.666667 ✓ checked

See also: precision · F1 score

LaTeX source
\mathrm{Recall}=\frac{TP}{TP+FN}
ML losses and metrics

ReLU and leaky ReLU

ReLU(x) = max(0, x)

where α ≈ 0.01

Gradient is 1 for x > 0, 0 for x < 0.

Worked example: x = -2, a = 0.01 → -0.02 ✓ checked

See also: GELU · softplus

LaTeX source
\operatorname{ReLU}(x)=\max(0,x),\qquad \operatorname{LeakyReLU}(x)=\max(\alpha x,x)
ML losses and metrics

root mean squared error

RMSE = √( (1/n) Σ (yᵢ − ŷᵢ)² )

Worked example: y = [1, 2, 3], yh = [1, 2, 5] → 1.1547 ✓ checked

See also: mean squared error

LaTeX source
\mathrm{RMSE}=\sqrt{\frac1n\sum_i(y_i-\hat y_i)^2}
ML losses and metrics

root mean squared log error

RMSLE = √(mean((ln(1 + ŷ) − ln(1 + y))²))

Cares about relative, not absolute, error.

Worked example: y = [3, 5], yh = [2, 6] → 0.230785 ✓ checked

See also: root mean squared error

LaTeX source
\mathrm{RMSLE}=\sqrt{\frac1n\sum\big(\ln(1+\hat y)-\ln(1+y)\big)^2}
ML losses and metrics

ROUGE-N

ROUGE-N = overlapping n-grams / n-grams in the reference (recall)

ROUGE-L uses the longest common subsequence.

Worked example: overlap = 4, ref = 6 → 0.666667 ✓ checked

See also: BLEU score · F1 score

LaTeX source
\mathrm{ROUGE\text{-}N}=\frac{\sum_{g\in\text{ref}}\min\big(\mathrm{count}_{\text{cand}}(g),\mathrm{count}_{\text{ref}}(g)\big)}{\sum_{g\in\text{ref}}\mathrm{count}_{\text{ref}}(g)}
ML losses and metrics

silhouette coefficient

s = (b − a)/max(a, b)

where a = mean distance to own cluster, b = mean distance to the nearest other cluster

Between −1 and 1; higher is better.

Worked example: a = 1, b = 3 → 0.666667 ✓ checked

See also: k-means objective

LaTeX source
s=\frac{b-a}{\max(a,b)}
ML losses and metrics

smooth L1 loss

L = ½a²/β if |a| < β, else |a| − ½β

Detection models (Faster R-CNN) use it for box regression.

Worked example: a = 0.5, b = 1 → 0.125 ✓ checked

See also: Huber loss

LaTeX source
L=\begin{cases}\tfrac12a^2/\beta&|a|<\beta\\ |a|-\tfrac12\beta&\text{otherwise}\end{cases}
ML losses and metrics

softmax with temperature

softmax(z/T)ₖ

where T > 1 flattens, T < 1 sharpens

Used for calibration and sampling.

Worked example: z = [1, 0], T = 2 → 0.622459 ✓ checked

See also: softmax

LaTeX source
\operatorname{softmax}(z/T)_k=\frac{e^{z_k/T}}{\sum_j e^{z_j/T}}
ML losses and metrics

softplus

softplus(x) = ln(1 + eˣ)

A smooth approximation of ReLU; its derivative is the sigmoid.

Worked example: x = 0 → 0.693147 ✓ checked

See also: ReLU and leaky ReLU · sigmoid (logistic function)

LaTeX source
\operatorname{softplus}(x)=\ln(1+e^{x})
ML losses and metrics

specificity, NPV, FPR and FNR

TNR = TN/(TN + FP);  NPV = TN/(TN + FN);  FPR = 1 − TNR;  FNR = 1 − TPR

Worked example: tp = 8, fp = 2, fn = 4, tn = 6 → [0.75, 0.6, 0.25, 0.333333] ✓ checked

See also: recall · precision

LaTeX source
\mathrm{TNR}=\frac{TN}{TN+FP},\ \ \mathrm{NPV}=\frac{TN}{TN+FN},\ \ \mathrm{FPR}=\frac{FP}{FP+TN},\ \ \mathrm{FNR}=\frac{FN}{FN+TP}
ML losses and metrics

structural similarity index (SSIM)

SSIM = (2μxμy + c₁)(2σxy + c₂)/((μx² + μy² + c₁)(σx² + σy² + c₂))

1 for identical images.

Worked example: mx = 0.5, my = 0.5, sx2 = 0.04, sy2 = 0.04, sxy = 0.04, c1 = 0.0001, c2 = 0.0009 → 1 ✓ checked

See also: peak signal-to-noise ratio

LaTeX source
\mathrm{SSIM}=\frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}{(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}
ML losses and metrics

Swish / SiLU

SiLU(x) = x σ(x)

Worked example: x = 1 → 0.731059 ✓ checked

See also: GELU · sigmoid (logistic function)

LaTeX source
\operatorname{SiLU}(x)=x\,\sigma(x)
ML losses and metrics

triplet loss

L = max(0, d(a, p) − d(a, n) + m)

where a = anchor, p = positive, n = negative, m = margin

Pulls matching pairs together and pushes others at least m apart.

Worked example: dp = 0.5, dn = 0.9, m = 0.5 → 0.1 ✓ checked

See also: contrastive loss (Hadsell) · InfoNCE (contrastive) loss

LaTeX source
L=\max\big(0,\ d(a,p)-d(a,n)+m\big)
ML losses and metrics

Tversky index

T = TP/(TP + αFP + βFN)

α = β = ½ is Dice; β > α favours recall.

Worked example: tp = 8, fp = 2, fn = 4, a = 0.3, b = 0.7 → 0.701754 ✓ checked

See also: Dice loss

LaTeX source
T=\frac{TP}{TP+\alpha FP+\beta FN}
ML losses and metrics

word error rate

WER = (S + D + I)/N

where S substitutions, D deletions, I insertions, N reference words

Can exceed 1. CER is the same at character level.

Worked example: S = 2, D = 1, I = 1, N = 20 → 0.2 ✓ checked

See also: Levenshtein distance recurrence

LaTeX source
\mathrm{WER}=\frac{S+D+I}{N}
ML losses and metrics

Youden's J and G-mean

J = TPR + TNR − 1;  G = √(TPR·TNR)

J picks the best ROC threshold.

Worked example: tpr = 0.8, tnr = 0.7 → [0.5, 0.748331] ✓ checked

See also: area under the ROC curve (AUC)

LaTeX source
J=\mathrm{TPR}+\mathrm{TNR}-1,\qquad G=\sqrt{\mathrm{TPR}\cdot\mathrm{TNR}}
ML models

AdaBoost

αₜ = ½ ln((1 − εₜ)/εₜ);  wᵢ ← wᵢ e^(−αₜ yᵢ hₜ(xᵢ))/Z

Misclassified points are up-weighted.

Worked example: e = 0.2 → 0.693147 ✓ checked

See also: exponential loss · gradient boosting

LaTeX source
\alpha_t=\tfrac12\ln\frac{1-\varepsilon_t}{\varepsilon_t},\qquad w_i\leftarrow w_i\,e^{-\alpha_ty_ih_t(x_i)}/Z_t
ML models

adaptive prediction sets (APS)

score = total probability of all classes at least as likely as y

Sets whose size adapts to difficulty; coverage still ≥ 1 − α.

Worked example: p = [0.6, 0.3, 0.1], y = 1 → 0.9 ✓ checked

LaTeX source
s(x,y)=\sum_{j:\hat p_j(x)\ge\hat p_y(x)}\hat p_j(x),\qquad \mathcal C(x)=\{y:\ s(x,y)\le\hat q\}
ML models

alternating least squares (matrix factorisation)

uᵢ = (VᵀV + λI)⁻¹Vᵀrᵢ over the items user i rated

Each step is a ridge regression; the basis of many recommender systems.

Worked example: V = [[1, 0], [0, 1], [1, 1]], r = [3, 4, 7], lam = 0 → [3, 4] ✓ checked

See also: ridge regression (closed form)

LaTeX source
\mathbf u_i=\Big(V_{\Omega_i}^{\top}V_{\Omega_i}+\lambda I\Big)^{-1}V_{\Omega_i}^{\top}\mathbf r_i
ML models

angle between vectors

θ = arccos(x·y/(‖x‖‖y‖))

Worked example: x = [1, 0], y = [1, 1] → 0.785398 ✓ checked

See also: cosine similarity · dot product

LaTeX source
\theta=\arccos\frac{\mathbf x\cdot\mathbf y}{\|\mathbf x\|\|\mathbf y\|}
ML models

bagging and out-of-bag fraction

(1 − 1/n)ⁿ → e⁻¹ ≈ 0.368

About 63.2% of the data appears in each bootstrap; the rest is a free validation set (out-of-bag error).

Worked example: n = 100000 → 0.367878 ✓ checked

See also: variance of an averaged ensemble · bootstrap standard error

LaTeX source
P(\text{example not in a bootstrap sample})=\Big(1-\frac1n\Big)^n\xrightarrow{n\to\infty}e^{-1}\approx0.368
ML models

Bayesian linear regression

posterior N(m_N, S_N); predictive variance = noise + parameter uncertainty

where α = prior precision, β = noise precision

m_N is the ridge solution with λ = α/β.

Worked example: Phi = [[1, 0], [1, 1], [1, 2]], t = [1, 3, 5], al = 1e-09, be = 1 → [1, 2] ✓ checked

See also: ridge regression (closed form) · Gaussian process posterior

LaTeX source
S_N=\big(\alpha I+\beta\Phi^{\top}\Phi\big)^{-1},\ \ \mathbf m_N=\beta S_N\Phi^{\top}\mathbf t,\ \ p(t_*)=\mathcal N\big(\mathbf m_N^{\top}\boldsymbol\phi_*,\ \beta^{-1}+\boldsymbol\phi_*^{\top}S_N\boldsymbol\phi_*\big)
ML models

BM25

idf × f(k₁ + 1)/(f + k₁(1 − b + b|d|/avgdl))

where k₁ ≈ 1.2, b ≈ 0.75

The standard lexical ranking function.

Worked example: N = 1000, df = 10, f = 3, k1 = 1.2, b = 0.75, dl = 100, avg = 100 → 7.14503 ✓ checked

See also: TF-IDF

LaTeX source
\mathrm{score}(q,d)=\sum_{t\in q}\ln\frac{N-\mathrm{df}+0.5}{\mathrm{df}+0.5}\cdot\frac{f(k_1+1)}{f+k_1\big(1-b+b\frac{|d|}{\mathrm{avgdl}}\big)}
ML models

common kernels

linear, polynomial, Laplace, Matérn 3/2

Worked example: x = [1, 2], y = [3, 1], c = 1, d = 2, l = 1 → [5, 36, 0.106878, 0.10134] ✓ checked

See also: RBF (Gaussian) kernel

LaTeX source
k_{\text{lin}}=\mathbf x^{\top}\mathbf x',\quad k_{\text{poly}}=(\mathbf x^{\top}\mathbf x'+c)^d,\quad k_{\text{Laplace}}=e^{-\|\mathbf x-\mathbf x'\|/\ell},\quad k_{\text{Mat\'ern}}^{3/2}=\Big(1+\tfrac{\sqrt3r}{\ell}\Big)e^{-\sqrt3r/\ell}
ML models

composition and subsampling

privacy budgets add up; subsampling amplifies privacy

where q = sampling rate

DP-SGD tracks this with the moments (RDP) accountant.

Worked example: e = 1, q = 0.01, k = 100 → [100, 0.0170369] ✓ checked

See also: differential privacy

LaTeX source
\text{basic: }\varepsilon_{tot}=\sum_i\varepsilon_i;\qquad \text{advanced: }\varepsilon'=\varepsilon\sqrt{2k\ln(1/\delta')}+k\varepsilon(e^\varepsilon-1);\qquad \text{subsampling: }\ln\big(1+q(e^\varepsilon-1)\big)
ML models

DBSCAN neighbourhood

core point: at least minPts points within ε

No k needed; finds arbitrary shapes and flags noise.

Worked example: d = [0.1, 0.2, 0.9, 0.3], eps = 0.5, minpts = 3 → 1 ✓ checked

See also: k-means objective

LaTeX source
N_\varepsilon(p)=\{q:\ d(p,q)\le\varepsilon\};\ \ p\text{ is a core point if }|N_\varepsilon(p)|\ge\text{minPts}
ML models

demographic parity and disparate impact

ΔDP = |P(ŷ = 1 | A = 0) − P(ŷ = 1 | A = 1)|;  disparate impact ≥ 0.8

where A = protected attribute

The four-fifths rule of US employment law.

Worked example: p0 = 0.5, p1 = 0.35 → [0.15, 0.7] ✓ checked

See also: equalised odds and equal opportunity

LaTeX source
\Delta_{DP}=\big|P(\hat y=1\mid A=0)-P(\hat y=1\mid A=1)\big|,\qquad \mathrm{DI}=\frac{P(\hat y=1\mid A=1)}{P(\hat y=1\mid A=0)}\ \ (\ge0.8)
ML models

differential privacy

P(M(D) ∈ S) ≤ e^ε P(M(D′) ∈ S) + δ

Smaller ε means stronger privacy.

Worked example: e = 1 → 2.71828 ✓ checked

See also: Laplace and Gaussian mechanisms

LaTeX source
P\big(\mathcal M(D)\in S\big)\le e^{\varepsilon}P\big(\mathcal M(D')\in S\big)+\delta\quad\text{for neighbouring }D,D'
ML models

elastic net

R(w) = λ( α‖w‖₁ + (1−α)/2 ‖w‖₂² )

where α mixes L1 and L2

Worked example: w = [1, -2], lam = 0.1, a = 0.5 → 0.275 ✓ checked

See also: L1 penalty (lasso) · L2 penalty (weight decay)

LaTeX source
R(\mathbf w)=\lambda\Big(\alpha\|\mathbf w\|_1+\tfrac{1-\alpha}{2}\|\mathbf w\|_2^2\Big)
ML models

EM for Gaussian mixtures

E-step: responsibilities γ;  M-step: re-estimate πₖ, μₖ, Σₖ

Each iteration never decreases the likelihood.

Worked example: x = [0, 4], mu = [0, 4], s = [1, 1], pi = [0.5, 0.5] → 0.999665 ✓ checked

See also: Gaussian mixture density · k-means objective

LaTeX source
\gamma_{ik}=\frac{\pi_k\mathcal N(x_i\mid\mu_k,\Sigma_k)}{\sum_j\pi_j\mathcal N(x_i\mid\mu_j,\Sigma_j)};\ \ N_k=\sum_i\gamma_{ik},\ \mu_k=\frac1{N_k}\sum_i\gamma_{ik}x_i,\ \pi_k=\frac{N_k}N
ML models

equalised odds and equal opportunity

equal TPR and FPR across groups

Several fairness criteria cannot hold simultaneously unless base rates are equal (impossibility theorem).

Worked example: tpr0 = 0.8, tpr1 = 0.7, fpr0 = 0.1, fpr1 = 0.15 → [0.1, 0.05] ✓ checked

See also: demographic parity and disparate impact

LaTeX source
P(\hat y=1\mid y=y_0,A=a)\ \text{equal across }a,\ y_0\in\{0,1\};\qquad \text{equal opportunity: only }y=1
ML models

factorisation machine

pairwise interactions through low-rank factors, computed in O(kn)

Worked example: x = [1, 2, 0], V = [[1, 0.5], [0.5, 1], [2, 0]] → [2, 2] ✓ checked

See also: alternating least squares (matrix factorisation)

LaTeX source
\hat y=w_0+\sum_iw_ix_i+\sum_{i<j}\langle\mathbf v_i,\mathbf v_j\rangle x_ix_j=w_0+\mathbf w^{\top}\mathbf x+\tfrac12\sum_f\Big[\big(\sum_iv_{if}x_i\big)^2-\sum_iv_{if}^2x_i^2\Big]
ML models

federated averaging

w ← Σ (n_k/n) w^(k)

Clients train locally; the server averages their weights by data size.

Worked example: n = [100, 300], w = [1, 2] → 1.75 ✓ checked

See also: exponential moving average

LaTeX source
w_{t+1}=\sum_{k=1}^{K}\frac{n_k}{n}\,w_{t+1}^{(k)}
ML models

Fisher's linear discriminant

w ∝ S_W⁻¹(μ₁ − μ₀)

where S_W = within-class scatter

Worked example: Sw = [[2, 0], [0, 1]], d = [2, 1] → [1, 1] ✓ checked

See also: Mahalanobis distance

LaTeX source
\mathbf w\propto S_W^{-1}(\boldsymbol\mu_1-\boldsymbol\mu_0),\qquad J(\mathbf w)=\frac{\big(\mathbf w^{\top}(\boldsymbol\mu_1-\boldsymbol\mu_0)\big)^2}{\mathbf w^{\top}S_W\mathbf w}
ML models

Gaussian discriminant (LDA / QDA)

δₖ(x) = −½(x − μₖ)ᵀΣₖ⁻¹(x − μₖ) − ½ ln|Σₖ| + ln πₖ

where shared Σ gives LDA (linear boundary), per-class Σₖ gives QDA

Worked example: x = [1], mu = 0, S = 1, pi = 0.5 → -1.19315 ✓ checked

See also: Fisher's linear discriminant

LaTeX source
\delta_k(x)=-\tfrac12(x-\mu_k)^{\top}\Sigma_k^{-1}(x-\mu_k)-\tfrac12\ln|\Sigma_k|+\ln\pi_k
ML models

Gaussian mixture density

p(x) = Σₖ πₖ N(x | μₖ, σₖ²)

where πₖ = mixing weights

Fit by expectation–maximisation.

Worked example: pi = [0.5, 0.5], mu = [0, 2], s = [1, 1], x = 0 → 0.226467 ✓ checked

See also: normal (Gaussian) density

LaTeX source
p(x)=\sum_{k}\pi_k\,\mathcal N(x\mid\mu_k,\sigma_k^2),\quad \sum_k\pi_k=1
ML models

Gaussian naive Bayes

log prior + Σ per-feature Gaussian log-likelihoods

Worked example: x = [1, 2], mu = [0, 2], s2 = [1, 4], prior = 0.5 → -3.72417 ✓ checked

See also: naive Bayes

LaTeX source
\ln P(y\mid\mathbf x)=\ln P(y)-\sum_i\Big[\tfrac12\ln(2\pi\sigma_{iy}^2)+\frac{(x_i-\mu_{iy})^2}{2\sigma_{iy}^2}\Big]+\text{const}
ML models

Gaussian process log marginal likelihood

ln p(y) = −½yᵀA⁻¹y − ½ ln|A| − (n/2) ln 2π,  A = K + σ²I

Maximise over kernel hyperparameters: a built-in Occam's razor.

Worked example: K = [[1, 0.5], [0.5, 1]], y = [1, 2], s2 = 0.1 → -3.64038 ✓ checked

See also: Gaussian process posterior

LaTeX source
\ln p(\mathbf y)=-\tfrac12\mathbf y^{\top}(K+\sigma^2I)^{-1}\mathbf y-\tfrac12\ln|K+\sigma^2I|-\tfrac n2\ln2\pi
ML models

Gaussian process posterior

μ* = K*ᵀ(K + σ²I)⁻¹y;  σ*² = k** − K*ᵀ(K + σ²I)⁻¹K*

Exact Bayesian regression with a kernel prior; O(n³).

Worked example: K = [[1, 0.5], [0.5, 1]], ks = [0.8, 0.6], kss = 1, y = [1, 2], s2 = 0.1 → [1.14583, 0.354167] ✓ checked

See also: multivariate normal: conditional distribution · kernel ridge regression

LaTeX source
\mu_*=K_*^{\top}(K+\sigma^2I)^{-1}\mathbf y,\qquad \sigma_*^2=k_{**}-K_*^{\top}(K+\sigma^2I)^{-1}K_*
ML models

Gini impurity

G = 1 − Σ pₖ²

where pₖ = class proportions in a node

0 for a pure node.

Worked example: p = [0.5, 0.5] → 0.5 ✓ checked

See also: information gain

LaTeX source
G=1-\sum_k p_k^2
ML models

GloVe loss

J = Σ f(Xᵢⱼ)(wᵢᵀw̃ⱼ + bᵢ + b̃ⱼ − ln Xᵢⱼ)²

Worked example: x = 10, xmax = 100, s = 2 → 0.0162815 ✓ checked

See also: skip-gram with negative sampling

LaTeX source
J=\sum_{i,j}f(X_{ij})\big(\mathbf w_i^{\top}\tilde{\mathbf w}_j+b_i+\tilde b_j-\ln X_{ij}\big)^2,\quad f(x)=\min\big((x/x_{\max})^{3/4},1\big)
ML models

gradient boosting

fit each tree to the negative gradient of the loss

where ν = shrinkage

For squared error the pseudo-residual is y − F; for log loss it is y − p.

Worked example: y = 1, F = 0 → [1, 0.5] ✓ checked

See also: XGBoost leaf weight and split gain · AdaBoost

LaTeX source
F_m(x)=F_{m-1}(x)+\nu\,h_m(x),\quad h_m\ \text{fits}\ r_{im}=-\Big[\frac{\partial L(y_i,F(x_i))}{\partial F(x_i)}\Big]_{F=F_{m-1}}
ML models

HMM forward algorithm

αₜ(j) = [Σᵢ αₜ₋₁(i)Aᵢⱼ] Bⱼ(oₜ)

where A = transitions, B = emissions

Dynamic programming in O(TN²). Replace the sum by a max for Viterbi.

Worked example: A = [[0.7, 0.3], [0.4, 0.6]], B = [[0.9, 0.1], [0.2, 0.8]], pi = [0.6, 0.4], o = [0, 1] → 0.209 ✓ checked

See also: Viterbi algorithm

LaTeX source
\alpha_t(j)=\Big[\sum_i\alpha_{t-1}(i)A_{ij}\Big]B_j(o_t),\quad P(O)=\sum_j\alpha_T(j)
ML models

information gain

IG = H(parent) − Σⱼ (nⱼ/n) H(childⱼ)

The split criterion of ID3/C4.5 trees.

Worked example: hp = 0.693147, w = [0.5, 0.5], hc = [0, 0] → 0.693147 ✓ checked

See also: Shannon entropy · Gini impurity

LaTeX source
\mathrm{IG}=H(\text{parent})-\sum_j\frac{n_j}{n}H(\text{child}_j)
ML models

isotonic regression (pool adjacent violators)

pool adjacent violators: replace out-of-order neighbours by their mean

A monotone, non-parametric fit; used to calibrate scores.

Worked example: y = [1, 3, 2, 4] → [1, 2.5, 2.5, 4] ✓ checked

See also: Platt scaling

LaTeX source
\min\sum(y_i-f_i)^2\ \text{s.t. }f_1\le f_2\le\cdots\le f_n
ML models

k-means objective

J = Σₙ Σₖ rₙₖ ‖xₙ − μₖ‖²

where rₙₖ = 1 if point n is assigned to cluster k

Lloyd's algorithm alternates assignment and mean updates; J never increases.

Worked example: X = [[0, 0], [2, 0]], mu = [1, 0] → 2 ✓ checked

See also: principal component analysis

LaTeX source
J=\sum_{n}\sum_{k}r_{nk}\,\|\mathbf x_n-\boldsymbol\mu_k\|^2
ML models

k-means update steps

assign to the nearest centroid, then move each centroid to its cluster mean

Worked example: x = [[0, 0], [0, 2], [10, 0]], mu = [[0, 1], [10, 0]] → [[0, 1], [10, 0]] ✓ checked

See also: k-means objective · k-means++ seeding

LaTeX source
c_i=\arg\min_k\|x_i-\mu_k\|^2,\qquad \mu_k=\frac1{|C_k|}\sum_{i\in C_k}x_i
ML models

k-means++ seeding

choose the next centre with probability ∝ D(x)²

where D(x) = distance to the nearest chosen centre

O(log k)-competitive with the optimum in expectation.

Worked example: d = [0, 1, 3] → [0, 0.1, 0.9] ✓ checked

See also: k-means update steps

LaTeX source
P(x)=\frac{D(x)^2}{\sum_{x'}D(x')^2}
ML models

k-nearest-neighbour prediction

majority (or distance-weighted) vote of the k nearest points

Worked example: labels = [1, 1, 0], d = [1, 2, 0.5] → 0 ✓ checked

See also: Cover–Hart bound for nearest neighbours

LaTeX source
\hat y(x)=\arg\max_c\sum_{i\in N_k(x)}w_i\mathbf 1[y_i=c],\quad w_i=\frac1{d(x,x_i)}\ \text{(optional)}
ML models

Kalman filter

predict with F, Q;  update with gain K = P⁻Hᵀ(HP⁻Hᵀ + R)⁻¹

The exact Bayesian filter for linear-Gaussian state-space models.

Worked example: x = 0, P = 1, z = 2, R = 1 → [1, 0.5] ✓ checked

See also: multivariate normal: conditional distribution · HMM forward algorithm

LaTeX source
\text{predict: }\hat x^-=F\hat x,\ P^-=FPF^{\top}+Q;\quad \text{update: }K=P^-H^{\top}(HP^-H^{\top}+R)^{-1},\ \hat x=\hat x^-+K(z-H\hat x^-),\ P=(I-KH)P^-
ML models

kernel PCA centering

K̃ = K − 1ₙK − K1ₙ + 1ₙK1ₙ

Centres the data in feature space; then eigendecompose K̃.

Worked example: K = [[2, 1], [1, 2]] → [[0.5, -0.5], [-0.5, 0.5]] ✓ checked

See also: PCA via SVD

LaTeX source
\tilde K=K-\mathbf 1_nK-K\mathbf 1_n+\mathbf 1_nK\mathbf 1_n,\quad \mathbf 1_n=\tfrac1n\mathbf 1\mathbf 1^{\top}
ML models

kernel ridge regression

α = (K + λI)⁻¹y;  f(x) = Σ αᵢ k(xᵢ, x)

Equals the GP posterior mean with noise variance λ.

Worked example: K = [[1, 0.5], [0.5, 1]], y = [1, 2], lam = 0.5 → [0.25, 1.25] ✓ checked

See also: Gaussian process posterior · RBF (Gaussian) kernel

LaTeX source
\boldsymbol\alpha=(K+\lambda I)^{-1}\mathbf y,\qquad \hat f(x)=\sum_i\alpha_i\,k(x_i,x)
ML models

Laplace and Gaussian mechanisms

add Laplace noise of scale Δf/ε

where Δf = sensitivity

Worked example: d = 1, e = 0.5, dl = 1e-05 → [2, 9.68961] ✓ checked

See also: differential privacy

LaTeX source
\mathcal M(D)=f(D)+\operatorname{Lap}\big(\Delta f/\varepsilon\big),\qquad \sigma=\frac{\Delta f\sqrt{2\ln(1.25/\delta)}}\varepsilon\ \ (\text{Gaussian})
ML models

naive Bayes

P(y|x) ∝ P(y) Πᵢ P(xᵢ|y)

where Features assumed independent given the class

In practice add log-probabilities.

Worked example: prior = 0.5, lik = [0.8, 0.5] → 0.2 ✓ checked

See also: Bayes' theorem

LaTeX source
P(y\mid\mathbf x)\propto P(y)\prod_i P(x_i\mid y)
ML models

non-negative matrix factorisation (multiplicative updates)

H ← H ∘ (WᵀV)/(WᵀWH);  W ← W ∘ (VHᵀ)/(WHHᵀ)

Lee–Seung updates; keep everything non-negative and never increase ‖V − WH‖.

Worked example: V = [[1, 2], [2, 4]], W = [[1], [1]], H = [[1, 1]] → [[1.5, 3]] ✓ checked

See also: PCA via SVD

LaTeX source
H\leftarrow H\circ\frac{W^{\top}V}{W^{\top}WH},\qquad W\leftarrow W\circ\frac{VH^{\top}}{WHH^{\top}}
ML models

particle filter (bootstrap) weights

wᵢ ∝ wᵢ p(z | xᵢ);  N_eff = 1/Σwᵢ²

Sequential Monte Carlo for non-linear, non-Gaussian filtering.

Worked example: w = [0.5, 0.3, 0.2] → 2.63158 ✓ checked

See also: effective sample size · Kalman filter

LaTeX source
w_i\propto w_i\,p(z\mid x_i),\quad N_{\text{eff}}=\frac1{\sum_iw_i^2}\ \text{(resample if small)}
ML models

PCA via SVD

components = V, variances = σₖ²/(n − 1)

where X_c = centred data

Worked example: X = [[1, 0], [-1, 0], [0, 2], [0, -2]] → [2.66667, 0.666667] ✓ checked

See also: principal component analysis · singular value decomposition

LaTeX source
X_c=U\Sigma V^{\top},\quad \text{components }=V,\quad \text{scores }=U\Sigma,\quad \text{variance}_k=\frac{\sigma_k^2}{n-1}
ML models

perceptron mistake bound (Novikoff)

mistakes ≤ (R/γ)²

where R = max ‖x‖, γ = margin

Worked example: R = 2, g = 0.5 → 16 ✓ checked

See also: perceptron update

LaTeX source
\#\text{mistakes}\le\Big(\frac R\gamma\Big)^2
ML models

perceptron update

if a mistake: w ← w + y x

Converges in at most (R/γ)² mistakes when the data are separable with margin γ.

Worked example: w = [0, 0], x = [1, 2], y = 1 → [1, 2] ✓ checked

See also: support vector machine (soft margin)

LaTeX source
\text{if }y\,\mathbf w^{\top}\mathbf x\le0:\quad \mathbf w\leftarrow\mathbf w+y\,\mathbf x
ML models

Platt scaling

P(y = 1 | s) = σ(As + B)

where s = classifier score; A, B fitted on validation data by maximum likelihood

Calibrates SVM and boosting scores; temperature scaling is the one-parameter version.

Worked example: A = 2, B = -1, s = 1 → 0.731059 ✓ checked

See also: isotonic regression (pool adjacent violators)

LaTeX source
P(y=1\mid s)=\sigma(As+B)
ML models

probabilistic PCA

σ̂² = mean of the discarded eigenvalues

PCA as a latent-variable model; gives a likelihood.

Worked example: lam = [4, 1, 0.5, 0.5], q = 2 → 0.5 ✓ checked

See also: principal component analysis

LaTeX source
\hat\sigma^2=\frac1{d-q}\sum_{j=q+1}^{d}\lambda_j,\qquad W=U_q(\Lambda_q-\hat\sigma^2I)^{1/2}
ML models

randomised response

answer truthfully with probability e^ε/(1 + e^ε), and debias the aggregate

The simplest local-DP mechanism.

Worked example: e = 1, pt = 0.4 → 0.4 ✓ checked

See also: differential privacy

LaTeX source
P(\text{truth})=\frac{e^\varepsilon}{1+e^\varepsilon},\qquad \hat p=\frac{\tilde p-(1-q)}{2q-1}
ML models

RBF (Gaussian) kernel

k(x, x′) = exp(−‖x − x′‖²/2ℓ²)

where ℓ = length scale, γ = 1/(2ℓ²)

Positive definite; corresponds to an infinite-dimensional feature space.

Worked example: x = [0, 0], y = [1, 1], l = 1 → 0.367879 ✓ checked

See also: Gram matrix · Gaussian process posterior

LaTeX source
k(\mathbf x,\mathbf x')=\exp\!\Big(-\frac{\|\mathbf x-\mathbf x'\|^2}{2\ell^2}\Big)=\exp\!\big(-\gamma\|\mathbf x-\mathbf x'\|^2\big)
ML models

skip-gram with negative sampling

L = −ln σ(u_oᵀv_c) − Σ ln σ(−u_kᵀv_c)

where o = observed context word, k = sampled negatives

Implicitly factorises the shifted PMI matrix.

Worked example: pos = 2, neg = [-1, 0.5] → 1.41427 ✓ checked

See also: sigmoid (logistic function) · GloVe loss

LaTeX source
L=-\ln\sigma(\mathbf u_o^{\top}\mathbf v_c)-\sum_{k=1}^{K}\ln\sigma\big(-\mathbf u_k^{\top}\mathbf v_c\big)
ML models

support vector machine (soft margin)

min ½‖w‖² + C Σ ξᵢ   s.t. yᵢ(wᵀxᵢ + b) ≥ 1 − ξᵢ, ξᵢ ≥ 0

where C trades margin width against violations ξ

Worked example: w = [3, 4], C = 1, xi = [0, 0.5] → 13 ✓ checked

See also: SVM margin width · hinge loss · KKT stationarity (inequality constraints)

LaTeX source
\min_{\mathbf w,b,\xi}\ \tfrac12\|\mathbf w\|^2+C\sum_i\xi_i\quad\text{s.t. }y_i(\mathbf w^{\top}\mathbf x_i+b)\ge1-\xi_i,\ \xi_i\ge0
ML models

SVM margin width

margin = 2 / ‖w‖

Maximising the margin means minimising ‖w‖.

Worked example: w = [3, 4] → 0.4 ✓ checked

See also: support vector machine (soft margin)

LaTeX source
\text{margin}=\frac{2}{\|\mathbf w\|}
ML models

t-SNE

Gaussian affinities in the data space, Student-t (1 dof) affinities in the map, minimise KL

The heavy-tailed t kernel avoids crowding. Perplexity = 2^H(Pᵢ) sets σᵢ.

Worked example: d2 = 1 → 0.5 ✓ checked

See also: Kullback–Leibler divergence

LaTeX source
p_{j|i}=\frac{e^{-\|x_i-x_j\|^2/2\sigma_i^2}}{\sum_{k\ne i}e^{-\|x_i-x_k\|^2/2\sigma_i^2}},\quad q_{ij}=\frac{(1+\|y_i-y_j\|^2)^{-1}}{\sum_{k\ne l}(1+\|y_k-y_l\|^2)^{-1}},\quad C=\mathrm{KL}(P\|Q)
ML models

TF-IDF

tf-idf = tf × ln(N/df)

where N = documents, df = documents containing t

Common-word terms get weights near 0.

Worked example: tf = 3, N = 1000, df = 10 → 13.8155 ✓ checked

See also: BM25

LaTeX source
\mathrm{tfidf}(t,d)=\mathrm{tf}(t,d)\cdot\ln\frac{N}{\mathrm{df}(t)}
ML models

variance of an averaged ensemble

Var = ρσ² + (1−ρ)σ²/B

where B models, pairwise correlation ρ, variance σ²

Averaging only removes the uncorrelated part: decorrelate the models (random forests).

Worked example: s2 = 1, rho = 0.5, B = 10 → 0.55 ✓ checked

See also: bias–variance decomposition

LaTeX source
\operatorname{Var}\!\Big(\frac1B\sum_b f_b\Big)=\rho\sigma^2+\frac{1-\rho}{B}\sigma^2
ML models

Viterbi algorithm

δₜ(j) = maxᵢ[δₜ₋₁(i)Aᵢⱼ] Bⱼ(oₜ)

The most likely hidden-state sequence.

Worked example: A = [[0.7, 0.3], [0.4, 0.6]], B = [[0.9, 0.1], [0.2, 0.8]], pi = [0.6, 0.4], o = [0, 1] → 0.1296 ✓ checked

See also: HMM forward algorithm

LaTeX source
\delta_t(j)=\max_i\big[\delta_{t-1}(i)A_{ij}\big]B_j(o_t),\quad \text{backtrack the argmax}
ML models

Ward's linkage

Δ = |A||B|/(|A| + |B|) · ‖μ_A − μ_B‖²

Merges the pair that least increases the within-cluster variance.

Worked example: nA = 3, nB = 5, d2 = 4 → 7.5 ✓ checked

See also: k-means objective

LaTeX source
\Delta(A,B)=\frac{|A||B|}{|A|+|B|}\,\|\mu_A-\mu_B\|^2
ML models

XGBoost leaf weight and split gain

w* = −G/(H + λ);  gain = ½[G_L²/(H_L + λ) + G_R²/(H_R + λ) − (G_L + G_R)²/(H + λ)] − γ

where G, H = sums of first and second derivatives of the loss in the leaf

Worked example: GL = -4, HL = 4, GR = 3, HR = 3, lam = 1, g = 0 → [0.8, 2.6625] ✓ checked

See also: gradient boosting

LaTeX source
w^*=-\frac{G}{H+\lambda},\qquad \text{Gain}=\tfrac12\Big[\frac{G_L^2}{H_L+\lambda}+\frac{G_R^2}{H_R+\lambda}-\frac{(G_L+G_R)^2}{H_L+H_R+\lambda}\Big]-\gamma
Deep learning

additive (Bahdanau) attention score

eᵢⱼ = vᵀ tanh(W₁sᵢ + W₂hⱼ);  α = softmax(e)

The original neural-translation attention.

Worked example: e = [1, 2, 3] → [0.0900306, 0.244728, 0.665241] ✓ checked

See also: scaled dot-product attention

LaTeX source
e_{ij}=\mathbf v^{\top}\tanh(W_1\mathbf s_i+W_2\mathbf h_j),\quad \alpha_{ij}=\operatorname{softmax}_j(e_{ij}),\quad \mathbf c_i=\sum_j\alpha_{ij}\mathbf h_j
Deep learning

affine quantisation

q = round(x/s) + z;  x̂ = s(q − z)

where b bits, scale s, zero-point z

Worst-case rounding error is s/2.

Worked example: lo = -1, hi = 1, b = 8, x = 0.3 → 1 ✓ checked

See also: machine epsilon and floating-point precision

LaTeX source
q=\operatorname{clip}\big(\operatorname{round}(x/s)+z,\ 0,\ 2^b-1\big),\quad s=\frac{x_{\max}-x_{\min}}{2^b-1},\quad \hat x=s\,(q-z)
Deep learning

ALiBi attention bias

score − m·(i − j)

where m = head-specific slope

A linear distance penalty instead of position embeddings; extrapolates to longer contexts.

Worked example: qk = 2, m = 0.5, i = 10, j = 6 → 0 ✓ checked

See also: rotary position embedding (RoPE)

LaTeX source
\operatorname{softmax}\big(q_i k_j^{\top}-m\,(i-j)\big),\quad m_h=2^{-8h/H}
Deep learning

backpropagation (layer error)

δ⁽ˡ⁾ = (W⁽ˡ⁺¹⁾)ᵀ δ⁽ˡ⁺¹⁾ ⊙ σ′(z⁽ˡ⁾)

∂L/∂W⁽ˡ⁾ = δ⁽ˡ⁾ (a⁽ˡ⁻¹⁾)ᵀ

Worked example: W = [[1, 2]], d = [0.5], sp = [1, 0.5] → [0.5, 0.5] ✓ checked

See also: chain rule

LaTeX source
\boldsymbol\delta^{(l)}=\big(W^{(l+1)}\big)^{\top}\boldsymbol\delta^{(l+1)}\odot\sigma'\!\big(\mathbf z^{(l)}\big)
Deep learning

batch normalisation

x̂ = (x − μ_B)/√(σ²_B + ε);  y = γx̂ + β

where μ_B, σ²_B = batch statistics; γ, β learned

Uses running averages at inference time.

Worked example: x = [1, 3], eps = 1e-05 → [-0.999995, 0.999995] ✓ checked

See also: layer normalisation · RMSNorm

LaTeX source
\hat x=\frac{x-\mu_B}{\sqrt{\sigma_B^2+\epsilon}},\quad y=\gamma\hat x+\beta
Deep learning

batch-norm running statistics

running = (1 − m)·running + m·batch  (m ≈ 0.1)

Used at inference time in place of batch statistics.

Worked example: run = 0, b = 1, m = 0.1 → 0.1 ✓ checked

See also: batch normalisation · exponential moving average

LaTeX source
\mu_{\text{run}}\leftarrow(1-m)\mu_{\text{run}}+m\,\mu_B,\qquad \sigma^2_{\text{run}}\leftarrow(1-m)\sigma^2_{\text{run}}+m\,\sigma^2_B
Deep learning

beam search with length normalisation

score = ln P(Y|X) / ((5 + |Y|)/6)^α

where α ≈ 0.6

Without it beam search prefers short outputs.

Worked example: lp = -6, n = 7, a = 0.6 → -3.95852 ✓ checked

See also: top-k, top-p and temperature sampling

LaTeX source
\operatorname{score}(Y)=\frac{\ln P(Y\mid X)}{\big((5+|Y|)/6\big)^{\alpha}}
Deep learning

classifier-free guidance

ε̃ = (1 + w)ε(x, c) − wε(x, ∅)

where w = guidance strength

Extrapolates away from the unconditional prediction toward the conditioned one.

Worked example: ec = 0.8, eu = 0.2, w = 3 → 2.6 ✓ checked

See also: DDPM reverse step

LaTeX source
\tilde\varepsilon=(1+w)\,\varepsilon_\theta(x_t,c)-w\,\varepsilon_\theta(x_t,\varnothing)
Deep learning

compute-optimal training (Chinchilla)

D ≈ 20N tokens;  N and D both grow as √C

Scale parameters and data together. Many deployed models are deliberately over-trained for cheaper inference.

Worked example: C = 5.76e+23 → [6.9282e+10, 1.38564e+12] ✓ checked

See also: parametric scaling law · training compute estimate

LaTeX source
D^*\approx20\,N,\qquad N^*\propto C^{0.5},\ D^*\propto C^{0.5},\qquad C\approx6ND
Deep learning

convolution output size

n_out = ⌊(n + 2p − k)/s⌋ + 1

where n input size, k kernel, p padding, s stride

Worked example: n = 224, k = 7, p = 3, s = 2 → 112 ✓ checked

See also: parameter counts

LaTeX source
n_{out}=\left\lfloor\frac{n+2p-k}{s}\right\rfloor+1
Deep learning

DDIM deterministic step

predict x̂₀, then jump to the earlier noise level

Allows far fewer sampling steps than DDPM.

Worked example: x = 1, e = 0.5, ab_t = 0.5, ab_p = 0.8 → 1.0413 ✓ checked

See also: DDPM reverse step

LaTeX source
\hat x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\varepsilon_\theta}{\sqrt{\bar\alpha_t}},\qquad x_{t-1}=\sqrt{\bar\alpha_{t-1}}\,\hat x_0+\sqrt{1-\bar\alpha_{t-1}}\,\varepsilon_\theta
Deep learning

DDPM reverse step

μ = (xₜ − βₜ/√(1 − ᾱₜ) ε_θ)/√αₜ;  β̃ₜ = (1 − ᾱₜ₋₁)/(1 − ᾱₜ) βₜ

Worked example: x = 1, e = 0.5, beta = 0.02, ab = 0.5 → 0.995867 ✓ checked

See also: diffusion forward process · diffusion training loss

LaTeX source
\mu_\theta(x_t,t)=\frac1{\sqrt{\alpha_t}}\Big(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\varepsilon_\theta(x_t,t)\Big),\qquad \tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t
Deep learning

denoising score matching

train s_θ(x̃) to equal −(x̃ − x)/σ² = ∇log q(x̃|x)

The score is ∇ₓ log p(x); ε-prediction in DDPM is the same thing up to scale: s = −ε/σ.

Worked example: x = 0, xt = 0.5, s = 0.5 → -2 ✓ checked

See also: diffusion training loss · Langevin dynamics

LaTeX source
\mathcal L=\mathbb E\Big\|s_\theta(\tilde x,\sigma)+\frac{\tilde x-x}{\sigma^2}\Big\|^2,\qquad \tilde x=x+\sigma\varepsilon
Deep learning

depthwise-separable convolution parameters

k²Cᵢₙ + CᵢₙC_out  vs  k²CᵢₙC_out

About an 8–9× reduction for 3×3 kernels (MobileNet).

Worked example: k = 3, ci = 64, co = 128 → [8768, 73728] ✓ checked

See also: parameter counts · convolution cost

LaTeX source
\underbrace{k^2C_{in}+C_{in}C_{out}}_{\text{separable}}\ \text{vs}\ \underbrace{k^2C_{in}C_{out}}_{\text{standard}}
Deep learning

diffusion forward process

xₜ = √ᾱₜ x₀ + √(1−ᾱₜ) ε;  ᾱₜ = Πₛ αₛ

where ε ~ N(0, I)

Sample any noise level directly from x₀.

Worked example: alphas = [0.9, 0.8], x0 = 1, e = 1 → 1.37768 ✓ checked

See also: diffusion training loss

LaTeX source
x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\varepsilon,\quad \bar\alpha_t=\prod_{s\le t}\alpha_s
Deep learning

diffusion training loss

L = E‖ε − ε_θ(xₜ, t)‖²

The network predicts the noise that was added.

Worked example: e = [1, 0], ep = [0.5, 0] → 0.25 ✓ checked

See also: diffusion forward process

LaTeX source
L=\mathbb{E}_{t,x_0,\varepsilon}\big[\|\varepsilon-\varepsilon_\theta(x_t,t)\|^2\big]
Deep learning

dilated convolution

k_eff = k + (k − 1)(d − 1)

where d = dilation

Grows the receptive field without adding parameters.

Worked example: k = 3, d = 4 → 9 ✓ checked

See also: receptive field recurrence

LaTeX source
k_{\text{eff}}=k+(k-1)(d-1)
Deep learning

direct preference optimisation (DPO)

L = −ln σ(β[log(π/π_ref)(y_w) − log(π/π_ref)(y_l)])

Optimises the RLHF objective in closed form, with no separate reward model or RL loop.

Worked example: b = 0.1, lw = -10, lw_ref = -12, ll = -15, ll_ref = -14 → 0.554355 ✓ checked

See also: Bradley–Terry reward-model loss · RLHF reward with KL penalty

LaTeX source
L=-\ln\sigma\Big(\beta\ln\frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)}-\beta\ln\frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\Big)
Deep learning

early-stopping rule

stop after `patience` epochs without a new best validation loss

Acts like an L2 penalty whose strength shrinks with training time.

Worked example: hist = [0.9, 0.8, 0.82, 0.81, 0.83], p = 3 → 1 ✓ checked

See also: L2 penalty (weight decay)

LaTeX source
\text{stop when }L_{\text{val}}\text{ has not improved for }p\text{ epochs (patience)}
Deep learning

ELU and SELU

ELU: x for x > 0, α(eˣ − 1) otherwise;  SELU scales it by λ

SELU self-normalises activations in fully connected networks.

Worked example: x = -1, a = 1 → -0.632121 ✓ checked

See also: ReLU and leaky ReLU · GELU

LaTeX source
\operatorname{ELU}(x)=\begin{cases}x&x>0\\ \alpha(e^x-1)&x\le0\end{cases},\qquad \operatorname{SELU}=\lambda\operatorname{ELU}\ (\lambda\approx1.0507,\ \alpha\approx1.6733)
Deep learning

EMA decay and half-life

β = 0.5^(1/half-life);  window ≈ 1/(1 − β)

Worked example: b = 0.99 → 100 ✓ checked

See also: exponential moving average

LaTeX source
\beta=0.5^{1/\text{half-life}},\qquad \text{effective window}\approx\frac1{1-\beta}
Deep learning

flow matching and rectified flow

x_t = (1 − t)x₀ + t x₁;  regress v_θ onto x₁ − x₀

where x₀ ~ noise, x₁ ~ data

Straight-line paths give simple training and few-step sampling.

Worked example: x0 = 0, x1 = 2, t = 0.25 → [0.5, 2] ✓ checked

See also: diffusion forward process

LaTeX source
x_t=(1-t)\,x_0+t\,x_1,\qquad \mathcal L=\mathbb E\big\|v_\theta(x_t,t)-(x_1-x_0)\big\|^2
Deep learning

GAN objective

min_G max_D E[log D(x)] + E[log(1 − D(G(z)))]

Worked example: dx = 0.8, dg = 0.3 → -0.579818 ✓ checked

See also: optimal GAN discriminator

LaTeX source
\min_G\max_D\ \mathbb{E}_{x\sim p_{\text{data}}}[\log D(x)]+\mathbb{E}_{z\sim p_z}[\log(1-D(G(z)))]
Deep learning

GELU tanh approximation

GELU ≈ ½x(1 + tanh(√(2/π)(x + 0.044715x³)))

The form used in the original BERT and GPT-2 code.

Worked example: x = 1 → 0.841192 ✓ checked

See also: GELU

LaTeX source
\operatorname{GELU}(x)\approx\tfrac12x\Big(1+\tanh\!\Big[\sqrt{\tfrac2\pi}\big(x+0.044715x^3\big)\Big]\Big)
Deep learning

graph attention (GAT)

learned attention weights over neighbours

Worked example: e = [0, 0] → [0.5, 0.5] ✓ checked

See also: scaled dot-product attention · graph convolution (GCN)

LaTeX source
e_{ij}=\operatorname{LeakyReLU}\big(\mathbf a^{\top}[W\mathbf h_i\,\|\,W\mathbf h_j]\big),\quad \alpha_{ij}=\operatorname{softmax}_j(e_{ij}),\quad \mathbf h_i'=\sigma\Big(\sum_j\alpha_{ij}W\mathbf h_j\Big)
Deep learning

graph convolution (GCN)

H′ = σ(D̃^(−½) Ã D̃^(−½) H W)

Each node averages its neighbours (and itself).

Worked example: A = [[0, 1], [1, 0]], H = [[1], [3]] → [[2], [2]] ✓ checked

See also: normalised graph Laplacian

LaTeX source
H^{(l+1)}=\sigma\big(\tilde D^{-1/2}\tilde A\tilde D^{-1/2}H^{(l)}W^{(l)}\big),\quad \tilde A=A+I
Deep learning

graph isomorphism network (GIN)

h′ = MLP((1 + ε)hᵥ + Σ hᵤ)

As expressive as the Weisfeiler–Lehman test.

Worked example: h = 1, nb = [2, 3], e = 0.1 → 6.1 ✓ checked

See also: graph convolution (GCN)

LaTeX source
\mathbf h_v'=\operatorname{MLP}\Big((1+\varepsilon)\mathbf h_v+\sum_{u\in N(v)}\mathbf h_u\Big)
Deep learning

group normalisation

normalise over each group of channels

Independent of batch size; instance norm is G = C, layer norm is G = 1.

Worked example: x = [1, 3, 5, 7], eps = 1e-12 → [-1.34164, -0.447214, 0.447214, 1.34164] ✓ checked

See also: layer normalisation · batch normalisation

LaTeX source
\hat x=\frac{x-\mu_g}{\sqrt{\sigma_g^2+\epsilon}},\quad \mu_g,\sigma_g\ \text{over the channels in a group and }H,W
Deep learning

GRU hidden update

hₜ = (1 − zₜ) ⊙ hₜ₋₁ + zₜ ⊙ h̃ₜ

where z = update gate

Worked example: z = 0.25, hp = 4, ht = 0 → 3 ✓ checked

See also: LSTM cell state update

LaTeX source
h_t=(1-z_t)\odot h_{t-1}+z_t\odot\tilde h_t
Deep learning

InfoNCE (contrastive) loss

L = −log( exp(s⁺/τ) / Σⱼ exp(sⱼ/τ) )

where s = similarity scores (positive first), τ = temperature

Lower bounds mutual information.

Worked example: s = [1, 0], tau = 1 → 0.313262 ✓ checked

See also: cosine similarity · mutual information

LaTeX source
L=-\log\frac{\exp(s^{+}/\tau)}{\sum_{j}\exp(s_j/\tau)}
Deep learning

inverted dropout

y = (m ⊙ x) / (1 − p)

where p = drop probability

Scaling by 1/(1−p) keeps the expected activation unchanged.

Worked example: m = [1, 0], x = [2, 2], p = 0.5 → [4, 0] ✓ checked

See also: L2 penalty (weight decay)

LaTeX source
\mathbf y=\frac{\mathbf m\odot\mathbf x}{1-p},\quad m_i\sim\mathrm{Bernoulli}(1-p)
Deep learning

KV-cache size

bytes = 2 · layers · kv_heads · d_head · T · bytes_per_value

Grouped-query attention shrinks it by n_heads/n_kv. It, not weights, often limits long-context serving.

Worked example: L = 32, nkv = 8, dh = 128, T = 8192, b = 2 → 1.07374e+09 ✓ checked

See also: self-attention cost

LaTeX source
\text{bytes}=2\cdot n_{\text{layers}}\cdot n_{kv}\cdot d_{\text{head}}\cdot T\cdot b
Deep learning

layer normalisation

x̂ᵢ = (xᵢ − μ)/√(σ² + ε);  yᵢ = γᵢx̂ᵢ + βᵢ

where μ, σ² over the features of one example

Independent of batch size; standard in transformers.

Worked example: x = [1, 2, 3], eps = 1e-05 → [-1.22474, 0, 1.22474] ✓ checked

See also: batch normalisation · RMSNorm

LaTeX source
\hat x_i=\frac{x_i-\mu}{\sqrt{\sigma^2+\epsilon}},\quad y_i=\gamma_i\hat x_i+\beta_i
Deep learning

layer-wise learning-rate decay

η_ℓ = η_top γ^(L − ℓ)

Lower layers (general features) change more slowly when fine-tuning.

Worked example: top = 0.0001, g = 0.9, L = 12, l = 6 → 5.31441e-05 ✓ checked

See also: exponential learning-rate decay

LaTeX source
\eta_\ell=\eta_{\text{top}}\,\gamma^{L-\ell}
Deep learning

least-squares and hinge GAN losses

squared and hinge variants of the discriminator loss

Worked example: dr = 0.8, df = 0.2 → [0.04, 1.4] ✓ checked

See also: GAN objective

LaTeX source
\text{LSGAN: }\tfrac12\mathbb E(D(x)-1)^2+\tfrac12\mathbb E\,D(G(z))^2;\qquad \text{hinge: }\mathbb E\max(0,1-D(x))+\mathbb E\max(0,1+D(G(z)))
Deep learning

linear (fully connected) layer

y = W x + b

where W ∈ ℝ^(out×in)

Worked example: W = [[1, 2], [3, 4]], x = [1, 1], b = [0, 1] → [3, 8] ✓ checked

See also: parameter counts

LaTeX source
\mathbf y=W\mathbf x+\mathbf b
Deep learning

linear attention

φ(q)ᵀ(Σ φ(k)vᵀ) / φ(q)ᵀ(Σ φ(k))

where φ = positive feature map, e.g. elu + 1

Associativity gives O(T) time and a recurrent form.

Worked example: phiq = [1, 2], phik = [[1, 0], [0, 1]], v = [[1], [3]] → 2.33333 ✓ checked

See also: scaled dot-product attention

LaTeX source
\operatorname{Attn}(Q,K,V)_i=\frac{\phi(q_i)^{\top}\sum_j\phi(k_j)v_j^{\top}}{\phi(q_i)^{\top}\sum_j\phi(k_j)}
Deep learning

Lipschitz bound of a network

Lip(f) ≤ Π ‖W_ℓ‖₂ · Π Lip(σ_ℓ)

ReLU has Lip 1. Loose, but it is the basis of spectral-norm and Lipschitz-constrained training.

Worked example: s = [2, 1.5, 0.5] → 1.5 ✓ checked

See also: spectral norm · Lipschitz continuity

LaTeX source
\operatorname{Lip}(f)\le\prod_{\ell}\|W_\ell\|_2\cdot\prod_\ell\operatorname{Lip}(\sigma_\ell)
Deep learning

low-rank adaptation (LoRA)

W′ = W + (α/r)·BA;  params = r(d + k)

A 4096×4096 layer at r = 8 trains 65 536 parameters instead of 16.8 million.

Worked example: d = 4096, k = 4096, r = 8 → [65536, 1.67772e+07] ✓ checked

See also: Eckart–Young theorem (low-rank approximation)

LaTeX source
W'=W+\frac\alpha r\,BA,\quad B\in\mathbb R^{d\times r},\ A\in\mathbb R^{r\times k},\quad \text{trainable params}=r(d+k)
Deep learning

LSTM cell state update

cₜ = fₜ ⊙ cₜ₋₁ + iₜ ⊙ c̃ₜ;  hₜ = oₜ ⊙ tanh(cₜ)

where f, i, o = forget, input, output gates

The additive update lets gradients flow over long spans.

Worked example: f = 0.5, i = 0.5, cp = 2, ct = 1 → 1.5 ✓ checked

See also: GRU hidden update · sigmoid (logistic function)

LaTeX source
c_t=f_t\odot c_{t-1}+i_t\odot\tilde c_t,\qquad h_t=o_t\odot\tanh(c_t)
Deep learning

LSTM gates

forget, input and output gates plus a candidate cell

Then cₜ = f ⊙ cₜ₋₁ + i ⊙ c̃ and hₜ = o ⊙ tanh(cₜ).

Worked example: z = 0 → [0.5, 0] ✓ checked

See also: LSTM cell state update

LaTeX source
f=\sigma(W_f[h,x]+b_f),\ i=\sigma(W_i[h,x]+b_i),\ o=\sigma(W_o[h,x]+b_o),\ \tilde c=\tanh(W_c[h,x]+b_c)
Deep learning

maximal-update parametrisation (μP)

hidden-layer learning rate ∝ 1/width

Hyper-parameters tuned on a small model transfer to a large one.

Worked example: lr0 = 0.01, w0 = 256, w1 = 4096 → 0.000625 ✓ checked

See also: He (Kaiming) initialisation

LaTeX source
\eta_{\text{hidden}}\propto\frac1{\text{width}},\qquad \text{output multiplier}\propto\frac1{\text{width}}
Deep learning

message passing framework

aggregate messages from neighbours, then update

Sum, mean and max are the usual permutation-invariant aggregators.

Worked example: nb = [1, 2, 3] → [6, 2, 3] ✓ checked

See also: graph convolution (GCN)

LaTeX source
m_v=\bigoplus_{u\in N(v)}\psi(h_u,h_v,e_{uv}),\qquad h_v'=\phi(h_v,m_v)
Deep learning

Mish and hard-swish

Mish = x tanh(softplus x);  h-swish = x·ReLU6(x + 3)/6

Worked example: x = 1 → [0.865098, 0.666667] ✓ checked

See also: Swish / SiLU · GELU

LaTeX source
\operatorname{Mish}(x)=x\tanh\big(\ln(1+e^x)\big),\qquad \text{hard-swish}(x)=x\frac{\operatorname{ReLU6}(x+3)}6
Deep learning

mixture-of-experts routing and load balance

top-k gate over experts;  balance loss α N Σ fᵢ Pᵢ

where f = fraction of tokens routed to expert i, P = mean router probability

Minimised when routing is uniform.

Worked example: f = [0.25, 0.25, 0.25, 0.25], P = [0.25, 0.25, 0.25, 0.25], al = 0.01, N = 4 → 0.01 ✓ checked

See also: softmax

LaTeX source
g=\operatorname{softmax}(W_rx),\quad y=\sum_{i\in\text{top-}k}g_i\,E_i(x),\qquad L_{\text{bal}}=\alpha N\sum_{i=1}^{N}f_iP_i
Deep learning

mixup

x̃ = λxᵢ + (1 − λ)xⱼ;  ỹ likewise

Worked example: lam = 0.7, xi = 1, xj = 3 → 1.6 ✓ checked

See also: label smoothing

LaTeX source
\tilde x=\lambda x_i+(1-\lambda)x_j,\quad \tilde y=\lambda y_i+(1-\lambda)y_j,\quad \lambda\sim\mathrm{Beta}(\alpha,\alpha)
Deep learning

model FLOPs utilisation

MFU = (6·N·tokens/sec) / peak FLOPs

40–60% is excellent for large-scale training.

Worked example: N = 7e+09, tps = 3000, peak = 3.12e+14 → 0.403846 ✓ checked

See also: training compute estimate

LaTeX source
\mathrm{MFU}=\frac{6ND/\Delta t}{P_{\text{peak}}\cdot n_{\text{GPU}}}
Deep learning

multi-head attention dimensions

d_k = d_model / h;  MHA = Concat(head₁…head_h) W^O

where h = number of heads

Worked example: d = 512, h = 8 → 64 ✓ checked

See also: scaled dot-product attention

LaTeX source
d_k=d_v=\frac{d_{\text{model}}}{h},\quad \operatorname{MHA}=\operatorname{Concat}(\text{head}_1,\dots,\text{head}_h)W^{O}
Deep learning

neural tangent kernel

Θ(x, x′) = ∇_θ f(x)·∇_θ f(x′)

In the infinite-width limit it stays constant, and training is kernel regression with Θ.

Worked example: g1 = [1, 2], g2 = [0.5, -1] → -1.5 ✓ checked

See also: Gram matrix · kernel ridge regression

LaTeX source
\Theta(x,x')=\nabla_\theta f(x;\theta)^{\top}\nabla_\theta f(x';\theta)
Deep learning

noise injection as regularisation

adding N(0, σ²) input noise ≡ an L2 penalty σ²‖w‖²

Bishop (1995): Tikhonov regularisation is equivalent to training with noise.

Worked example: w = [1, 2], s2 = 0.1 → 0.5 ✓ checked

See also: L2 penalty (weight decay) · ridge regression (closed form)

LaTeX source
\mathbb E\big[(\mathbf w^{\top}(\mathbf x+\boldsymbol\varepsilon)-y)^2\big]=(\mathbf w^{\top}\mathbf x-y)^2+\sigma^2\|\mathbf w\|^2
Deep learning

normalising flow change of variables

log p(x) = log p(z) + log|det ∂z/∂x|

where z = f(x)

Layers are chosen so the Jacobian determinant is cheap (triangular, coupling).

Worked example: x = 1, a = 2 → -2.22579 ✓ checked

See also: change of variables (Jacobian)

LaTeX source
\log p_X(x)=\log p_Z\big(f(x)\big)+\log\Big|\det\frac{\partial f}{\partial x}\Big|
Deep learning

online softmax (FlashAttention rescaling)

merge two blocks' running max, normaliser and output

Lets attention be computed block by block without materialising the T×T matrix.

Worked example: x1 = [1, 2], x2 = [3, 0.5] → 3.46077 ✓ checked

See also: scaled dot-product attention · stable softmax and log-sum-exp

LaTeX source
m'=\max(m,\tilde m),\quad \ell'=e^{m-m'}\ell+e^{\tilde m-m'}\tilde\ell,\quad O'=\frac{e^{m-m'}\ell\,O+e^{\tilde m-m'}\tilde\ell\,\tilde O}{\ell'}
Deep learning

optimal GAN discriminator

D*(x) = p_data(x) / (p_data(x) + p_g(x))

At the optimum p_g = p_data, D* = ½.

Worked example: pd = 0.6, pg = 0.2 → 0.75 ✓ checked

See also: GAN objective

LaTeX source
D^{*}(x)=\frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)}
Deep learning

PAC-Bayes bound

E_Q R ≤ E_Q R̂ + √((KL(Q‖P) + ln(2√n/δ))/(2n))

Non-vacuous bounds for neural networks have been obtained this way.

Worked example: kl = 50, n = 10000, d = 0.05 → 0.053988 ✓ checked

See also: Kullback–Leibler divergence · generalisation bound for a finite class

LaTeX source
\mathbb E_{h\sim Q}R(h)\le\mathbb E_{h\sim Q}\hat R(h)+\sqrt{\frac{D_{\mathrm{KL}}(Q\|P)+\ln\frac{2\sqrt n}\delta}{2n}}
Deep learning

parameter counts

dense: (in+1)·out     conv: (kₕk_w·c_in + 1)·c_out

Bias counted once per output.

Worked example: i = 784, o = 10, kh = 3, kw = 3, ci = 64, co = 128 → [7850, 73856] ✓ checked

See also: linear (fully connected) layer · convolution output size

LaTeX source
\text{dense: }(n_{in}+1)\,n_{out}\qquad \text{conv: }(k_hk_wc_{in}+1)\,c_{out}
Deep learning

parameters of a multilayer perceptron

Σ (n_{ℓ−1} + 1) n_ℓ

A 784-128-10 network has 101 770 parameters.

Worked example: n = [784, 128, 10] → 101770 ✓ checked

See also: parameter counts

LaTeX source
\sum_{\ell}(n_{\ell-1}+1)\,n_\ell,\qquad \text{forward FLOPs}\approx2\times\text{parameters}
Deep learning

parametric scaling law

L(N,D) = E + A/N^α + B/D^β

where N parameters, D training tokens; E, A, B, α, β fitted constants

The Chinchilla form; constants depend on the data and architecture.

Worked example: E = 1.7, A = 400, B = 400, a = 0.3, b = 0.3, N = 1e+09, D = 1e+10 → 2.8981 ✓ checked

See also: training compute estimate

LaTeX source
L(N,D)=E+\frac{A}{N^{\alpha}}+\frac{B}{D^{\beta}}
Deep learning

pooling output size

n_out = ⌊(n − k)/s⌋ + 1

Worked example: n = 32, k = 2, s = 2 → 16 ✓ checked

See also: convolution output size

LaTeX source
n_{out}=\Big\lfloor\frac{n-k}{s}\Big\rfloor+1,\qquad \text{global average pool: }\frac1{HW}\sum_{h,w}x_{hw}
Deep learning

power-law loss scaling

loss falls as a power law in parameters, data and compute

Doubling N multiplies the reducible loss by 2^(−α).

Worked example: a = 0.076 → 0.948684 ✓ checked

See also: parametric scaling law

LaTeX source
L(N)=\Big(\frac{N_c}{N}\Big)^{\alpha_N},\quad L(D)=\Big(\frac{D_c}{D}\Big)^{\alpha_D},\quad L(C)=\Big(\frac{C_c}{C}\Big)^{\alpha_C}
Deep learning

PReLU and leaky ReLU gradient

f = max(0, x) + a·min(0, x);  ∂f/∂a = min(0, x)

where a learned

Worked example: x = -2, a = 0.25 → [-0.5, -2] ✓ checked

See also: ReLU and leaky ReLU

LaTeX source
f(x)=\max(0,x)+a\min(0,x),\qquad \frac{\partial f}{\partial a}=\min(0,x)
Deep learning

Rademacher generalisation bound

R ≤ R̂ + 2ℜₙ(H) + √(ln(1/δ)/(2n))

where ℜₙ = Rademacher complexity

Data-dependent; for linear classes ℜ ≤ BR/√n.

Worked example: rad = 0.02, dl = 0.05, n = 10000 → 0.0522387 ✓ checked

See also: VC generalisation bound

LaTeX source
R(h)\le\hat R(h)+2\mathfrak R_n(\mathcal H)+\sqrt{\frac{\ln(1/\delta)}{2n}}
Deep learning

reparameterisation trick

z = μ + σ ⊙ ε,  ε ~ N(0, I)

Moves the randomness out of the graph so gradients flow through μ and σ.

Worked example: mu = 1, s = 2, e = 0.5 → 2 ✓ checked

See also: evidence lower bound (VAE)

LaTeX source
z=\mu+\sigma\odot\varepsilon,\quad \varepsilon\sim\mathcal N(0,I)
Deep learning

repetition penalty

divide positive logits (multiply negative ones) by θ > 1

Worked example: z = 2, th = 1.2 → 1.66667 ✓ checked

See also: top-k, top-p and temperature sampling

LaTeX source
z_i\leftarrow\begin{cases}z_i/\theta&z_i>0\\ z_i\theta&z_i<0\end{cases}\quad(\text{for tokens already generated})
Deep learning

residual-branch scaling

scale residual outputs by 1/√(2L)

where L = number of residual blocks

Keeps the variance of the residual stream from growing with depth (GPT-2).

Worked example: L = 48 → 0.102062 ✓ checked

See also: He (Kaiming) initialisation

LaTeX source
\text{scale the last layer of each residual branch by }\frac1{\sqrt{2L}}
Deep learning

RMSNorm

yᵢ = xᵢ / √(mean(x²) + ε) · gᵢ

where g = learned gain

LayerNorm without the mean subtraction; used in modern LLMs.

Worked example: x = [3, 4], eps = 1e-12 → [0.848528, 1.13137] ✓ checked

See also: layer normalisation

LaTeX source
y_i=\frac{x_i}{\sqrt{\tfrac1d\sum_j x_j^2+\epsilon}}\,g_i
Deep learning

rotary position embedding (RoPE)

rotate each coordinate pair by m·θᵢ

where m = position

Relative position enters the attention score through the rotation difference.

Worked example: m = 1, th = 1.5708, x = [1, 0] → [6.12323e-17, 1] ✓ checked

See also: sinusoidal positional encoding · 2-D rotation matrix

LaTeX source
\begin{pmatrix}x_{2i}'\\ x_{2i+1}'\end{pmatrix}=\begin{pmatrix}\cos m\theta_i&-\sin m\theta_i\\ \sin m\theta_i&\cos m\theta_i\end{pmatrix}\begin{pmatrix}x_{2i}\\ x_{2i+1}\end{pmatrix},\quad \theta_i=10000^{-2i/d}
Deep learning

scaled dot-product attention

Attn(Q,K,V) = softmax( QKᵀ/√d_k ) V

where d_k = key dimension

The 1/√d_k keeps dot products from saturating the softmax.

Worked example: Q = [[1, 0]], K = [[1, 0], [0, 1]], V = [[1, 2], [3, 4]] → [[1.66048, 2.66048]] ✓ checked

See also: multi-head attention dimensions · sinusoidal positional encoding · softmax

LaTeX source
\operatorname{Attn}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V
Deep learning

self-attention cost

FLOPs ≈ 4T²d per layer;  attention matrix memory O(T²)

where T = sequence length, d = model width

FlashAttention keeps the maths but tiles it so memory is O(T).

Worked example: T = 2048, d = 4096 → 6.87195e+10 ✓ checked

See also: online softmax (FlashAttention rescaling)

LaTeX source
\text{FLOPs}\approx4T^2d\ \ (QK^{\top}\text{ and }AV),\qquad \text{memory}=O(T^2)
Deep learning

sinusoidal positional encoding

PE(pos,2i) = sin(pos/10000^(2i/d));  PE(pos,2i+1) = cos(…)

Worked example: pos = 1, i = 0, d = 4 → [0.841471, 0.540302] ✓ checked

See also: scaled dot-product attention

LaTeX source
PE_{(pos,2i)}=\sin\!\frac{pos}{10000^{2i/d}},\quad PE_{(pos,2i+1)}=\cos\!\frac{pos}{10000^{2i/d}}
Deep learning

softmax Jacobian

J = diag(p) − ppᵀ

Symmetric, rank n − 1, rows sum to zero.

Worked example: z = [0, 0] → [[0.25, -0.25], [-0.25, 0.25]] ✓ checked

See also: gradient of softmax cross-entropy

LaTeX source
\frac{\partial p_i}{\partial z_j}=p_i(\delta_{ij}-p_j),\qquad J=\operatorname{diag}(p)-pp^{\top}
Deep learning

speculative decoding acceptance

accept with probability min(1, p/q)

where q = draft model, p = target model

Output distribution is exactly the target's; speed-up comes from verifying several drafted tokens in one pass.

Worked example: p = 0.2, q = 0.5 → 0.4 ✓ checked

See also: importance sampling

LaTeX source
P(\text{accept token }x)=\min\Big(1,\frac{p(x)}{q(x)}\Big),\qquad \text{on rejection resample from }\operatorname{norm}\big((p-q)_+\big)
Deep learning

stochastic depth survival probabilities

p_ℓ = 1 − (ℓ/L)(1 − p_L)

where layer ℓ survives with probability p_ℓ

Worked example: l = 10, L = 20, pL = 0.5 → 0.75 ✓ checked

See also: inverted dropout

LaTeX source
p_\ell=1-\frac\ell L(1-p_L)
Deep learning

SwiGLU feed-forward block

FFN(x) = (SiLU(xW₁) ⊙ xW₃)W₂

Gated FFN used in LLaMA-style models; d_ff ≈ (8/3)d keeps parameters equal to a 4d ReLU FFN.

Worked example: d = 4096 → [1.3421e+08, 1.34218e+08] ✓ checked

See also: gated linear unit · Swish / SiLU

LaTeX source
\operatorname{FFN}(x)=\big(\operatorname{SiLU}(xW_1)\odot xW_3\big)W_2,\qquad \text{params}=3\,d\,d_{ff}
Deep learning

training compute estimate

C ≈ 6 N D

where N = parameters, D = training tokens; FLOPs

About 2ND forward + 4ND backward.

Worked example: N = 1e+09, D = 2e+10 → 1.2e+20 ✓ checked

See also: parametric scaling law

LaTeX source
C\approx 6\,N\,D
Deep learning

training memory per parameter (mixed-precision Adam)

≈ 16 bytes per parameter, before activations

ZeRO shards these across devices.

Worked example: N = 7e+09 → 112 ✓ checked

See also: transformer parameter count

LaTeX source
\underbrace{2}_{\text{bf16 weights}}+\underbrace{2}_{\text{grads}}+\underbrace{4}_{\text{fp32 master}}+\underbrace{4+4}_{\text{Adam }m,v}=16\ \text{bytes/parameter}
Deep learning

transformer parameter count

N ≈ 12·L·d² + V·d

where L layers, width d, vocabulary V

A quick estimate; GPT-3 (L = 96, d = 12288) gives about 175B.

Worked example: L = 96, d = 12288 → 1.73946e+11 ✓ checked

See also: parametric scaling law · training compute estimate

LaTeX source
N\approx12\,L\,d^2+V\,d,\qquad \text{(attention }4d^2+\text{FFN }8d^2\text{ per layer)}
Deep learning

transposed convolution output size

n_out = (n − 1)s − 2p + k + output_padding

The inverse of the convolution size formula; used in decoders and GANs.

Worked example: n = 16, s = 2, p = 1, k = 4, po = 0 → 32 ✓ checked

See also: convolution output size

LaTeX source
n_{out}=(n-1)s-2p+k+p_{out}
Deep learning

vanilla RNN cell

hₜ = tanh(W_h hₜ₋₁ + W_x xₜ + b)

Worked example: Wh = 0.5, Wx = 1, h = 1, x = 0.5, b = 0 → 0.761594 ✓ checked

See also: LSTM cell state update · GRU hidden update

LaTeX source
h_t=\tanh(W_hh_{t-1}+W_xx_t+b)
Deep learning

vanishing and exploding gradients (BPTT)

‖∂h_T/∂h_t‖ ≤ (‖W‖γ)^(T − t)

where γ = bound on the activation derivative

Below 1 the gradient vanishes, above 1 it explodes: the motivation for LSTMs, gradient clipping and orthogonal initialisation.

Worked example: w = 0.9, g = 1, n = 50 → 0.00515378 ✓ checked

See also: LSTM cell state update · gradient norm clipping

LaTeX source
\Big\|\frac{\partial h_T}{\partial h_t}\Big\|\le\big(\|W\|\,\gamma\big)^{T-t}
Deep learning

VQ-VAE loss

reconstruction + codebook loss + commitment loss

where sg = stop-gradient

Worked example: rec = 0.5, ze = 1, e = 0.6, b = 0.25 → 0.7 ✓ checked

See also: evidence lower bound (VAE)

LaTeX source
\mathcal L=\|x-\hat x\|^2+\|\operatorname{sg}[z_e]-e\|^2+\beta\|z_e-\operatorname{sg}[e]\|^2
Deep learning

Wasserstein GAN loss and gradient penalty

critic loss + λ(‖∇D(x̂)‖ − 1)²

The critic estimates the Wasserstein-1 distance; the penalty enforces 1-Lipschitzness.

Worked example: dfake = 0.5, dreal = 1.5, gn = 1.2, lam = 10 → -0.6 ✓ checked

See also: Wasserstein-1 distance (1-D) · GAN objective

LaTeX source
L_D=\mathbb E[D(\tilde x)]-\mathbb E[D(x)]+\lambda\,\mathbb E\big[(\|\nabla_{\hat x}D(\hat x)\|_2-1)^2\big]
Deep learning

weight and spectral normalisation

w = g v/‖v‖;  W̄ = W/σ_max(W)

Spectral norm makes a layer 1-Lipschitz, which stabilises GAN discriminators.

Worked example: W = [[3, 0], [0, 1]] → 1 ✓ checked

See also: spectral norm · Lipschitz continuity

LaTeX source
\mathbf w=g\frac{\mathbf v}{\|\mathbf v\|},\qquad \bar W=\frac{W}{\sigma(W)}
Deep learning

Xavier (Glorot) initialisation

std = √(2 / (fan_in + fan_out))

For tanh/sigmoid networks.

Worked example: fi = 100, fo = 100 → 0.1 ✓ checked

See also: He (Kaiming) initialisation

LaTeX source
w\sim\mathcal N\!\left(0,\tfrac{2}{n_{in}+n_{out}}\right)
Deep learning

β-VAE objective

L = E[log p(x|z)] − β·KL

where β > 1 encourages disentanglement

Worked example: rec = -10, kl = 2, b = 4 → -18 ✓ checked

See also: evidence lower bound (VAE)

LaTeX source
\mathcal L=\mathbb E_q[\log p(x\mid z)]-\beta\,D_{\mathrm{KL}}\big(q(z\mid x)\,\|\,p(z)\big)
Reinforcement learning

actor–critic

the TD error trains the critic and weights the actor's gradient

Worked example: r = 1, g = 0.9, vn = 2, v = 1.5 → 1.3 ✓ checked

See also: temporal-difference error · REINFORCE with a baseline

LaTeX source
\delta=r+\gamma V(s')-V(s),\qquad \theta\leftarrow\theta+\alpha_\pi\,\delta\,\nabla\ln\pi_\theta(a\mid s),\qquad w\leftarrow w+\alpha_V\,\delta\,\nabla V_w(s)
Reinforcement learning

advantage function

A = Q − V;  E_π[A] = 0

Worked example: q = 3, v = 2.5 → 0.5 ✓ checked

See also: generalised advantage estimation

LaTeX source
A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s),\qquad \mathbb E_{a\sim\pi}A^\pi(s,a)=0
Reinforcement learning

Bellman optimality equation

Q*(s,a) = r + γ Σ P(s′|s,a) max_a′ Q*(s′,a′)

Worked example: r = 1, g = 0.9, qn = 5 → 5.5 ✓ checked

See also: Q-learning update

LaTeX source
Q^{*}(s,a)=r+\gamma\sum_{s'}P(s'\mid s,a)\max_{a'}Q^{*}(s',a')
Reinforcement learning

DDPG target and Polyak averaging

y = r + γQ′(s′, μ′(s′));  target ← τ·online + (1 − τ)·target

where τ ≈ 0.005

Worked example: r = 1, g = 0.99, qn = 2, tau = 0.005, phi = 1, phip = 0 → [2.98, 0.005] ✓ checked

See also: exponential moving average · TD3 clipped double-Q target

LaTeX source
y=r+\gamma Q_{\phi'}\big(s',\mu_{\theta'}(s')\big),\qquad \phi'\leftarrow\tau\phi+(1-\tau)\phi'
Reinforcement learning

discounted return

Gₜ = Σₖ γᵏ rₜ₊ₖ

where γ ∈ [0,1) = discount factor

Worked example: r = [1, 1, 1], g = 0.5 → 1.75 ✓ checked

See also: Bellman expectation equation

LaTeX source
G_t=\sum_{k=0}^{\infty}\gamma^{k}r_{t+k}
Reinforcement learning

distributional RL projection (C51)

b = (r + γz − V_min)/Δz;  split mass between the neighbouring atoms

Worked example: r = 1, g = 0.9, z = 2, vmin = -10, dz = 1 → [12, 13, 0.8] ✓ checked

See also: DQN loss

LaTeX source
b=\frac{\mathcal T z_j-V_{\min}}{\Delta z},\quad \mathcal Tz_j=r+\gamma z_j\ (\text{clipped}),\quad \text{split mass between atoms }\lfloor b\rfloor,\lceil b\rceil
Reinforcement learning

double Q-learning

choose the action with one table, evaluate it with the other

Removes the maximisation bias of Q-learning.

Worked example: qa = 2, qb_at_argmax = 3, a = 0.5, r = 1, g = 0.9 → 2.85 ✓ checked

See also: Q-learning update

LaTeX source
Q_A(s,a)\leftarrow Q_A+\alpha\big[r+\gamma Q_B\big(s',\arg\max_{a'}Q_A(s',a')\big)-Q_A\big]
Reinforcement learning

DQN loss

L = (r + γ max Q_target(s′, a′) − Q(s, a))²

where θ⁻ = periodically updated target network

Worked example: r = 1, g = 0.99, qt = 5, q = 4 → 3.8025 ✓ checked

See also: Q-learning update · temporal-difference error

LaTeX source
L=\mathbb E\Big[\Big(r+\gamma\max_{a'}Q_{\theta^-}(s',a')-Q_\theta(s,a)\Big)^2\Big]
Reinforcement learning

effective horizon

H_eff = 1/(1 − γ)

γ = 0.99 looks about 100 steps ahead.

Worked example: g = 0.99 → 100 ✓ checked

See also: discounted return

LaTeX source
H_{\text{eff}}=\frac1{1-\gamma}
Reinforcement learning

gradient bandit update

preferences follow the policy-gradient rule

Worked example: H = [0, 0], a = 0, R = 1, Rb = 0, al = 0.1 → [0.05, -0.05] ✓ checked

See also: policy gradient (softmax policy)

LaTeX source
H_a\leftarrow H_a+\alpha(R-\bar R)(1-\pi_a),\quad H_b\leftarrow H_b-\alpha(R-\bar R)\pi_b\ (b\ne a)
Reinforcement learning

Lai–Robbins lower bound

no consistent algorithm beats this logarithmic regret

Worked example: mu = 0.5, ms = 0.7 → 2.29419 ✓ checked

See also: UCB1

LaTeX source
\liminf_{T\to\infty}\frac{\mathbb E[\mathrm{Regret}_T]}{\ln T}\ge\sum_{i:\mu_i<\mu^*}\frac{\mu^*-\mu_i}{D_{\mathrm{KL}}(\mu_i\|\mu^*)}
Reinforcement learning

maximum-entropy inverse RL

trajectory probability ∝ exp(reward); gradient = expert features − expected features

Worked example: th = [1, 0], f = [[1, 0], [0, 1]] → [0.731059, 0.268941] ✓ checked

See also: optimal entropy-regularised policy

LaTeX source
P(\tau\mid\theta)=\frac{\exp\big(\boldsymbol\theta^{\top}\mathbf f(\tau)\big)}{Z(\theta)},\qquad \nabla_\theta\mathcal L=\tilde{\mathbf f}-\mathbb E_\theta[\mathbf f]
Reinforcement learning

mixed Nash equilibrium (2×2 zero-sum)

p* = (d − c)/(a − b − c + d);  value = (ad − bc)/(a − b − c + d)

Matching pennies: p* = ½, value 0.

Worked example: a = 1, b = -1, c = -1, d = 1 → [0.5, 0] ✓ checked

See also: Shapley value

LaTeX source
p^*=\frac{d-c}{a-b-c+d},\qquad v=\frac{ad-bc}{a-b-c+d}\quad\text{for payoffs }\begin{pmatrix}a&b\\c&d\end{pmatrix}
Reinforcement learning

n-step return

Gₜ⁽ⁿ⁾ = Σ γᵏ rₜ₊ₖ₊₁ + γⁿ V(sₜ₊ₙ)

n = 1 is TD(0), n = ∞ is Monte Carlo.

Worked example: r = [1, 1, 1], g = 0.9, v = 5 → 6.355 ✓ checked

See also: λ-return and eligibility traces · temporal-difference error

LaTeX source
G_t^{(n)}=\sum_{k=0}^{n-1}\gamma^kr_{t+k+1}+\gamma^nV(s_{t+n})
Reinforcement learning

off-policy correction (importance ratios)

ρ = π/b; Retrace truncates the ratio at 1

Worked example: pi = 0.6, b = 0.3, lam = 1 → [2, 1] ✓ checked

See also: importance sampling

LaTeX source
\rho_t=\frac{\pi(a_t|s_t)}{b(a_t|s_t)},\qquad \text{Retrace: }c_s=\lambda\min\big(1,\tfrac{\pi}{\mu}\big)
Reinforcement learning

optimal entropy-regularised policy

π* ∝ π_ref exp(Q*/β)

The softmax policy; also the closed-form solution of KL-regularised RL (RLHF).

Worked example: q = [1, 2], b = 1 → [0.268941, 0.731059] ✓ checked

See also: soft actor–critic · RLHF reward with KL penalty

LaTeX source
\pi^*(a\mid s)\propto\pi_{\text{ref}}(a\mid s)\,\exp\big(Q^*(s,a)/\beta\big)
Reinforcement learning

policy evaluation as a linear system

V^π = (I − γP_π)⁻¹ r_π

Exact for small MDPs; iterative methods scale to large ones.

Worked example: P = [[0.9, 0.1], [0.2, 0.8]], r = [1, 0], g = 0.9 → [7.56757, 4.86486] ✓ checked

See also: Bellman expectation equation · value iteration

LaTeX source
V^{\pi}=(I-\gamma P_\pi)^{-1}\mathbf r_\pi
Reinforcement learning

policy gradient (softmax policy)

∇J = E[ ∇ log π(a|s) · Â ];  ∇_z log π(a) = eₐ − π

REINFORCE. For a softmax policy the gradient on the logits is the one-hot action minus the policy.

Worked example: pi = [0.5, 0.5], a = 0 → [0.5, -0.5] ✓ checked

See also: PPO clipped objective · generalised advantage estimation

LaTeX source
\nabla_\theta J=\mathbb{E}\big[\nabla_\theta\log\pi_\theta(a\mid s)\,\hat A\big];\quad \nabla_z\log\pi(a)=\mathbf e_a-\pi
Reinforcement learning

policy improvement

act greedily with respect to Q^π

Alternating evaluation and improvement converges to the optimal policy.

Worked example: q = [1, 3, 2] → 1 ✓ checked

See also: value iteration

LaTeX source
\pi'(s)=\arg\max_aQ^{\pi}(s,a)\ \Rightarrow\ V^{\pi'}\ge V^{\pi}
Reinforcement learning

potential-based reward shaping

F = γΦ(s′) − Φ(s)

Ng, Harada and Russell (1999): adding F leaves the optimal policy unchanged.

Worked example: g = 0.9, ps = 1, p2 = 3 → 1.7 ✓ checked

See also: Bellman optimality equation

LaTeX source
F(s,s')=\gamma\Phi(s')-\Phi(s)
Reinforcement learning

PPO clipped objective

L = E[ min( r·Â, clip(r, 1−ε, 1+ε)·Â ) ]

where r = probability ratio, ε ≈ 0.2

Stops the policy moving too far in one update.

Worked example: r = 1.5, A = 2, e = 0.2 → 2.4 ✓ checked

See also: policy gradient (softmax policy) · generalised advantage estimation

LaTeX source
L^{\text{CLIP}}=\mathbb{E}\big[\min\big(r_t\hat A_t,\ \operatorname{clip}(r_t,1-\epsilon,1+\epsilon)\hat A_t\big)\big],\ r_t=\frac{\pi_\theta(a|s)}{\pi_{\text{old}}(a|s)}
Reinforcement learning

Q-learning update

Q(s,a) ← Q + α [ r + γ max Q(s′,·) − Q ]

where α = learning rate

Off-policy temporal-difference control.

Worked example: q = 2, a = 0.5, r = 1, g = 0.9, qn = 5 → 3.75 ✓ checked

See also: temporal-difference error · Bellman optimality equation

LaTeX source
Q(s,a)\leftarrow Q(s,a)+\alpha\big[r+\gamma\max_{a'}Q(s',a')-Q(s,a)\big]
Reinforcement learning

REINFORCE with a baseline

∇J = E[∇ln π · (G − b)]

Any baseline that does not depend on the action leaves the gradient unbiased and can cut the variance.

Worked example: G = 10, b = 8, dlogpi = 0.5 → 1 ✓ checked

See also: policy gradient (softmax policy) · actor–critic

LaTeX source
\nabla_\theta J=\mathbb E\big[\nabla_\theta\ln\pi_\theta(a\mid s)\,(G-b(s))\big]
Reinforcement learning

SARSA update

Q ← Q + α(r + γQ(s′, a′) − Q)

where a′ = the action actually taken next

On-policy; Q-learning replaces Q(s′, a′) by max.

Worked example: q = 2, a = 0.5, r = 1, g = 0.9, qn = 4 → 3.3 ✓ checked

See also: Q-learning update

LaTeX source
Q(s,a)\leftarrow Q(s,a)+\alpha\big[r+\gamma Q(s',a')-Q(s,a)\big]
Reinforcement learning

soft actor–critic

maximum-entropy objective;  soft value = α log Σ exp(Q/α)

As α → 0 the soft value tends to max Q.

Worked example: q = [1, 2], al = 0.5 → 2.06346 ✓ checked

See also: log-sum-exp · optimal entropy-regularised policy

LaTeX source
J=\mathbb E\sum_t\big[r_t+\alpha\,\mathcal H(\pi(\cdot|s_t))\big],\qquad V(s)=\alpha\ln\sum_a\exp\big(Q(s,a)/\alpha\big)
Reinforcement learning

successor representation

M = (I − γT)⁻¹;  V = M r

where T = state-transition matrix under the policy

Separates the environment's dynamics from the reward.

Worked example: T = [[0.5, 0.5], [0, 1]], g = 0.9 → [[1.81818, 8.18182], [0, 10]] ✓ checked

See also: policy evaluation as a linear system

LaTeX source
M=(I-\gamma T)^{-1},\qquad V=M\mathbf r
Reinforcement learning

TD3 clipped double-Q target

y = r + γ min(Q₁′, Q₂′)(s′, μ′(s′) + clipped noise)

The minimum of two critics counters overestimation.

Worked example: r = 1, g = 0.99, q1 = 2, q2 = 1.6 → 2.584 ✓ checked

See also: DDPG target and Polyak averaging · double Q-learning

LaTeX source
y=r+\gamma\min\big(Q_1',Q_2'\big)\big(s',\mu'(s')+\operatorname{clip}(\varepsilon,-c,c)\big)
Reinforcement learning

Thompson sampling (Bernoulli)

sample each arm's success rate from its posterior; play the best sample

Matches the Lai–Robbins lower bound in practice.

Worked example: al = 1, be = 1, s = 7, f = 3 → 0.666667 ✓ checked

See also: UCB1 · Beta–binomial conjugate update

LaTeX source
\theta_i\sim\mathrm{Beta}(\alpha_i+s_i,\ \beta_i+f_i),\quad a_t=\arg\max_i\theta_i
Reinforcement learning

TRPO surrogate and trust region

maximise the importance-weighted advantage within a KL ball

PPO replaces the constraint with clipping.

Worked example: ratio = 1.2, A = 2 → 2.4 ✓ checked

See also: PPO clipped objective · Kullback–Leibler divergence

LaTeX source
\max_\theta\ \mathbb E\Big[\frac{\pi_\theta(a|s)}{\pi_{\text{old}}(a|s)}\hat A\Big]\quad\text{s.t.}\quad\mathbb E\big[D_{\mathrm{KL}}(\pi_{\text{old}}\|\pi_\theta)\big]\le\delta
Reinforcement learning

UCB1

choose argmax x̄ᵢ + c√(ln t/nᵢ)

where c = √2 in the classic analysis

Optimism in the face of uncertainty: regret O(√(KT ln T)).

Worked example: xbar = 0.5, t = 100, n = 10, c = 1.41421 → 1.45971 ✓ checked

See also: Thompson sampling (Bernoulli) · regret of online gradient descent

LaTeX source
a_t=\arg\max_i\Big(\bar x_i+c\sqrt{\frac{\ln t}{n_i}}\Big)
Reinforcement learning

UCT and PUCT (MCTS)

select argmax Q̄ + exploration bonus

where N = parent visits, n = child visits, P = prior

PUCT (AlphaZero) uses a policy-network prior.

Worked example: Q = 0.5, N = 100, n = 10, c = 1.4, P = 0.3 → [1.45006, 0.881818] ✓ checked

See also: UCB1

LaTeX source
\mathrm{UCT}=\bar Q+c\sqrt{\frac{\ln N}{n}},\qquad \mathrm{PUCT}=\bar Q+c\,P(a)\frac{\sqrt N}{1+n}
Reinforcement learning

value iteration

V ← max_a Σ P (r + γV)

A γ-contraction: error shrinks by γ per sweep.

Worked example: r = [1, 2], v = 3, g = 0.9 → 4.7 ✓ checked

See also: Bellman optimality equation · policy improvement

LaTeX source
V_{k+1}(s)=\max_a\sum_{s'}P(s'\mid s,a)\big[r(s,a,s')+\gamma V_k(s')\big]
Reinforcement learning

λ-return and eligibility traces

G^λ = (1 − λ) Σ λⁿ⁻¹ G⁽ⁿ⁾;  trace e ← γλe + ∇V

Interpolates between TD(0) (λ = 0) and Monte Carlo (λ = 1).

Worked example: lam = 0.5, g = [1, 2, 3] → 1.75 ✓ checked

See also: n-step return · generalised advantage estimation

LaTeX source
G_t^\lambda=(1-\lambda)\sum_{n=1}^{\infty}\lambda^{n-1}G_t^{(n)},\qquad e\leftarrow\gamma\lambda e+\nabla V,\ \ \theta\leftarrow\theta+\alpha\,\delta\,e
General maths

AM–GM inequality

(a + b)/2 ≥ √(ab)

Equality iff a = b.

Worked example: a = 1, b = 4 → 0.5 ✓ checked

See also: Jensen's inequality

LaTeX source
\frac{a+b}{2}\ \ge\ \sqrt{ab}\quad(a,b\ge0)
General maths

change of base for logarithms

log_b x = ln x / ln b

Bits vs nats: log₂ x = ln x / ln 2.

Worked example: x = 8, b = 2 → 3 ✓ checked

See also: Shannon entropy

LaTeX source
\log_b x=\frac{\ln x}{\ln b}
General maths

Gaussian integral

∫ e^(−x²) dx = √π

Gives the normalising constant of the normal density.

Worked example → 1.77245 ✓ checked

See also: normal (Gaussian) density

LaTeX source
\int_{-\infty}^{\infty}e^{-x^2}\,dx=\sqrt\pi
General maths

geometric series

Σ a rᵏ = a(1 − rⁿ)/(1 − r);  to ∞: a/(1 − r)

Worked example: a = 1, r = 0.5, n = 3 → 1.75 ✓ checked

See also: discounted return

LaTeX source
\sum_{k=0}^{n-1}ar^{k}=a\,\frac{1-r^{n}}{1-r},\qquad \sum_{k=0}^{\infty}ar^k=\frac{a}{1-r}\ (|r|<1)
General maths

Lipschitz continuity

‖f(x) − f(y)‖ ≤ L ‖x − y‖

where L = Lipschitz constant

Bounds how fast the output can change; the basis of stability and robustness analysis.

Worked example: x = 1, y = 3 → 2 ✓ checked

See also: spectral norm

LaTeX source
\|f(x)-f(y)\|\le L\,\|x-y\|
General maths

quadratic formula

x = (−b ± √(b² − 4ac)) / 2a

where ax² + bx + c = 0

Real roots iff b² − 4ac ≥ 0.

Worked example: a = 1, b = -3, c = 2 → [1, 2] ✓ checked

LaTeX source
x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}
General maths

Stirling's approximation

n! ≈ √(2πn) (n/e)ⁿ

Relative error about 1/(12n).

Worked example: n = 10 → 3.5987e+06 ✓ checked

See also: combinations and permutations

LaTeX source
n!\approx\sqrt{2\pi n}\left(\frac ne\right)^{n}

Is a formula missing?

Tell us what you need and we will add it, with LaTeX, symbols and a worked example. It goes straight to the Excyst team.

Suggest a formula

Every worked example is run and compared with an independently computed value whenever this library changes. Download all 1038 as JSON.