SafeZone AI Learn
Learn/ Mathematical Foundations/ Probability & Statistical Inference · lesson 1 of 9

Random variables and distributions

The working vocabulary of uncertainty: expectation and variance as operators you can push through models, the distribution zoo with its parameters under your fingers, and conditioning — the single most important operation in machine learning.

Where this came from. Probability began in 1654 as a gambling dispute — how to split an interrupted game’s pot fairly — settled in letters between Pascal and Fermat that invented expected value along the way. It took a century for Bayes to reverse evidence back to causes, another for Gauss to give measurement error a distribution, and until 1933 for Kolmogorov to give the whole subject axioms. Respectable mathematics did not “do” uncertainty; every formula in this module was a scandal first. The story is in How the mathematics was forged; the machinery starts here.

Machine learning is a probability discipline wearing an optimization costume. A model’s output is a conditional distribution; a loss is a negative log-likelihood in disguise (that reveal comes in lesson 3); every evaluation metric is an expectation estimated from samples. This module builds the probability a practitioner actually leans on daily — not measure theory, but fluency: the operators, the standard distributions, and above all conditioning, which is what the word “prediction” formally means.

Random variables, and the two operators that matter

A random variable XX assigns a number to each outcome of a random process; it is described by its distribution — a pmf p(x)p(x) for discrete values, a pdf f(x)f(x) for continuous ones (heights of a density, not probabilities themselves: only areas abf\int_a^b f are probabilities — the classic beginner trap, since densities happily exceed 1). Two functionals summarize a distribution, and they behave like operators with algebra worth memorizing:

E[X]=xxp(x)   or   xf(x)dx,Var[X]=E[(XEX)2]=E[X2](EX)2.\mathbb{E}[X] = \sum_x x\, p(x) \;\text{ or }\; \int x f(x)\, dx, \qquad \operatorname{Var}[X] = \mathbb{E}\big[(X - \mathbb{E}X)^2\big] = \mathbb{E}[X^2] - (\mathbb{E}X)^2 .

The rules — provable in two lines each, used ten thousand times each:

  • Linearity of expectation: E[aX+bY]=aEX+bEY\mathbb{E}[aX + bY] = a\,\mathbb{E}X + b\,\mathbb{E}Yunconditionally, independence not required. The single most-used fact in this curriculum’s proofs (the unbiasedness of minibatch gradients was exactly this).
  • Variance algebra: Var[aX]=a2Var[X]\operatorname{Var}[aX] = a^2 \operatorname{Var}[X], and Var[X+Y]=VarX+VarY\operatorname{Var}[X + Y] = \operatorname{Var}X + \operatorname{Var}Y only under independence (in general add 2Cov(X,Y)2\operatorname{Cov}(X,Y) — forgetting the covariance term is how the forest lesson’s ρσ2\rho\sigma^2 floor surprises people).
  • The consequence that runs statistics: an average of nn i.i.d. draws has E[Xˉ]=μ\mathbb{E}[\bar X] = \mu and Var[Xˉ]=σ2/n\operatorname{Var}[\bar X] = \sigma^2/n — the 1/n1/\sqrt n standard-error law, formally born here and starring in the next lesson.

The zoo, and how to choose from it

Distributions are modeling assumptions with names. Choosing one is asserting a data-generating story, and each standard story earns its slot:

DistributionThe story it tellsMean / VarianceWhere this curriculum uses it
Bernoulli(pp)one yes/no eventpp / p(1p)p(1-p)classification labels; cross-entropy’s origin
Binomial(n,pn, p)count of yes in nn triesnpnp / np(1p)np(1-p)vote-sim & judge widgets (RL track)
Poisson(λ\lambda)counts of rare events in a windowλ\lambda / λ\lambdaarrivals, defects, word counts
Gaussian(μ,σ2\mu, \sigma^2)sum of many small effectsμ\mu / σ2\sigma^2noise models; least squares (lesson 3)
Exponential(λ\lambda)waiting time, memoryless1/λ1/\lambda / 1/λ21/\lambda^2durations, survival, queues

Play deliberately: on the Binomial, push p toward 0.05 and watch symmetry break (the Gaussian resemblance at p = 0.5 is the next lesson’s CLT foreshadowed — and its failure at extreme p with small n is why rare-event problems need care); on the Poisson, confirm mean = variance as λ moves (a testable fingerprint — count data with variance ≫ mean is “overdispersed” and the Poisson story is wrong); on the Exponential, notice the mode is at zero no matter the parameter — if your waiting-time data has a hump away from zero, memorylessness is already refuted. Reading a distribution’s SHAPE as a claim about the world is the skill; the sliders are for calibrating it.

Joint, marginal, conditional: the grammar of “given”

Real problems involve several variables, and three constructions relate them. The joint p(x,y)p(x, y) says everything; the marginal p(x)=yp(x,y)p(x) = \sum_y p(x, y) integrates the rest away; the conditional re-normalizes a slice:

p(yx)=p(x,y)p(x).p(y \mid x) = \frac{p(x, y)}{p(x)} .

Conditioning is the central operation of machine learning — the whole discipline of supervised learning is the art of estimating p(yx)p(y \mid x): the logistic model was Pr(y=1x)\Pr(y{=}1 \mid x), a language model is p(next tokencontext)p(\text{next token} \mid \text{context}), and “prediction” means computing a conditional. Two structural facts complete the grammar. Independence (p(x,y)=p(x)p(y)p(x,y) = p(x)p(y) — knowing one tells nothing about the other) is the assumption behind every “i.i.d.” in this curriculum, and its conditional cousin — XYZX \perp Y \mid Z — is subtler and stronger machinery: Naive Bayes assumes features independent given the class; Markov chains assume the future independent of the past given the present (the Markov property that carried the entire RL track). And the chain rule p(x1,,xn)=ip(xix<i)p(x_1, \ldots, x_n) = \prod_i p(x_i \mid x_{<i}) factorizes any joint into conditionals — the identity that makes autoregressive language models possible at all.

The inversion of conditioning — p(xy)p(x \mid y) from p(yx)p(y \mid x) — is Bayes’ theorem, which gets lesson 4 to itself. Here, just the shape of the trap it resolves: Pr(diseasepositive test)\Pr(\text{disease} \mid \text{positive test}) and Pr(positive testdisease)\Pr(\text{positive test} \mid \text{disease}) differ by the base rate, and confusing them (the prosecutor’s fallacy) is possibly the most consequential statistical error civilians make.

Expectation as the universal interface

A closing reframe that pays rent across the curriculum: nearly every quantity ML optimizes or reports is an expectation —

risk=E(x,y)[(y,f(x))],J(π)=Eπ[G0],accuracy=E[1{y^=y}]\text{risk} = \mathbb{E}_{(x,y)}[\ell(y, f(x))], \qquad J(\pi) = \mathbb{E}_\pi[G_0], \qquad \text{accuracy} = \mathbb{E}[\mathbf{1}\{\hat y = y\}]

— and none of them can be computed exactly, because the underlying distribution is the world. Everything is estimated by sample averages, which is why the next lesson — on what sample averages do and how fast — is arguably the load-bearing wall of the entire practice: it prices every training batch, every test set, and every Monte Carlo rollout you will ever run.

import numpy as np
rng = np.random.default_rng(0)

# linearity needs no independence; variance addition does
x = rng.normal(2.0, 1.0, 200_000)
y = 0.8 * x + rng.normal(0, 0.5, 200_000)          # correlated with x
print(np.mean(x + y), np.mean(x) + np.mean(y))     # equal (linearity)
print(np.var(x + y), np.var(x) + np.var(y))        # NOT equal (covariance ≠ 0)
print(np.var(x + y), np.var(x) + np.var(y) + 2 * np.cov(x, y)[0, 1])  # fixed

Exercises

Work these before the next lesson

  1. Prove Var[X]=E[X2](EX)2\operatorname{Var}[X] = \mathbb{E}[X^2] - (\mathbb{E}X)^2 and linearity of expectation for the discrete case. Then derive Bernoulli’s variance p(1p)p(1-p) and explain why it peaks at p=0.5p = 0.5 in one intuitive sentence.
    Solution

    Worked solutions are part of Premiumunlock all of them for £5/month →

  2. 5 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • J. Blitzstein & J. Hwang, Introduction to Probability, 2nd ed. — the best story-first treatment; free lectures (Stat 110) accompany it.
  • L. Wasserman, All of Statistics, ch. 1–3 — the compressed graduate version of this module.
  • D. MacKay, Information Theory, Inference, and Learning Algorithms, ch. 2 — probability as the language of inference, free online.