AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·147

Probability and Statistics

The language of uncertainty that every model speaks: sample spaces and random variables, discrete and continuous distributions (Bernoulli, binomial, categorical, Poisson, uniform, normal, multivariate normal), expectation, variance and covariance, conditional probability, independence and Bayes' theorem with a worked diagnostic-test example, maximum likelihood and why it gives MSE and cross-entropy, MAP estimation and regularisation, entropy, cross-entropy and KL divergence derived from information theory, softmax with numerically stable log-sum-exp, sampling methods (inverse CDF, Monte Carlo, temperature, top-k/top-p preview), the law of large numbers and central limit theorem, confidence intervals and bootstrap, hypothesis testing, p-values and A/B tests for model comparison, with code in Python, R, Julia, Rust and Go.

38 topics · ~25 min read · 33-question quiz
Updated Suggest a correction

Start here: reasoning when you can't be sure

Every model outputs uncertain guesses, every dataset is a sample, and every measured accuracy has error bars. Probability is the language for uncertainty (how likely things are); statistics is how you learn from samples without fooling yourself. Four results do most of the work in practice.

Averages behave better than individuals

Tiffin order values are lopsided: most are ₹120–200, and 5% are ₹2,000 party orders. Mean ₹252, median ₹162, skewness 4.2. Take averages of n random orders, 20,000 times:

Text
means of   1 order:   spread ₹395   skewness 4.38
means of   5 orders:  spread ₹181   skewness 1.88
means of  30 orders:  spread  ₹73   skewness 0.74
means of 200 orders:  spread  ₹29   skewness 0.32     (theory σ/√n: ₹28.7)

The spread of an average shrinks like σ/√n (four times the data, half the uncertainty), and its distribution becomes bell-shaped even though individual orders aren't: the central limit theorem. It's why error bars on accuracy, A/B results and averages are possible at all.

Confidence intervals mean what they say (when used right)

A 12% conversion rate measured from 400 visitors, repeated 10,000 times; each time a 95% confidence interval (p̂ ± 1.96 × standard error) was computed:

Text
the interval contained the true 12% in 95.0% of repeats; typical width ±3.2 points

With 400 visitors, "12%" really means "somewhere around 9–15%". When a model's accuracy improves from 91% to 92% on a test set of 1,000 examples, that's inside the noise.

Peeking turns noise into "discoveries"

Two identical versions of the menu page (an A/A test: no real difference). A chi-squared test at the 5% level should call it "significant" about 5% of the time:

Text
one test at the planned 5,000 users per group:      'significant' in  5.9% of experiments
checking after every 100 users, stopping at p<0.05: 'significant' in 31.1% of experiments

Checking repeatedly and stopping at the first good-looking p-value gave a false "winner" six times as often. The same trap appears in ML when you try many models, features or seeds against one test set and report the best: the test set gets "used up". Fix the sample size and analysis in advance, or use methods designed for repeated looks (sequential tests).

Base rates: a 99% accurate detector that's usually wrong

A fraud flag catches 99% of fraud and wrongly flags 1% of honest orders. Only 0.5% of orders are fraud. Bayes' theorem:

Text
P(fraud | flagged) = 0.99 × 0.005 / (0.99 × 0.005 + 0.01 × 0.995) = 33.2%

Two of every three flagged orders are honest, because honest orders vastly outnumber fraud. Rare-event classifiers must be judged with this in mind (chapter 149's precision and recall).

How deep to go in probability and statistics

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain probability, distributions, mean, variance and base rates
L2 Compute confidence intervals and run a correct A/B test with a fixed plan
L3 Explain the CLT, likelihood, MLE, Bayes' theorem and why cross-entropy is a likelihood
L4 Spot statistical errors: peeking, multiple comparisons, base-rate neglect, leakage-inflated results
L5 Design experiments and evaluation protocols with adequate power and honest uncertainty
L6 Set experimentation and evaluation standards across an organisation

Why probability

Data is noisy, labels are uncertain, and the future is unknown. Probability gives a calculus for uncertainty; statistics turns observed data into conclusions about the process that generated it. Nearly every ML idea has a probabilistic reading:

  • A classifier outputs a probability distribution over classes; an LLM outputs a distribution over the next token.
  • Training by minimising MSE or cross-entropy is maximum likelihood estimation under a noise model.
  • Regularisation is a prior (MAP estimation).
  • Generation is sampling from a learned distribution.
  • Evaluating whether model B beats model A is hypothesis testing.

Foundations

Sample spaces, events, axioms

  • Sample space Ω: all possible outcomes (a die: {1, …, 6}).
  • Event: a subset of Ω ("roll is even" = {2, 4, 6}).
  • Probability P assigns each event a number with the Kolmogorov axioms: P(A) ≥ 0; P(Ω) = 1; for disjoint events, P(A ∪ B) = P(A) + P(B).

Consequences: P(not A) = 1 − P(A); P(A ∪ B) = P(A) + P(B) − P(A ∩ B).

Two interpretations: frequentist (long-run frequency of repeatable experiments) and Bayesian (degree of belief, updated by evidence). ML uses both freely.

Random variables

A random variable X maps outcomes to numbers.

  • Discrete: countable values, described by a probability mass function (PMF) p(x) = P(X = x), summing to 1.
  • Continuous: values in an interval, described by a probability density function (PDF) f(x), integrating to 1. P(X = exact value) = 0; probabilities are areas: P(a ≤ X ≤ b) = ∫ₐᵇ f(x) dx. Densities can exceed 1.
  • Cumulative distribution function (CDF) F(x) = P(X ≤ x), for both kinds.

Common distributions

Distribution Parameters Models Mean Variance
Bernoulli p One yes/no trial (click, spam) p p(1 − p)
Binomial n, p Successes in n independent trials np np(1 − p)
Categorical p₁ … p_K One draw from K classes (next token!) — —
Multinomial n, p₁…p_K Counts over K classes in n draws npᵢ npᵢ(1 − pᵢ)
Poisson λ Counts of rare events per interval (requests/second) λ λ
Geometric p Trials until first success 1/p (1 − p)/p²
Uniform a, b Equal likelihood over an interval (a + b)/2 (b − a)²/12
Normal (Gaussian) μ, σ² Sums of many small effects; measurement noise μ σ²
Exponential λ Waiting time between Poisson events 1/λ 1/λ²
Beta α, β Uncertainty about a probability (prior for Bernoulli) α/(α + β) —
Dirichlet α₁…α_K Distributions over distributions (prior for categorical) — —

The normal distribution

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

  • About 68% of mass within 1σ of the mean, 95% within 1.96σ, 99.7% within 3σ.
  • Standardisation: z = (x − μ)/σ gives a standard normal N(0, 1).
  • Multivariate normal N(μ, Σ): mean vector μ, covariance matrix Σ. Contours are ellipses whose axes are Σ's eigenvectors (chapter 145). Used in weight initialisation, VAEs, diffusion models, Gaussian processes.
μ μ−σμ+σ μ−2σμ+2σ μ−3σμ+3σ 68% ≈95% in ±2σ 99.7%
The normal distribution's bell curve with standard deviation bands. About 68% of probability lies within one standard deviation of the mean, about 95% within 1.96 standard deviations, and 99.7% within three. Standardising subtracts the mean and divides by the standard deviation so every normal becomes the standard normal.
Python
import numpy as np
rng = np.random.default_rng(42)
x = rng.normal(loc=170, scale=8, size=100_000)     # heights, cm
np.mean(np.abs(x - 170) < 8), np.mean(np.abs(x - 170) < 16)   # ≈ 0.683, 0.954

from scipy import stats
stats.norm(170, 8).cdf(186) - stats.norm(170, 8).cdf(154)     # exact 0.9545
stats.binom(n=10, p=0.3).pmf(3)                                # P(3 successes) ≈ 0.2668
stats.poisson(mu=4).pmf(0)                                     # P(no events) = e⁻⁴ ≈ 0.0183

Expectation, variance, covariance

Expectation

The expected value is the probability-weighted average:

  • Discrete: E[X] = Σ x p(x). Continuous: E[X] = ∫ x f(x) dx.
  • Linearity (always holds, even for dependent variables): E[aX + bY] = aE[X] + bE[Y].
  • E[g(X)] = Σ g(x) p(x) (the "law of the unconscious statistician"). In general E[g(X)] ≠ g(E[X]) (Jensen's inequality: for convex g, E[g(X)] ≥ g(E[X])).

The loss we minimise is an expectation: expected loss over the data distribution, approximated by the average over the training set (empirical risk).

Variance and standard deviation

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

  • Var(aX + b) = a² Var(X).
  • Standard deviation σ = √Var, in the same units as X.
  • For independent X, Y: Var(X + Y) = Var(X) + Var(Y). Averaging n independent samples divides variance by n → standard error σ/√n. This is why bigger batches give less noisy gradients and why more test examples give tighter accuracy estimates.

Covariance and correlation

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

  • Positive: they move together; negative: opposite; zero: no linear relation.
  • Correlation ρ = Cov(X, Y)/(σ_X σ_Y) ∈ [−1, 1]: scale-free.
  • Independence ⇒ zero covariance, but not the converse: Y = X² with symmetric X has zero correlation yet is fully dependent.
  • Correlation is not causation: confounders, reverse causation, selection effects (chapter 149's leakage problems are often hidden correlations).
  • The covariance matrix Σ of a random vector is symmetric positive semi-definite; PCA eigendecomposes it (chapter 145).

Conditional probability and Bayes

Conditional probability and independence

P(A | B) = P(A ∩ B) / P(B)

"Probability of A given that B happened": restrict the world to B.

  • Product rule: P(A ∩ B) = P(A | B) P(B).
  • Independence: P(A | B) = P(A), equivalently P(A ∩ B) = P(A)P(B).
  • Conditional independence: A and B independent given C. Naive Bayes assumes features are conditionally independent given the class.
  • Law of total probability: P(A) = Σᵢ P(A | Bᵢ) P(Bᵢ) over a partition {Bᵢ}.
  • Chain rule of probability: P(x₁, …, xₙ) = P(x₁) P(x₂ | x₁) P(x₃ | x₁, x₂) … — exactly how autoregressive language models factor the probability of a text: each token conditioned on all previous ones (chapter 156).

Bayes' theorem

P(H | E) = P(E | H) · P(H) / P(E)

  • P(H): prior, belief before evidence.
  • P(E | H): likelihood, how probable the evidence is if H is true.
  • P(H | E): posterior, updated belief.
  • P(E): evidence, normaliser = Σ over hypotheses of P(E | H)P(H).

Worked example (the base-rate fallacy): a disease affects 1% of people. A test detects it 99% of the time (sensitivity) and has a 5% false-positive rate. You test positive. Probability you have the disease?

  • P(D) = 0.01; P(+ | D) = 0.99; P(+ | ¬D) = 0.05.
  • P(+) = 0.99 × 0.01 + 0.05 × 0.99 = 0.0099 + 0.0495 = 0.0594.
  • P(D | +) = 0.0099 / 0.0594 ≈ 0.167: only about 17%, because healthy people vastly outnumber sick ones.
10,000 people 100 sick (1%) 9,900 healthy 99 test + 1 test − 495 test + (5%) 9,405 test − positives: 594true: 99P(sick|+) ≈ 17%
Bayes' theorem as counting. Out of 10,000 people, 100 have the disease and 99 of them test positive; of the 9,900 healthy people, 5% or 495 also test positive. Among all 594 positive results only 99 are true positives, so the posterior probability of disease given a positive test is about 17 percent. The same base-rate effect makes rare-class detectors such as fraud models produce many false alarms.
Python
def posterior(prior, sens, fpr):
    evidence = sens * prior + fpr * (1 - prior)
    return sens * prior / evidence

p = posterior(0.01, 0.99, 0.05)     # 0.1667
p2 = posterior(p, 0.99, 0.05)       # second independent positive test: ≈ 0.798

Bayesian updating is sequential: today's posterior is tomorrow's prior. Naive Bayes classifiers apply Bayes with the conditional-independence assumption: P(class | words) ∝ P(class) Πᵢ P(wordᵢ | class), a strong baseline for text (chapter 148).

Likelihood and estimation

Maximum likelihood estimation (MLE)

Given data D = {x₁, …, xₙ} assumed i.i.d. (independent, identically distributed) from a model p(x | θ), the likelihood is L(θ) = Πᵢ p(xᵢ | θ): how probable the observed data is under parameters θ (a function of θ, not a probability distribution over θ). MLE picks θ maximising it. Products of many small numbers underflow, and sums are easier to differentiate, so we maximise the log-likelihood Σᵢ log p(xᵢ | θ), or equivalently minimise the negative log-likelihood (NLL).

Example: coin flips with 7 heads in 10. Log-likelihood ℓ(p) = 7 log p + 3 log(1 − p). Derivative 7/p − 3/(1 − p) = 0 → p̂ = 0.7, the sample frequency.

Why loss functions are likelihoods

  • MSE = Gaussian MLE: assume y = f(x; θ) + ε with ε ~ N(0, σ²). Then −log p(y | x, θ) = (y − f(x; θ))²/(2σ²) + const. Minimising NLL = minimising squared error.
  • Cross-entropy = categorical MLE: a classifier outputs probabilities p_θ(k | x). NLL of the true class y is −log p_θ(y | x): the cross-entropy loss. Binary case (Bernoulli) gives log loss: −[y log p + (1 − y) log(1 − p)].
  • MAE = Laplace noise MLE, robust to outliers.
  • LLM pre-training minimises NLL of the next token: maximum likelihood over trillions of tokens.

MAP estimation and priors

Maximum a posteriori (MAP) maximises the posterior p(θ | D) ∝ p(D | θ) p(θ), i.e. log-likelihood + log-prior:

  • Gaussian prior θ ~ N(0, τ²) → log-prior = −‖θ‖²/(2τ²) → L2 regularisation / weight decay.
  • Laplace prior → L1 regularisation (sparsity, lasso).

Full Bayesian inference keeps the whole posterior distribution rather than a point estimate, giving uncertainty; exact computation is usually intractable, so we use MCMC sampling or variational inference (approximating the posterior with a simpler distribution: the idea behind VAEs, chapter 153).

Bias and variance of estimators

An estimator θ̂ has bias E[θ̂] − θ and variance Var(θ̂); MSE = bias² + variance. The sample variance with denominator n is biased (underestimates); dividing by n − 1 (Bessel's correction) removes the bias. The same trade-off reappears as the model bias-variance trade-off in chapter 149.

Information theory

Entropy

Claude Shannon's information content (surprise) of an outcome with probability p is −log₂ p bits: certain events carry 0 bits, a fair coin flip 1 bit, a 1-in-1024 event 10 bits.

Entropy is the expected surprise of a distribution:

H(p) = −Σₓ p(x) log p(x)

  • Maximal for the uniform distribution (log K for K outcomes); zero for a deterministic one.
  • It's the minimum average number of bits needed to encode samples from p (source coding theorem). Tokenizers and compression connect here (chapter 155).

Cross-entropy

H(p, q) = −Σₓ p(x) log q(x)

The average number of bits to encode samples from the true distribution p using a code optimised for model q. With p a one-hot label, H(p, q) = −log q(true class): exactly the classification loss. Perplexity = exp(cross-entropy in nats): the effective number of equally likely choices the model is "confused" between per token (chapter 156).

KL divergence

D_KL(p ‖ q) = Σₓ p(x) log (p(x)/q(x)) = H(p, q) − H(p)

  • The extra bits paid for using q instead of p. ≥ 0 (Gibbs' inequality), = 0 iff p = q.
  • Not symmetric: D_KL(p ‖ q) ≠ D_KL(q ‖ p); not a true distance. Forward KL (p‖q) is "mean-seeking" (q covers all of p's modes); reverse KL (q‖p) is "mode-seeking".
  • Since H(p) of the data is fixed, minimising cross-entropy = minimising KL from the data distribution to the model.
  • Appears in: VAEs (KL to the prior), knowledge distillation (match the teacher's distribution), RLHF and DPO (KL penalty keeping the fine-tuned policy near the reference model, chapter 164), drift detection (chapter 177).

Mutual information I(X; Y) = D_KL(p(x, y) ‖ p(x)p(y)): how much knowing one variable reduces uncertainty about the other. Used in feature selection and representation learning (contrastive losses like InfoNCE maximise a bound on it).

true pgood qpoor q H(p) = 0.80 nats H(p, good q) = 0.82KL = 0.02 H(p, poor q) = 1.44KL = 0.63 cross-entropy = H(p) + KL
Entropy, cross-entropy and KL divergence for a three-class example. The true distribution p is 0.7, 0.2, 0.1. A good model q close to p has cross-entropy only slightly above the entropy of p; a poor model pays a larger cross-entropy. The gap between cross-entropy and entropy is exactly the KL divergence, which training reduces.
Python
p = np.array([0.7, 0.2, 0.1]); q_good = np.array([0.6, 0.25, 0.15]); q_bad = np.array([0.2, 0.3, 0.5])
H  = lambda p: -np.sum(p * np.log(p))
CE = lambda p, q: -np.sum(p * np.log(q))
KL = lambda p, q: np.sum(p * np.log(p / q))
round(H(p), 2), round(CE(p, q_good), 2), round(KL(p, q_good), 2)    # 0.8, 0.82, 0.02
round(CE(p, q_bad), 2), round(KL(p, q_bad), 2), round(KL(q_bad, p), 2)   # 1.44, 0.63, 0.68 (asymmetric)

Softmax and numerical stability

A network outputs real-valued logits z₁ … z_K. Softmax turns them into a categorical distribution:

softmax(z)ᵢ = exp(zᵢ) / Σⱼ exp(zⱼ)

  • Invariant to adding a constant to all logits → subtract max(z) before exponentiating to avoid overflow (exp(1000) = inf).
  • Log-softmax via the log-sum-exp trick: log softmax(z)ᵢ = zᵢ − (m + log Σⱼ exp(zⱼ − m)) with m = max z. Frameworks fuse softmax and cross-entropy (PyTorch cross_entropy takes logits) for stability.
  • Gradient of cross-entropy w.r.t. logits = softmax(z) − onehot(y): beautifully simple, as promised in chapter 146.
  • Temperature T: softmax(z/T). T < 1 sharpens (more deterministic), T > 1 flattens (more random), T → 0 approaches argmax. Used in LLM decoding (chapter 157) and distillation.
Python
def log_softmax(z):
    m = z.max()
    return z - (m + np.log(np.sum(np.exp(z - m))))

z = np.array([1000.0, 1001.0, 1002.0])
np.exp(z) / np.exp(z).sum()             # [nan nan nan]: overflow
np.exp(log_softmax(z))                  # [0.090 0.245 0.665]: stable

y = 2                                   # true class
p = np.exp(log_softmax(z))
loss = -log_softmax(z)[y]               # cross-entropy ≈ 0.408
grad_logits = p - np.eye(3)[y]          # [0.090, 0.245, −0.335]

for T in (0.5, 1.0, 2.0):
    print(T, np.round(np.exp(log_softmax(np.array([2.0, 1.0, 0.1]) / T)), 3))
# 0.5 → [0.864 0.117 0.019]; 1.0 → [0.659 0.242 0.099]; 2.0 → [0.502 0.304 0.194]

Sampling

Why sample

  • Generation: draw tokens, pixels or latent vectors from a model's distribution.
  • Monte Carlo estimation: approximate an expectation E[g(X)] ≈ (1/n) Σ g(xᵢ) with samples; error shrinks as 1/√n regardless of dimension.
  • Stochastic training: mini-batches, dropout, data augmentation, random initialisation.
  • Resampling for uncertainty: bootstrap.

Methods

  • Inverse CDF: if U ~ Uniform(0, 1), then F⁻¹(U) has CDF F. Sampling from a categorical: draw u, walk cumulative probabilities until exceeding u.
  • Box–Muller / library samplers for normals.
  • Reparameterisation trick: write z = μ + σ·ε with ε ~ N(0, 1), so gradients flow through μ and σ (VAEs, diffusion).
  • Gumbel-max trick: argmax(zᵢ + Gumbel noise) samples from softmax(z); Gumbel-softmax is a differentiable relaxation.
  • Rejection and importance sampling: sample from an easy distribution, correct with weights or acceptance.
  • Markov chain Monte Carlo (Metropolis–Hastings, Hamiltonian Monte Carlo/NUTS in Stan, PyMC, NumPyro): sample from complex posteriors.
  • Decoding strategies (greedy, temperature, top-k, top-p/nucleus, min-p) are sampling from a truncated, reshaped categorical: the subject of chapter 157.
Python
def sample_categorical(probs, rng):
    u = rng.random()
    return int(np.searchsorted(np.cumsum(probs), u))     # inverse CDF

rng = np.random.default_rng(0)
probs = np.array([0.5, 0.3, 0.2])
counts = np.bincount([sample_categorical(probs, rng) for _ in range(100_000)], minlength=3)
counts / counts.sum()                                    # ≈ [0.5, 0.3, 0.2]

# Monte Carlo estimate of π: fraction of random points inside the unit quarter circle
pts = rng.random((1_000_000, 2))
4 * np.mean((pts ** 2).sum(axis=1) <= 1)                 # ≈ 3.141
# Python: numpy.random.Generator (PCG64), seeded for reproducibility
rng = np.random.default_rng(7)
rng.normal(0, 1, 5); rng.choice(["a", "b", "c"], p=[0.5, 0.3, 0.2], size=10)

Laws of large numbers and the central limit theorem

  • Law of large numbers: the sample mean converges to the true mean as n grows. Justifies training-set averages approximating expected loss, and test accuracy approximating true accuracy.
  • Central limit theorem (CLT): the sum (or mean) of many independent variables with finite variance is approximately normal, whatever their original distribution: X̄ ≈ N(μ, σ²/n). This is why normal-based confidence intervals work for accuracy, latency means and A/B metrics, and why gradient noise from mini-batches looks roughly Gaussian.
raw samples: skewed means ofn = 30 sample means ≈ normal, spread σ/√n
The central limit theorem. Individual samples from a skewed distribution (left) are far from normal, but the distribution of means of 30 samples (right) is close to a normal curve centred on the true mean, with spread equal to sigma divided by the square root of the sample size.

Confidence intervals and the bootstrap

A point estimate (test accuracy 0.874) without uncertainty is incomplete. A 95% confidence interval is a procedure that, over repeated experiments, captures the true value 95% of the time.

  • For a proportion (accuracy) on n test examples: p̂ ± 1.96 √(p̂(1 − p̂)/n). With n = 1,000 and p̂ = 0.874: ±0.021. With n = 100: ±0.065: small test sets can't distinguish models a few points apart.
  • Bootstrap: resample the test set with replacement many times, recompute the metric, take the 2.5th and 97.5th percentiles. Works for any metric (F1, AUC, BLEU, LLM-judge win rates) without formulas.
Python
correct = rng.random(1000) < 0.874                 # simulated per-example correctness
acc = correct.mean()
se = np.sqrt(acc * (1 - acc) / len(correct))
(acc - 1.96 * se, acc + 1.96 * se)                 # normal-approximation CI

boots = [rng.choice(correct, size=len(correct), replace=True).mean() for _ in range(5000)]
np.percentile(boots, [2.5, 97.5])                  # bootstrap CI, very similar

Hypothesis testing

The framework

  1. Null hypothesis H₀: no effect (new model is not better; variant B's conversion rate equals A's).
  2. Choose a test statistic and its distribution under H₀.
  3. Compute the p-value: the probability, assuming H₀ is true, of a result at least as extreme as observed.
  4. If p < α (significance level, often 0.05), reject H₀.

What a p-value is not: the probability that H₀ is true, or the size or importance of an effect.

Error Meaning Controlled by
Type I (false positive) Rejecting a true H₀ α
Type II (false negative) Missing a real effect Power = 1 − β; more data

Power analysis decides sample size before an experiment: detecting a 1-point accuracy difference needs far more examples than a 10-point one.

Common tests

Test Use
z / t-test Compare means (two-sample, paired)
Chi-squared Independence in contingency tables; categorical distributions
McNemar's test Two classifiers on the same test set (counts where exactly one is right)
Paired bootstrap / permutation test Any metric, distribution-free
Mann–Whitney U / Wilcoxon Non-parametric comparisons (latency)
Kolmogorov–Smirnov Compare distributions (data drift, chapter 177)
Python
# Is model B better than A on the same 1,000 examples? McNemar's test on disagreements.
from statsmodels.stats.contingency_tables import mcnemar
a_right_b_wrong, a_wrong_b_right = 38, 61
table = [[0, a_right_b_wrong], [a_wrong_b_right, 0]]     # only off-diagonal cells matter
mcnemar(table, exact=True).pvalue                        # ≈ 0.026 → B significantly better at α = 0.05

# A/B test on conversion: 2-proportion z-test
from statsmodels.stats.proportion import proportions_ztest
proportions_ztest(count=[540, 600], nobs=[10_000, 10_000])   # p ≈ 0.067 → not significant at 0.05

Pitfalls

  • Multiple comparisons: test 20 prompt variants at α = 0.05 and expect one false "win". Correct with Bonferroni (α/m) or Benjamini–Hochberg (controls false discovery rate).
  • Peeking: checking an A/B test daily and stopping when p < 0.05 inflates false positives; use fixed horizons, sequential tests or always-valid inference.
  • Statistical vs practical significance: with millions of samples, trivial differences become "significant"; report effect sizes and intervals.
  • Non-independence: examples from the same user or conversation are correlated; bootstrap by cluster.
  • LLM evaluation variance: sampling temperature, prompt order and judge randomness all add noise; run multiple seeds and report intervals (chapter 175).

Lab: simulation as a statistics teacher

NumPy 2.5 and SciPy 1.18 on the lab machine; every result below comes from repeating a random experiment thousands of times, which is the most reliable way to check a statistical claim you're unsure of.

Experiment 1: the central limit theorem

Population: 9,500 orders ~ N(₹160, ₹30) plus 500 party orders ~ N(₹2,000, ₹300); mean ₹252, median ₹162, skewness 4.2. 20,000 samples of size n:

n sd of the mean σ/√n skewness of the mean
1 ₹395.1 ₹405.6 4.38
5 ₹181.4 ₹181.4 1.88
30 ₹73.4 ₹74.0 0.74
200 ₹28.7 ₹28.7 0.32

"n = 30 is enough for normality" is folklore: with this skew, the mean of 30 still had skewness 0.74, so a symmetric interval would be off in the tails. For heavy-tailed metrics (revenue per user, latency), use the bootstrap (resample with replacement and take percentiles) instead of assuming normality.

Experiment 2: interval coverage

Text
true rate 12%, n = 400, Wald interval p̂ ± 1.96·√(p̂(1−p̂)/n): coverage 95.0% over 10,000 repeats

The simple (Wald) interval works here; it under-covers for rates near 0 or 1 or small n (try p = 1%, n = 100), where the Wilson interval is the safer default. For classifier accuracy on a test set of size n, the same formula gives the error bar: 92% on 1,000 examples is ±1.7 points.

Experiment 3: optional stopping

Text
A/A test, 12% conversion in both groups, χ² test at α = 0.05, 2,000 simulated experiments:
  single test at n = 5,000 per group:          5.9% "significant"
  test every 100 users, stop at first p < 0.05: 31.1% "significant"

Fixes, in order of simplicity: decide the sample size in advance with a power calculation and look once; use a sequential method designed for peeking (alpha spending, always-valid p-values, or a Bayesian approach with a pre-registered decision rule); for ML, keep a test set you touch once, and select models on a separate validation set or with cross-validation.

Experiment 4: base rates

Base rate of fraud P(fraud given flagged), 99% sensitivity and specificity
0.5% 33.2%
5% (compute it) ≈84%
50% 99%

The classifier didn't change; only the population did. That's why precision depends on prevalence, and why a model evaluated on a balanced test set can disappoint in production (chapter 149).

Try it yourself

  1. Replace the Wald interval with Wilson's and measure coverage for p = 1%, n = 100.
  2. Bootstrap a 95% interval for mean order value from a sample of 50 orders, and check its coverage by simulation.
  3. Simulate testing 20 independent features at α = 0.05 when none matters. How often is at least one "significant"? Apply a Bonferroni correction.
  4. Compute the sample size needed to detect 12% → 13% conversion with 80% power at α = 0.05.

Revision sheet: probability and statistics

Key ideas

  • Random variables and distributions: Bernoulli, binomial, categorical, Poisson, uniform, normal, multivariate normal; expectation, variance, covariance.
  • Conditional probability and Bayes' theorem: posterior ∝ likelihood × prior; base rates matter.
  • Law of large numbers and CLT: sample means converge; their spread is σ/√n and their distribution ≈ normal.
  • Estimation: maximum likelihood (cross-entropy loss is negative log-likelihood); MAP and regularisation as priors.
  • Uncertainty: standard errors, confidence intervals (Wald, Wilson, bootstrap), credible intervals.
  • Testing: p-values, power, sample size, multiple comparisons, optional stopping.
  • Information: entropy, cross-entropy, KL divergence (used for losses and distillation).

Numbers to remember

  • 95% CI ≈ ±1.96 standard errors; for a proportion, SE = √(p(1−p)/n).
  • Lab: peeking every 100 users raised false positives from ~5% to 31%.
  • Lab: 99%/99% detector at 0.5% prevalence → 33% precision.
  • Accuracy on 1,000 test examples: about ±1.7–1.9 points.

Pitfalls

  • Treating small accuracy differences as real without error bars.
  • Peeking, early stopping on significance, and reporting the best of many tries.
  • Base-rate neglect; evaluating on balanced data and deploying on imbalanced.
  • Assuming normality for heavy-tailed metrics.
  • Confusing p-values with the probability a hypothesis is true.

Glossary

  • Standard error: spread of an estimate across samples.
  • Power: probability of detecting a real effect of a given size.
  • Likelihood: probability of the data under given parameters.
  • KL divergence: how one distribution differs from another.
  • Bootstrap: estimating uncertainty by resampling the data.