Probability and Statistics

Dive into Deep Learning · §1.6

Probability and Statistics: Reasoning Under Uncertainty in Machine Learning
aleatoric vs. epistemic uncertainty · distributions & conditioning · Bayes’ theorem · expectation & covariance · \sigma/\sqrt{n} error bars

Why Probability and Statistics Are the Language of Machine Learning

Motivation

  • Calibrated predictions & losses: Softmax outputs P(Y \mid \mathbf{x}) quantify predictive risk; cross-entropy and MSE arise directly from maximum likelihood P(\mathcal{D} \mid \mathbf{w}).
  • Monte Carlo training & evaluation: Minibatch SGD estimates \nabla \mathbb{E}[\ell] from B = 256 examples, while standard errors \sigma/\sqrt{n} separate true gains from test-set noise.
  • Forward vs. inverse duality: Probability predicts data from known \boldsymbol{\theta}; statistics infers \hat{\boldsymbol{\theta}} and error bars from data \mathcal{D}.

Two Sources of Uncertainty: Aleatoric vs. Epistemic

Taxonomy of Uncertainty

  • Data (aleatoric) uncertainty — irreducible: Intrinsic randomness or ambiguity in the observation itself.
    • Even when we know a coin is fair (p = 0.5), the next toss is still 50/50.
    • A blurry 28 \times 28 Fashion-MNIST image that humans split 60/40 between pullover and coat stays ambiguous no matter how many training images we collect.
  • Model (epistemic) uncertainty — reducible: Ignorance about true parameters (p or weights \mathbf{w}) due to finite sample size n.
    • Shrinks at rate 1/\sqrt{n} as we collect more data.

Sampling and Empirical Frequencies

From Models to Data

Drawing realizations from a distribution P is called sampling. For n independent tosses of a fair coin with P = (0.5, 0.5), the count vector follows a multinomial distribution:

  • Dividing observed counts by n gives the empirical frequency \hat{P}_n = \textrm{counts}/n, an estimator of the true probability P = (0.5, 0.5).
  • In a single 100-toss trial, counts routinely deviate from (50, 50) by several heads:
fair_probs = torch.tensor([0.5, 0.5])
Multinomial(100, fair_probs).sample()
tensor([48., 52.])
  • Across five independent 100-toss experiments, \hat{p}_n fluctuates noticeably around 0.50 (whereas at n = 10{,}000, fluctuations tighten tenfold to \approx \pm 0.005):
Multinomial(100, fair_probs).sample((5,)) / 100
tensor([[0.5000, 0.5000],
        [0.4500, 0.5500],
        [0.5000, 0.5000],
        [0.4900, 0.5100],
        [0.5800, 0.4200]])

The Law of Large Numbers: Convergence of Running Frequencies

Asymptotic Consistency

  • Tracking the running frequency \hat{p}_n = \frac{1}{n}\sum_{i=1}^n X_i after every toss n = 1, 2, \ldots, 10{,}000 via cumsum illustrates the Law of Large Numbers (LLN): \hat{p}_n = \frac{1}{n}\sum_{i=1}^n X_i \xrightarrow{n \to \infty} p = 0.5
  • Early swings at n < 100 are wide, but as n \to 10{,}000, the empirical curve locks onto P(\textrm{heads}) = 0.5.

The missing piece: The LLN guarantees eventual convergence as n \to \infty, but does not tell us how fast estimation error shrinks at finite n.

How Fast Do Empirical Estimates Converge? The 1/√n Envelope

Rate of Convergence

  • Simulating 1{,}000 experiments at each sample size n \in \{10, 100, 1{,}000, 10{,}000\} reveals a straight line of slope -1/2 on a log–log plot: \textrm{std}(\hat{p}_n) = \frac{0.5}{\sqrt{n}}
  • The quadratic cost of precision:
    • Shrinking error by 2\times requires 4\times more evaluation examples.
    • Shrinking error by 10\times requires 100\times more examples (n = 100 \to \pm 5\%; n = 10{,}000 \to \pm 0.5\%).
  • To derive this 1/\sqrt{n} law from first principles, we formalize events, random variables, expectation, and variance.

Sample Spaces, Events, and Kolmogorov’s Axioms

Foundations of Probability

  • A random experiment has a sample space \mathcal{S} of all possible outcomes; an event is any subset \mathcal{A} \subseteq \mathcal{S}.
  • Kolmogorov’s three axioms (1933):
    1. Nonnegativity: P(\mathcal{A}) \ge 0 for every \mathcal{A} \subseteq \mathcal{S}.
    2. Normalization: P(\mathcal{S}) = 1 (and P(\emptyset) = 0).
    3. Additivity: For mutually exclusive events (\mathcal{A}_i \cap \mathcal{A}_j = \emptyset), P(\bigcup_i \mathcal{A}_i) = \sum_i P(\mathcal{A}_i).
  • Complement (P(\mathcal{A}^\complement) = 1 - P(\mathcal{A})) & inclusion–exclusion: P(\mathcal{A} \cup \mathcal{B}) = P(\mathcal{A}) + P(\mathcal{B}) - P(\mathcal{A} \cap \mathcal{B})

Die roll (\mathcal{S} = \{1,\ldots,6\}): For \mathcal{A} = \{2, 4, 6\} (even) and \mathcal{B} = \{5, 6\} (\ge 5), \mathcal{A} \cap \mathcal{B} = \{6\}, so P(\mathcal{A} \cup \mathcal{B}) = \frac{3}{6} + \frac{2}{6} - \frac{1}{6} = \frac{2}{3}.

Discrete vs. Continuous Random Variables

Random Variables & Distributions

  • A random variable X: \mathcal{S} \to \mathbb{R} maps outcomes to numbers (e.g., mapping 2^{100} coin sequences to \{0, \ldots, 100\} heads).
  • Discrete (probability mass function): Assigns mass P(X = v) \ge 0 to individual values with \sum_v P(X = v) = 1 (e.g., softmax over classes or vocabulary tokens).
  • Continuous (probability density function): Described by a density p(x) \ge 0 where probability is area under the curve: P(a \le X \le b) = \int_a^b p(x)\,dx, \quad \int_{-\infty}^{\infty} p(x)\,dx = 1 Note: p(x) can exceed 1, while P(X = x) = 0 at any single point.

Joint, Marginal, and Conditional Probability

Sum Rule & Product Rule

  • Joint distribution P(X = x, Y = y): Probability that X = x and Y = y occur together (a 2D table whose entries sum to 1).
  • Sum rule (marginalization): Sum out nuisance or latent variables along an axis (sum(axis=1)): P(X = x) = \sum_y P(X = x, Y = y)
  • Conditioning & product (chain) rule: Restrict to row X = x and renormalize by P(X = x): P(Y \mid X) = \frac{P(X, Y)}{P(X)} \iff P(X, Y) = P(Y \mid X)\,P(X) Iterating the product rule factorizes autoregressive language models: P(x_1, \ldots, x_T) = \prod_{t=1}^T P(x_t \mid x_{<t}).

Bayes’ Theorem: Reversing Conditioning

Inverse Probability

  • Writing the joint distribution in both orders, P(H, D) = P(D \mid H)P(H) = P(H \mid D)P(D), and dividing by P(D) yields Bayes’ theorem: P(H \mid D) = \frac{P(D \mid H)\,P(H)}{P(D)} = \frac{\textrm{likelihood} \times \textrm{prior}}{\textrm{evidence}} where P(D) = \sum_h P(D \mid H = h)\,P(H = h) normalizes the posterior across all hypotheses.
  • Forward model \to inverse inference: Generative models specify how hidden causes or labels H produce observed features or test results D (P(D \mid H)); Bayes’ theorem inverts this to infer P(H \mid D).

Dependence, Independence, and ‘Explaining Away’

Graphical Structure & Conditioning

  • Marginal independence (X \perp Y): P(X, Y) = P(X)P(Y).
  • Conditional independence (X \perp Y \mid Z): P(X, Y \mid Z) = P(X \mid Z)P(Y \mid Z). Conditioning can destroy or create dependence:
    1. Common cause (X \leftarrow Z \to Y): Dependent marginally, but independent once common cause Z is observed.
    2. Markov chain (X \to Y \to Z): Past X \perp future Z given present Y.
    3. Common effect (X \to Z \leftarrow Y, explaining away): Independent causes (Rain \perp Sprinkler) become negatively dependent once common effect Z = 1 (wet grass) is observed.

Expectation: Center of Mass and Unbiased Estimators

First Moment

  • The expectation (mean \mu = \mathbb{E}[X]) is the probability-weighted center of mass: \mathbb{E}[X] = \sum_x x\,P(X = x), \qquad \mathbb{E}[f(X)] = \sum_x f(x)\,P(X = x)
  • Examples: Investment return 0.5(0) + 0.4(2) + 0.1(10) = 1.8; Bernoulli indicator X \in \{0, 1\} has \mathbb{E}[X] = p.
  • Linearity of expectation (always holds, even if X, Y are dependent): \mathbb{E}[aX + bY] = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y] Thus \mathbb{E}[\hat{p}_n] = \frac{1}{n}\sum_{i=1}^n \mathbb{E}[X_i] = p: sample frequencies and minibatch SGD gradients are unbiased estimators.

Variance and Standard Deviation: Measuring Spread

Second Central Moment

  • Variance measures expected squared deviation around \mu = \mathbb{E}[X]; standard deviation \sigma = \sqrt{\mathrm{Var}(X)} restores the original units of X: \mathrm{Var}(X) = \mathbb{E}\!\left[(X - \mu)^2\right] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2
  • Shift invariance & quadratic scaling: \mathrm{Var}(aX + b) = a^2\,\mathrm{Var}(X).
  • Investment return: \mathbb{E}[X^2] = 0.5(0) + 0.4(4) + 0.1(100) = 11.6, so \mathrm{Var}(X) = 11.6 - 1.8^2 = 8.36 (\sigma \approx 2.9).
  • Bernoulli indicator X \in \{0, 1\}: Since X^2 = X, \mathrm{Var}(X) = p - p^2 = p(1 - p) \le \frac{1}{4} (maximized at p = 0.5).

Covariance, Correlation, and the Variance of an Average

Co-Movement & 1/√n Scaling

  • Covariance & correlation (\rho = \frac{\mathrm{Cov}(X, Y)}{\sigma_X \sigma_Y} \in [-1, 1]) quantify linear co-movement: \mathrm{Cov}(X, Y) = \mathbb{E}\!\left[(X - \mu_X)(Y - \mu_Y)\right]
  • Variance of a sum: Expanding \mathbb{E}[(X - \mu_X + Y - \mu_Y)^2] gives \mathrm{Var}(X + Y) = \mathrm{Var}(X) + \mathrm{Var}(Y) + 2\,\mathrm{Cov}(X, Y)
  • Why averaging divides variance by n: For n independent draws (\mathrm{Cov} = 0), variances add (\mathrm{Var}(\sum_{i=1}^n X_i) = n\sigma^2), and dividing by n scales variance by 1/n^2: \mathrm{Var}(\bar{X}_n) = \frac{\sigma^2}{n} \implies \mathrm{SE}(\bar{X}_n) = \frac{\sigma}{\sqrt{n}}

Chebyshev’s Inequality, the Central Limit Theorem, and Bias Testing

Statistical Significance

  • For a fair coin (p = 0.5), \mathrm{SE}(\hat{p}_n) = \sqrt{p(1-p)/n} = 0.5/\sqrt{n}. Comparing \hat{p} = 0.56 at two sample sizes:
    • 56/100 tosses (\mathrm{SE} = 0.05): Deviation 0.06 is 1.2\,\mathrm{SE} (p\text{-value} \approx 0.27, routine chance fluctuation).
    • 5{,}600/10{,}000 tosses (\mathrm{SE} = 0.005): Deviation 0.06 is 12\,\mathrm{SE} (p\text{-value} \approx 0, decisive evidence of bias).
  • Chebyshev’s inequality (any distribution): P(|X - \mu| \ge k\sigma) \le 1/k^2 (at k=2, tail \le 25\%).
  • Central Limit Theorem (Gaussian tails for averages): \bar{X}_n falls within \pm 1\sigma / \pm 2\sigma / \pm 3\sigma with probability 68\% / 95\% / 99.7\% (95\% CI: \hat{p} \pm 1.96\,\mathrm{SE}).
def fraction_as_far(heads, n, num_experiments=1000):
    """Fraction of fair-coin experiments at least as far from n/2 as heads."""
    counts = (torch.rand(num_experiments, n) < 0.5).sum(dim=1)
    far = (counts - n / 2).abs() >= abs(heads - n / 2)
    return far.to(torch.float32).mean()

fraction_as_far(56, 100), fraction_as_far(5600, 10000)
(tensor(0.2820), tensor(0.))

Evaluating Classifiers: Minibatch Noise vs. Paired Comparisons

ML Evaluation & Error Bars

Each test prediction is Bernoulli with \mathrm{SE}(\hat{p}_n) = \sqrt{p(1-p)/n}:

  • Minibatch (n = 256) vs. test set (n = 10{,}000) at p = 0.90: Minibatch \mathrm{SE} \approx \mathbf{1.9\%} (a 3\% dip is normal noise), whereas test-set \mathrm{SE} = \mathbf{0.30\%}.
  • Why paired evaluation on the same test set wins: On 10{,}000 shared images, 9{,}700 agreements cancel (\mathrm{Cov} > 0), cutting \mathrm{SE}(\hat{p}_A - \hat{p}_B) from 0.42\% to \mathbf{0.17\%} (+0.5\% gain = 2.9\,\mathrm{SE}).

Worked Example: Base-Rate Neglect in Medical & Anomaly Screening

Bayes’ Theorem in Practice

  • A diagnostic test D_1 \in \{0, 1\} for HIV status H \in \{0, 1\} has 100\% sensitivity (P(D_1{=}1 \mid H{=}1) = 1.00) and 99\% specificity (P(D_1{=}1 \mid H{=}0) = 0.01), with prevalence P(H{=}1) = 0.0015.
  • By the sum rule, P(D_1{=}1) = 1.00(0.0015) + 0.01(0.9985) = 0.011485. Bayes’ theorem gives: P(H{=}1 \mid D_1{=}1) = \frac{0.0015}{0.011485} = \mathbf{0.1306} \;(13.1\%)
  • Why so low? Out of 10{,}000 people, all 15 infected cases test positive, but 1\% of 9{,}985 healthy people creates \approx 100 false alarms (15 / 115 \approx 13.1\%).

Sequential Bayesian Updating and Correlated Evidence

Two-Stage Screening & Monte Carlo

  • Follow-up test D_2 (sensitivity 0.98, FPR 0.03): Under conditional independence D_1 \perp D_2 \mid H, joint false positives drop to 0.01 \times 0.03 = 0.0003: P(H{=}1 \mid D_1{=}1, D_2{=}1) = \frac{0.00147}{0.00147 + 0.00030} = \mathbf{0.8307}
  • Correlated errors: If shared biochemistry couples false positives (P(D_1{=}1, D_2{=}1 \mid H{=}0) > 0.0003), false alarms multiply and the posterior drops (e.g., to 32.9\% if joint FPR rises tenfold to 0.003).
n = 2000000
H = torch.rand(n) < 0.0015
D1 = torch.rand(n) < torch.where(H, 1.00, 0.01)
D2 = torch.rand(n) < torch.where(H, 0.98, 0.03)
H[D1 & D2].to(torch.float32).mean()  # Exact value: 0.8307
tensor(0.8220)

Concept Check: Standard Errors & Bayesian Updating

Check Your Understanding

Test your intuition on three practical machine learning design problems:

  1. Sizing a test set: Your classifier has accuracy p \approx 0.90. How many test examples n are required to achieve a standard error of \mathrm{SE}(\hat{p}_n) = 0.005 (0.5\%)? How many for \mathrm{SE} = 0.0025?
  2. Explaining away: Two independent fair coins X, Y \in \{0, 1\} are tossed, and we observe Z = \max(X, Y) = 1 (at least one heads). What is P(X = 1 \mid Z = 1), and how does it change if we then observe Y = 1?
  3. Shifting the prior: If the first HIV test (100\% sensitivity, 1\% FPR) is used in a high-risk clinic where prevalence is P(H = 1) = 0.01 (1\%) instead of 0.15\%, what is P(H = 1 \mid D_1 = 1)?

Answers:

  1. \sqrt{0.9 \times 0.1 / n} = 0.005 \implies n = 0.09 / 0.000025 = \mathbf{3{,}600} images. Halving \mathrm{SE} to 0.0025 requires 4\times more data: \mathbf{14{,}400} images.
  2. P(X = 1 \mid Z = 1) = \mathbf{2/3} (among \{(1,0), (0,1), (1,1)\}). Observing Y = 1 explains away Z = 1, dropping P(X = 1 \mid Z = 1, Y = 1) back to \mathbf{1/2}.
  3. P(H = 1 \mid D_1 = 1) = \frac{1.00 \times 0.01}{1.00(0.01) + 0.01(0.99)} = \frac{0.01}{0.0199} \approx \mathbf{50.3\%} (true positives and false positives are now 1{:}1).

Summary: Probabilistic Tools and Their Deep Learning Roles

Key Takeaways

Concept / Rule Mathematical Form Scaling / Behavior Primary Deep Learning Role
Marginalization (Sum Rule) P(X) = \sum_y P(X, Y) Collapses one axis (sum(axis=...)) Averaging over latent variables & ensembles
Chain Rule (Product Rule) P(X, Y) = P(Y \mid X)\,P(X) Exact factorization of any joint P(\mathbf{x}) Autoregressive LLMs \prod_t P(x_t \mid x_{<t})
Bayes’ Theorem P(H \mid D) = \frac{P(D \mid H)P(H)}{P(D)} Posterior \propto likelihood \times prior MAP estimation, anomaly & medical screening
Linearity of Expectation \mathbb{E}[aX + bY] = a\mathbb{E}[X] + b\mathbb{E}[Y] Holds even when X, Y are dependent Unbiased minibatch SGD gradient estimates
Standard Error of a Mean \mathrm{SE}(\bar{X}_n) = \sigma / \sqrt{n} 4\times data \to \frac{1}{2} error; 100\times data \to \frac{1}{10} error Test-set sizing & paired model comparisons
Aleatoric vs. Epistemic Data noise vs. parameter ignorance Aleatoric: irreducible; Epistemic: \propto 1/\sqrt{n} Softmax calibration vs. active data collection