C. Probability, Concentration & Information

Random variables, Gaussians, high-probability guarantees, martingales, KL divergence and risk measures

Before you start

This primer assumes:

Study route — Rebuild probability from weighted averages

No previous probability course is needed. Start with events and finite probability tables, then conditioning and transitions. Gaussian formulas use the matrix review in Primer A; the probability language is introduced here. Treat the measure-theory background and longer proofs as a second pass after you can do the Easy and Medium problems.

Begin with the three readiness checks. If a check is difficult, use its review link and worked answer, then try again without looking. After each section, try its Easy problem, use the separate hint if needed, and continue to Medium once you can explain the steps. Hard problems combine ideas or expose a common mistake. Keep the answers closed on your first attempt.

The original cumulative exercises combine sections after this guided practice. Finish a study session by explaining one worked solution in your own words, then changing a number and solving it again.

Readiness checks — a short prerequisite refresher

These checks are diagnostic, with the needed calculation explained in each answer. A gap tells you where to review; it is not a reason to skip this primer.

Exercise C.R1 — Readiness: Translate a complement

An event $A$ has probability $0.15$. What is the probability that it does not occur? If $A$ means a constraint is violated, which event describes no violation?

Review if needed: sets and complements.

Show hint
An event and its complement partition all outcomes.
Show worked solution

The complement $A^c$ contains exactly the outcomes outside $A$. Since the probabilities of these disjoint events add to $1$, $\mathbb P(A^c)=1-0.15=0.85$. If $A$ means violation, $A^c$ means no violation. This statement concerns the specified event; a guarantee across many times requires defining an event for the whole trajectory.

Exercise C.R2 — Readiness: Build a weighted average

A quantity is $2$ in one quarter of cases and $6$ in the other three quarters. Find the average. Why is simply adding $2+6$ incorrect?

Review if needed: sums and weights.

Show hint
Give each value a weight equal to its fraction of cases.
Show worked solution

In four representative cases the values are $2,6,6,6$, whose average is $(2+6+6+6)/4=5$. Equivalently, $2(1/4)+6(3/4)=5$. Adding $2+6$ ignores both frequencies and the division by the number of cases. An expectation is this same weighted-average idea applied to a probability law.

Exercise C.R3 — Readiness: Check an outer product

For column vector $v=(1,2)^\top$, compute $vv^\top$ and show that its quadratic form is nonnegative for every vector $w=(w_1,w_2)^\top$.

Review if needed: outer products and PSD matrices.

Show hint
The entry in row $i$, column $j$ is $v_iv_j$. Use $w^\top vv^\top w=(v^\top w)^2$.
Show worked solution

The product is $vv^\top=\begin{bmatrix}1&2\\2&4\end{bmatrix}$. For any $w$, its quadratic form is $(w_1+2w_2)^2\ge0$, so this matrix is positive semidefinite. It is not positive definite: nonzero $w=(-2,1)^\top$ gives zero. Covariance matrices are averages of such outer products, which explains their nonnegative quadratic forms.

Book contents · Apply this chapter to a real decision · Glossary

Contents
1. Random Variables, Expectation & Variance 2. Conditional Probability, Bayes & Conditional Expectation 3. Markov Chains, Stationary Distributions & Monte Carlo 4. The Multivariate Gaussian & Gaussian Conditioning 5. Concentration: Markov, Chebyshev, Hoeffding & Sub-Gaussian Noise 6. “With Probability at Least $1-\delta$”: Union Bounds & Confidence Statements 7. Adaptive Data, Filtrations & Martingales 8. Entropy, KL Divergence, Total Variation & Mutual Information 9. Quantiles, Value-at-Risk & CVaR 10. Binomial Tails, Hypothesis Tests & Exchangeability Interactive: Concentration & Gaussian Conditioning Application lab & chapter review Exercises Further Reading Flashcards

Many guarantees in the modules are statements about a random experiment: a noisy measurement, one episode of a stochastic closed loop, a batch of training data, the random seed of a verifier. Others are deterministic and hold for every admissible state, disturbance or input, such as forward invariance or a verified network bound (Module 1 compares the types). To read a probabilistic guarantee you must be able to say what is random, which event is being measured and which average is taken. This primer builds that vocabulary from a first course in calculus and linear algebra, and then the tools the modules lean on: Gaussian conditioning (the engine of GP regression), concentration inequalities, union bounds, martingales for adaptively collected data, information measures, risk measures and distribution-free tests.

1. Random Variables, Expectation & Variance

Start here — Weighted averages and spread

Start with a finite table: a value $2$ occurring with probability $1/4$ contributes $2(1/4)=1/2$ to the mean. $\mathbb P(A)$ is a number assigned to an event $A$; $\mathbb E[X]$ averages a numerical random variable $X$. The first practice set rebuilds both operations before using covariance matrices.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review sets and events.

Definition — Probability space, event, random variable, law
A random experiment has a sample space $\Omega$ (all possible outcomes $\omega$), events $A\subseteq\Omega$ (the yes/no questions we may ask about the outcome) and a probability $\mathbb P$ assigning each event a number in $[0,1]$, with $\mathbb P(\Omega)=1$ and $\mathbb P(A_1\cup A_2\cup\cdots)=\sum_i\mathbb P(A_i)$ for disjoint events. Consequences: $\mathbb P(A^c)=1-\mathbb P(A)$ and $A\subseteq B\Rightarrow\mathbb P(A)\le\mathbb P(B)$.
A random variable is a number computed from the outcome, $X:\Omega\to\mathbb R$; a random vector takes values in $\mathbb R^n$; a random trajectory $\tau=(x_0,u_0,x_1,u_1,\dots)$ is a random sequence. The law (distribution) of $X$ is the map $B\mapsto\mathbb P(X\in B)$; $X\sim p$ reads "$X$ has law $p$".
Definition — Mass function, density, CDF, atom
  • Discrete: $p(x)=\mathbb P(X=x)$ with $\sum_xp(x)=1$. Examples: Bernoulli$(q)$ with $\mathbb P(X=1)=q$, $\mathbb P(X=0)=1-q$; the point mass $\delta_s$ with $\mathbb P(X=s)=1$, so an initial law $\mu=\delta_{s_1}$ means "always start in $s_1$".
  • Continuous with a density $p\ge0$: $\mathbb P(a\le X\le b)=\int_a^bp(x)\,dx$ and $\int p=1$; every single point then has probability $0$. Example: the uniform law $\mathcal U(a,b)$ with density $1/(b-a)$ on $[a,b]$. For a vector, $x_0\sim\mathcal U([-0.5,0.5]^2)$ means density $1$ on the square, i.e. two independent uniform coordinates. A density may exceed $1$ ($\mathcal U(0,0.5)$ has density $2$); only its integrals are probabilities.
  • The CDF $F_X(z)=\mathbb P(X\le z)$ is nondecreasing and right-continuous, rising from $0$ to $1$. A jump of height $q\gt0$ at $z$ is an atom: $\mathbb P(X=z)=q$. A mixed law has atoms and a density part.
0 1 z 0.5 1 atom: jump of 1/2 at z = 0 CDF of Z = max(X, 0)

Worked example (an excursion with an atom). Let $X\sim\mathcal U(-1,1)$ be the signed distance of the state beyond a constraint boundary (positive means violated) and $Z=\max(X,0)=X^+$ the excursion. Then $\mathbb P(Z=0)=\mathbb P(X\le0)=\tfrac12$: an atom at zero. For $0\le z\le1$, $F_Z(z)=\mathbb P(X\le z)=(1+z)/2$, so $F_Z$ jumps from $0$ to $\tfrac12$ at $z=0$ and then rises linearly to $1$ (figure). A nondegenerate Gaussian has no atoms and assigns positive probability to negative values; a degenerate Gaussian is a single point mass. Neither represents this mixed law.

Definition — Expectation, indicator, linearity
$\mathbb E[g(X)]=\sum_xg(x)p(x)$ (discrete) or $\int g(x)p(x)\,dx$ (density), defined when the same sum or integral of $|g|$ is finite ($g(X)$ is then integrable). Linearity: $\mathbb E[aX+bY+c]=a\,\mathbb E[X]+b\,\mathbb E[Y]+c$ for integrable random variables, dependent or not. The indicator $\mathbf 1_A$ of an event is $1$ if $A$ occurs and $0$ otherwise, so $\mathbb E[\mathbf 1_A]=\mathbb P(A)$: probabilities are expectations. The Heaviside step $H(v)=\mathbf 1\{v\gt0\}$ is the indicator of a positive argument (its value at $v=0$ is a convention), and $\mathbf 1\{f(z)\ge0\}$ is the safety indicator of a query $z$.
Subscripts name what is averaged: $\mathbb E_{x\sim\mu}[G(x)]$ averages $G$ over initial states drawn from $\mu$; $\mathbb E_{\tau\sim\pi}$ averages over trajectories generated jointly by the initial law, the policy $\pi$ and the transition law.

Worked example. For the excursion above, $\mathbb E[Z]=0\cdot\tfrac12+\int_0^1z\cdot\tfrac12\,dz=\tfrac14$: the atom contributes nothing, the density $\tfrac12$ on $(0,1]$ the rest. Counting violations: with $c_t=\mathbf 1\{x_t\gt1\}$ and $N=\sum_{t=1}^Tc_t$, linearity gives $\mathbb E[N]=\sum_t\mathbb P(x_t\gt1)$ even though the states of one episode are dependent. If each of $T=50$ steps violates with probability $0.004$, then $\mathbb E[N]=0.2$. Since $N$ is a nonnegative integer, $\mathbf 1\{N\ge1\}\le N$, hence $\mathbb P(\text{at least one violation})\le\mathbb E[N]=0.2$ whatever the dependence. A Boolean test becomes a signed monitor by subtracting one half: $\mathbf 1\{\text{test passed}\}-\tfrac12\in\{-\tfrac12,+\tfrac12\}$ is positive exactly when the test passes.

Definition — Variance, covariance, covariance matrix
Assume finite second moments for the variance and covariance formulas below. $\operatorname{Var}(X)=\mathbb E[(X-\mathbb EX)^2]=\mathbb E[X^2]-(\mathbb EX)^2$; the standard deviation $\sqrt{\operatorname{Var}X}$ has the units of $X$ (noise variance $0.01$ means standard deviation $0.1$), and $\operatorname{Var}(aX+b)=a^2\operatorname{Var}X$. $\operatorname{Cov}(X,Y)=\mathbb E[(X-\mathbb EX)(Y-\mathbb EY)]$. For a random vector $X\in\mathbb R^n$ with mean $m$,
$$\Sigma=\operatorname{Cov}(X)=\mathbb E\big[(X-m)(X-m)^\top\big],\qquad \Sigma_{ij}=\operatorname{Cov}(X_i,X_j),\qquad \operatorname{Cov}(AX+b)=A\Sigma A^\top .$$
Isotropic noise has $\Sigma=\sigma^2I$: uncorrelated coordinates with the same variance $\sigma^2$ in every direction. The correlation of $X,Y$ with standard deviations $\sigma_X,\sigma_Y\gt0$ is $\rho=\operatorname{Cov}(X,Y)/(\sigma_X\sigma_Y)$, the covariance of the standardised variables. It lies in $[-1,1]$ because $0\le\operatorname{Var}\big(\tfrac X{\sigma_X}\pm\tfrac Y{\sigma_Y}\big)=2(1\pm\rho)$, and $\rho=\pm1$ exactly when $Y$ is almost surely an affine function of $X$ (slope of sign $\pm$). In these terms the vector $(X,Y)$ has covariance matrix $\begin{bmatrix}\sigma_X^2&\rho\sigma_X\sigma_Y\\\rho\sigma_X\sigma_Y&\sigma_Y^2\end{bmatrix}$.
Fact — Covariance matrices are positive semidefinite
For every $v\in\mathbb R^n$, $v^\top\Sigma v=\mathbb E\big[(v^\top(X-m))^2\big]=\operatorname{Var}(v^\top X)\ge0$, so $\Sigma\succeq0$ (Primer A). It is positive definite, hence invertible, iff no nonzero combination $v^\top X$ is almost surely constant.

Worked example (ensemble spread). Two ensemble members predict means $\mu_1=(1,0)$ and $\mu_2=(-1,0)$. Their average is $\bar\mu=(0,0)$ and the outer-product estimate $\hat\Sigma=\tfrac12\sum_e(\mu_e-\bar\mu)(\mu_e-\bar\mu)^\top=\begin{bmatrix}1&0\\0&0\end{bmatrix}$ is PSD but singular: the members disagree only along the first axis. With $E$ members in $\mathbb R^n$ this estimate has rank at most $E-1$, so it is singular whenever $E\le n$ and must not be inverted. A fusion rule such as $\big(\tfrac1E\sum_e\Sigma_e^{-1}\big)^{-1}$ needs every member covariance $\Sigma_e$ to be positive definite.

Definition — Independence and i.i.d.
$X$ and $Y$ are independent if $\mathbb P(X\in A,\,Y\in B)=\mathbb P(X\in A)\,\mathbb P(Y\in B)$ for all sets $A,B$ (for densities: $p(x,y)=p_X(x)p_Y(y)$). Then $\mathbb E[g(X)h(Y)]=\mathbb E[g(X)]\,\mathbb E[h(Y)]$, $\operatorname{Cov}(X,Y)=0$ and $\operatorname{Var}(X+Y)=\operatorname{Var}X+\operatorname{Var}Y$. A sequence is i.i.d. (independent, identically distributed) if its members are mutually independent with a common law, e.g. measurement noise in $y_i=f(x_i)+\varepsilon_i$ with $\varepsilon_i\sim\mathcal N(0,\sigma^2)$ i.i.d.; in the frequentist reading the unknown $f$ itself is not random (Section 6).
Pitfall — three different "independences" and a hidden bias
(1) Uncorrelated is not independent: $X$ uniform on $\{-1,0,1\}$ and $Y=X^2$ have $\operatorname{Cov}(X,Y)=\mathbb E[X^3]-\mathbb E[X]\,\mathbb E[X^2]=0$, yet $Y$ is a function of $X$. (2) Across episodes vs within an episode: in $x_{t+1}=x_t+u_t+w_t$ under a fixed controller, with independently drawn initial states and independent noise sequences, different episodes are independent (independence can fail if the controller is updated from earlier episodes or all episodes share one random parameter), while states within one episode can share past noise and be dependent; this is not automatic, since the fixed controller $u_t=-x_t$ gives $x_{t+1}=w_t$, which are independent for i.i.d. noise. (3) Bounded is not centred: $\varepsilon\sim\mathcal U(0,\sigma)$ satisfies $|\varepsilon|\le\sigma$ almost surely but has mean $\sigma/2$, a bias that no amount of averaging removes.

Almost surely, support and essential supremum

Definition — Almost surely, support, essential supremum
A statement holds almost surely (a.s., with probability one) if the outcomes where it fails form an event of probability $0$. Such outcomes may still exist: $X\sim\mathcal U(0,1)$ satisfies $X\ne\tfrac12$ a.s., yet $\tfrac12$ is a possible value. "$|\varepsilon|\le\sigma$ a.s." tolerates probability-zero exceptions; "for every admissible realisation" (robust) tolerates none.
The support of a law $\mu$ on $\mathbb R^n$ is the set of points $x$ such that every open ball around $x$ has positive probability (the smallest closed set of probability one): $\operatorname{supp}\mathcal U(a,b)=[a,b]$, $\operatorname{supp}\delta_s=\{s\}$, $\operatorname{supp}\mathcal N(0,\sigma^2)=\mathbb R$ for $\sigma\gt0$ (for $\sigma=0$ the support is $\{0\}$).
The essential supremum $\operatorname{ess\,sup}Z=\inf\{c:\ \mathbb P(Z\le c)=1\}$ is the smallest almost-sure upper bound.

Worked example. For the excursion, $\operatorname{ess\,sup}Z=1$. Now let a disturbance $W\sim\mathcal U(0,1)$ enter through $g(W)$ with $g=0$ except $g(0.5)=10$. The worst case over all disturbances is $\sup_wg(w)=10$, but $\mathbb P(g(W)=0)=1$, so $\operatorname{ess\,sup}g(W)=0$: an almost-sure analysis never sees the spike.

Fact — Two bridges between "on average", "almost surely" and "everywhere"
(a) If $Z\ge0$ and $\mathbb E[Z]=0$, then $Z=0$ almost surely. Proof. $\tfrac1k\mathbf 1\{Z\ge\tfrac1k\}\le Z$, so $\mathbb P(Z\ge\tfrac1k)\le k\,\mathbb E[Z]=0$ for every $k$, and $\{Z\gt0\}=\bigcup_k\{Z\ge\tfrac1k\}$ is a countable union of probability-zero events. $\square$ It does not give $Z(x)=0$ at every point: with $x\sim\mathcal U(0,1)$ and $Z(x)=5\cdot\mathbf 1\{x=0.3\}$, $\mathbb E[Z]=0$ although $Z(0.3)=5$.
(b) If $g$ is continuous and $g(X)\le0$ almost surely, then $g\le0$ on all of $\operatorname{supp}(X)$. Proof. If $g(x_0)\gt0$ at some $x_0$ in the support, continuity gives a ball around $x_0$ on which $g\gt0$; that ball has positive probability, a contradiction. $\square$ Full support plus continuity is what upgrades an almost-sure guarantee to a robust one.
Going deeper — the measure-theory words the modules use

Measurable. The events form a $\sigma$-algebra (closed under complements and countable unions); a measurable function is one for which $\{X\in B\}$ is an event, i.e. a legitimate random variable. Everything built from continuous maps, indicators of boxes, sums, products, limits, max and min is measurable; "measurable feedback controller" or "measurable transition kernel" only asks that the probabilities we write down exist.

Measures and integrals. A measure assigns sizes to sets and is countably additive: Lebesgue measure is length, area or volume; counting measure counts points; a probability measure has total mass $1$. The integral $\int g\,d\nu$ is the ordinary integral for Lebesgue measure and the sum $\sum_xg(x)$ for counting measure. A density $p$ with respect to a reference measure $\nu$ means $\mathbb P(X\in A)=\int_Ap\,d\nu$: a mass function is a density with respect to counting measure. That is why one formula for expectations, entropy or KL covers sums and integrals at once. Mixed laws (atoms plus a density) and some policies have no density with respect to either; then statements are made for events directly, e.g. total variation as a supremum over events (Section 8).

Null sets and "almost everywhere". A null set has measure zero; a property holds almost everywhere (a.e.) if it fails only on a null set of the reference measure, usually Lebesgue. Points, lines, smooth curves in the plane and hyperplanes have zero volume, so a ReLU network, whose kinks lie on finitely many pieces of hyperplanes, is differentiable a.e.; a full-dimensional region contains a ball and has positive volume. A probability-zero exception never licenses a statement "for every parameter".

Averages of many samples

Theorem — Law of large numbers (statement)
If $X_1,X_2,\dots$ are i.i.d. with $\mathbb E|X_1|\lt\infty$ and mean $m$, the sample mean $\bar X_N=\tfrac1N\sum_{i=1}^NX_i$ converges to $m$ almost surely (strong law). If also $\operatorname{Var}X_1\lt\infty$, the weak law $\mathbb P(|\bar X_N-m|\gt t)\to0$ for every $t\gt0$ follows from Chebyshev's inequality (Section 5).

Keep two objects apart: the population quantity $\mathbb E[X]$ is a fixed number, the sample average $\bar X_N$ is random and changes with the data. The empirical distribution of $N$ samples puts mass $1/N$ on each observed value (mass $1/200$ on each of $200$ simulated episodes); its mean is the sample mean. How far $\bar X_N$ typically is from $\mathbb E[X]$ at finite $N$ is the subject of Section 3 (standard errors) and Section 5 (guaranteed bounds).

Fact — Exchanging sums, limits and expectations
Tonelli: if $X_t\ge0$, then $\mathbb E\big[\sum_tX_t\big]=\sum_t\mathbb E[X_t]$ (both may be $+\infty$). Fubini: for signed terms the same holds when $\sum_t\mathbb E|X_t|\lt\infty$. Dominated convergence: if $X_n\to X$ almost surely and $|X_n|\le Y$ with $\mathbb E[Y]\lt\infty$ (bounded convergence: $|X_n|\le C$), then $\mathbb E[X_n]\to\mathbb E[X]$.
Example. Rewards with $|r_t|\le r_{\max}$ and discount $0\le\gamma\lt1$ give $\sum_t\gamma^t\mathbb E|r_t|\le r_{\max}/(1-\gamma)$, so $\mathbb E\big[\sum_t\gamma^tr_t\big]=\sum_t\gamma^t\mathbb E[r_t]$. Likewise, the difference quotients $\big[(Z-\nu-h)^+-(Z-\nu)^+\big]/h$ are bounded by $1$ and tend to $-\mathbf 1\{Z\gt\nu\}$ as $h\downarrow0$ and to $-\mathbf 1\{Z\ge\nu\}$ as $h\uparrow0$, so bounded convergence gives the right and left derivatives $-\mathbb P(Z\gt\nu)$ and $-\mathbb P(Z\ge\nu)$ of $\nu\mapsto\mathbb E[(Z-\nu)^+]$. They agree, and the ordinary derivative exists, exactly when $\mathbb P(Z=\nu)=0$ (the CVaR derivation in Module 1; atoms in Section 9).
Pitfall — a limit that escapes the expectation
With $U\sim\mathcal U(0,1)$ let $X_n=n\,\mathbf 1\{U\lt1/n\}$. For every outcome with $U\gt0$ (probability one), $X_n=0$ once $n\gt1/U$, so $X_n\to0$; yet $\mathbb E[X_n]=n\cdot\tfrac1n=1$ for all $n$. There is no integrable $Y$ dominating all $X_n$, and the exchange fails.
Where this is used — events, expectations and laws
Safety as the probability of an event versus an expected cost, with trajectories as random objects: Module 1. $\mathbb E_{\tau\sim\pi}$ in the performance-difference lemma: Module 9. $\mathbb E_{x\sim\mu}[G(x,u)]$ and averaged versus pointwise constraints: Module 7. Point-mass initial laws $\mu=\delta_{s_1}$ and indicator costs: Module 8. The Heaviside step and the safety indicator $\mathbf 1\{f(z)\ge0\}$: Module 4. Indicators $\mathbf 1(t_i=T)$ turned into signed monitors: Module 10. Uniform initial states $x_0\sim\mathcal U(-0.5,0.5)$: Module 14. Densities integrated over events and i.i.d. samples: Module 15.
Where this is used — noise models, covariances, almost-sure language
i.i.d. observation noise $y_i=f(x_i)+\varepsilon_i$: Module 3, Module 6. Noise "a.s. bounded by $\sigma$", i.i.d. Gaussian noise of variance $0.01$, and bounded noise with a bias: Module 5. Ensemble means and covariances, PSD versus invertible: Module 7. An atom at zero: Module 7; "$\mu$-almost every initial state" from $\rho\ge0$ and a zero average: Module 7. Almost-sure safety, support and $\operatorname{ess\,sup}$: Module 1. Two hundred independent episodes and their empirical distribution: Module 1. Exchanging sums and expectations: Module 8. "Differentiable almost everywhere": Module 12, Module 13.

Practice — Weighted averages and spread

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S1 — Easy: Read a probability table

A random cost $X$ is $0$, $2$, or $4$ with probabilities $1/2$, $1/4$, and $1/4$. Check that this is a probability law. Find $\mathbb P(X\ge2)$ and $\mathbb E[X]$.

Review if needed: this section and sets and events.

Show hint
Probabilities add over distinct outcomes. For the mean, multiply each value by its probability before adding.
Show worked solution
  1. The probabilities are nonnegative and $1/2+1/4+1/4=1$, so they form a valid law.
  2. The event $X\ge2$ contains the outcomes $2$ and $4$. Therefore $\mathbb P(X\ge2)=1/4+1/4=1/2$.
  3. Weight all values, including zero: $\mathbb E[X]=0(1/2)+2(1/4)+4(1/4)=3/2$. A mean need not be one of the possible outcomes.
Exercise C.S2 — Medium: Variance is an average of squared distances

For the same law, compute $\mathbb E[X^2]$, $\operatorname{Var}(X)$ and the standard deviation. If $Y=3X+1$, find its mean and variance.

Review if needed: this section and sets and events.

Show hint
Square the values before averaging. A shift changes the mean but leaves distances from the mean unchanged.
Show worked solution
  1. $\mathbb E[X^2]=0^2(1/2)+2^2(1/4)+4^2(1/4)=5$.
  2. Subtract the square of the mean: $\operatorname{Var}(X)=5-(3/2)^2=11/4=2.75$. The standard deviation is $\sqrt{11}/2\approx1.658$.
  3. Linearity gives $\mathbb E[Y]=3(3/2)+1=11/2$. Since $Y-\mathbb E[Y]=3(X-\mathbb E[X])$, its squared distances are nine times larger: $\operatorname{Var}(Y)=9(11/4)=99/4$.
Exercise C.S3 — Hard: A covariance calculation that detects dependence

Let $X$ be uniform on $\{-1,0,1\}$ and set $Y=X^2$. Compute the covariance matrix of $(X,Y)$. Are $X$ and $Y$ independent?

Review if needed: this section and sets and events.

Show hint
Compute $\mathbb E[X]$, $\mathbb E[Y]$, $\mathbb E[XY]$ and both variances. Independence is stronger than covariance zero.
Show worked solution
  1. Symmetry gives $\mathbb E[X]=0$, while $\mathbb E[Y]=2/3$ and $\mathbb E[XY]=\mathbb E[X^3]=0$. Thus $\operatorname{Cov}(X,Y)=0$.
  2. $\operatorname{Var}(X)=2/3$. Since $Y^2=Y$, $\operatorname{Var}(Y)=2/3-(2/3)^2=2/9$. The covariance matrix is $\operatorname{diag}(2/3,2/9)$.
  3. They are dependent: $Y=0$ forces $X=0$, so $\mathbb P(X=0\mid Y=0)=1$, whereas $\mathbb P(X=0)=1/3$. Zero covariance did not remove this information.

2. Conditional Probability, Bayes & Conditional Expectation

Start here — Condition on the information you actually have

Conditioning means keeping only outcomes consistent with new information and rescaling their weights. If an event leaves three equally likely outcomes, each remaining outcome has conditional probability $1/3$. Distinguish the information after the vertical bar from the question before it.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review weighted expectations.

Conditioning is updating on information. Once we know that an event $B$ happened, only outcomes inside $B$ remain possible, and their probabilities are rescaled so that they again sum to one.

Definition — Conditional probability, total probability, Bayes' rule
For $\mathbb P(B)\gt0$: $\mathbb P(A\mid B)=\mathbb P(A\cap B)/\mathbb P(B)$, equivalently the product rule $\mathbb P(A\cap B)=\mathbb P(A\mid B)\,\mathbb P(B)$. For a partition $B_1,\dots,B_k$ of $\Omega$ (disjoint events covering everything), the law of total probability and Bayes' rule read
$$\mathbb P(A)=\sum_{j}\mathbb P(A\mid B_j)\,\mathbb P(B_j),\qquad \mathbb P(B_i\mid A)=\frac{\mathbb P(A\mid B_i)\,\mathbb P(B_i)}{\sum_j\mathbb P(A\mid B_j)\,\mathbb P(B_j)} .$$
With a joint density: $p(x\mid y)=p(x,y)/p(y)$ and $p(y)=\int p(y\mid x)\,p(x)\,dx$.

Worked example (an alarm and the base rate). A fault occurs in $1\%$ of runs; a monitor detects a fault with probability $0.95$ and raises a false alarm on a healthy run with probability $0.05$. Given an alarm,

$$\mathbb P(\text{fault}\mid\text{alarm})=\frac{0.95\cdot0.01}{0.95\cdot0.01+0.05\cdot0.99}=\frac{0.0095}{0.059}\approx0.161 .$$

About five out of six alarms are false: a small false-alarm rate is swamped by the many healthy runs. The false-alarm rate $\mathbb P(\text{alarm}\mid\text{healthy})$ of a test (Section 10) and the posterior $\mathbb P(\text{fault}\mid\text{alarm})$ are different numbers, and the second needs a prior.

Transition kernels and trajectory laws. A transition kernel $P(s'\mid s,a)$ is a family of conditional laws, one distribution of the next state for each state-action pair; a stochastic policy $\pi(a\mid s)$ is a conditional law of the action. The product rule chains them into the law of a trajectory,

$$\mathbb P(s_0,a_0,s_1,a_1,s_2)=\mu(s_0)\,\pi(a_0\mid s_0)\,P(s_1\mid s_0,a_0)\,\pi(a_1\mid s_1)\,P(s_2\mid s_1,a_1),$$

and total probability gives marginals, $\mathbb P(s_1=s')=\sum_{s,a}\mu(s)\,\pi(a\mid s)\,P(s'\mid s,a)$. For instance, from $\mu=\delta_{s_0}$ with two actions of probability $0.5$ each that reach an unsafe state with probabilities $0.2$ and $0.6$, $\mathbb P(s_1\text{ unsafe})=0.5\cdot0.2+0.5\cdot0.6=0.4$. Decorations such as $\mathbb P^\pi_\mu$ or $\mathbb E_{\tau\sim\pi}$ record which $\mu$, $\pi$ and $P$ generate the trajectory; change any of them and every probability changes.

Definition — Conditional expectation and the tower rule
$\mathbb E[X\mid Y=y]=\sum_xx\,p(x\mid y)$ (or $\int x\,p(x\mid y)\,dx$) is a number for each $y$; inserting the random $Y$ gives the random variable $\mathbb E[X\mid Y]$, the predictor of $X$ from $Y$ that minimises mean squared error when $\mathbb E[X^2]\lt\infty$. For an event with $\mathbb P(A)\gt0$, $\mathbb E[X\mid A]=\mathbb E[X\mathbf 1_A]/\mathbb P(A)$, i.e. $\mathbb E[X\mathbf 1_A]=\mathbb P(A)\,\mathbb E[X\mid A]$. Two rules do most of the work:
$$\underbrace{\mathbb E\big[\mathbb E[X\mid Y]\big]=\mathbb E[X]}_{\text{tower rule}},\qquad \underbrace{\mathbb E[g(Y)\,X\mid Y]=g(Y)\,\mathbb E[X\mid Y]}_{\text{take out what is known}} .$$
Proof of the tower rule (discrete): $\sum_yp(y)\sum_xx\,p(x\mid y)=\sum_{x,y}x\,p(x,y)=\mathbb E[X]$. $\square$

Worked example (averaging over a policy). In a state $s$, action $a_1$ has expected cost $\mathbb E[X\mid a_1]=2$ and action $a_2$ has $\mathbb E[X\mid a_2]=10$. Under $\pi=(0.7,0.3)$ the tower rule gives $\mathbb E[X]=0.7\cdot2+0.3\cdot10=4.4$. Under another policy $\pi'=(0.9,0.1)$ the conditional expectations, a property of the environment, are unchanged and only the weights move: $0.9\cdot2+0.1\cdot10=2.8$. The performance-difference lemma averages the advantage of $\pi$ over the actions of $\pi'$ in exactly this way.

Theorem — Law of total variance
$\operatorname{Var}(X)=\mathbb E\big[\operatorname{Var}(X\mid Y)\big]+\operatorname{Var}\big(\mathbb E[X\mid Y]\big)$: the average spread within groups plus the spread of the group means. Proof. With $\bar X=\mathbb E[X\mid Y]$, the tower rule gives $\mathbb E[X^2]=\mathbb E\big[\mathbb E[X^2\mid Y]\big]=\mathbb E\big[\operatorname{Var}(X\mid Y)+\bar X^2\big]$ and $\mathbb E[X]=\mathbb E[\bar X]$; subtract $(\mathbb E\bar X)^2$ from both sides. $\square$ For vectors, $\operatorname{Cov}(X)=\mathbb E[\operatorname{Cov}(X\mid Y)]+\operatorname{Cov}(\mathbb E[X\mid Y])$.
Definition — Mixture distribution
First draw a label $L$ with $\mathbb P(L=j)=w_j$, then draw $X$ from the component law $p_j$ (mean $m_j$, variance $\sigma_j^2$). Then $X$ has density $p(x)=\sum_jw_jp_j(x)$, mean $\bar m=\sum_jw_jm_j$ and, by total variance, $\operatorname{Var}X=\sum_jw_j\sigma_j^2+\sum_jw_j(m_j-\bar m)^2$.

Worked example (small and large errors). Residuals that are $\mathcal N(0,0.5^2)$ with probability $0.8$ and $\mathcal N(0,3^2)$ with probability $0.2$ (the "80% small, 20% large" option of the Module 15 explorer) have variance $0.8\cdot0.25+0.2\cdot9=2$. Their tail is nothing like that of $\mathcal N(0,2)$: $\mathbb P(|E|\gt5)=0.8\cdot\mathbb P(|Z|\gt10)+0.2\cdot\mathbb P(|Z|\gt\tfrac53)\approx0.019$, against $0.0004$ for the Gaussian with the same variance, while near zero the mixture is more concentrated ($\mathbb P(|E|\gt1)\approx0.18$ against $0.48$). An ensemble of $E$ Gaussian predictions is an equal-weight mixture: its covariance is the average member covariance (aleatoric part) plus the covariance of the member means (epistemic part, the $\hat\Sigma$ of Section 1).

Definition — Likelihood, prior, posterior, MAP, marginal likelihood
A statistical model $p(\mathcal D\mid\theta)$ gives the probability (density) of data $\mathcal D$ for each parameter $\theta$. Read as a function of $\theta$ with the data fixed, it is the likelihood $L(\theta)=p(\mathcal D\mid\theta)$, which is not a density in $\theta$. With a prior $p(\theta)$, Bayes' rule gives the posterior
$$p(\theta\mid\mathcal D)=\frac{p(\mathcal D\mid\theta)\,p(\theta)}{p(\mathcal D)},\qquad p(\mathcal D)=\int p(\mathcal D\mid\theta)\,p(\theta)\,d\theta .$$
The maximum-likelihood (ML) estimate maximises $L(\theta)$; the MAP estimate maximises $L(\theta)\,p(\theta)$, i.e. minimises $-\log p(\mathcal D\mid\theta)-\log p(\theta)$: data fit plus regulariser. The normaliser $p(\mathcal D)$ is the marginal likelihood (evidence), the probability of the data with the latent quantity integrated out. When the prior has its own parameters $\vartheta$ (a GP length-scale), $p(\mathcal D\mid\vartheta)=\int p(\mathcal D\mid f)\,p(f\mid\vartheta)\,df$ is maximised over $\vartheta$ (type-II maximum likelihood, empirical Bayes), or $\vartheta$ gets a hyperprior and is integrated out too.

Worked example (ten runs, no failure). Let $\theta$ be the failure probability of a controller, with a uniform prior on $[0,1]$. Ten independent runs show no failure, so $L(\theta)=(1-\theta)^{10}$ and the posterior density is $11(1-\theta)^{10}$ (a Beta$(1,11)$ law, Section 10). The ML estimate is $\hat\theta=0$, "it never fails", yet the posterior mean is $1/12\approx0.083$ and $\mathbb P(\theta\gt0.2\mid\mathcal D)=\int_{0.2}^111(1-\theta)^{10}d\theta=0.8^{11}\approx0.086$. For Gaussian models the posterior and the marginal likelihood are available in closed form (Section 4); non-Gaussian likelihoods, such as binary safe/unsafe labels or censored measurements, need approximations (Laplace, expectation propagation, sampling). Preference data give another likelihood: in the Bradley–Terry model an item with score $r_a$ beats one with score $r_b$ with probability $1/(1+e^{-(r_a-r_b)})$, and the negative log-likelihood of an observed preference is the logistic loss $\log(1+e^{-(r_a-r_b)})$.

Definition — Conditioning on a region (truncation)
If $X$ has density $p$ and $c=\mathbb P(X\in A)\gt0$, then $X$ given $X\in A$ has density $p(x)\,\mathbf 1_A(x)/c$: cut the density to $A$ and renormalise. A truncated Gaussian policy is $\mathcal N(m,s^2)$ conditioned on the admissible action interval; a posterior "truncated to its credible region of mass $c$" is the posterior conditioned on a set $A$ of posterior probability $c$.

Worked example (nested probabilities). A controller is stable with probability at least $1-\epsilon=0.95$ under a posterior truncated to a region $A$ of mass $c=0.99$. Under the untruncated posterior, $\mathbb P(\text{stable})\ge\mathbb P(\text{stable}\cap A)=\mathbb P(\text{stable}\mid A)\,\mathbb P(A)\ge0.95\cdot0.99=0.9405$. The same product rule composes a hyperparameter statement with a function statement: if the true hyperparameter lies in a box with probability at least $1-\delta_1$ and, given that, a confidence band holds with probability at least $1-\delta_2$, both hold with probability at least $(1-\delta_1)(1-\delta_2)\ge1-\delta_1-\delta_2$. If the result is afterwards validated on random test samples, the validation confidence is a third, frequentist probability over those samples (Section 6); keep it apart from posterior mass. The tower rule also explains conformal coverage (Section 10): conditional on the calibration data the coverage is a random variable $C$, and its average $\mathbb E[C]$ is the marginal coverage probability.

Pitfall — the model is not the world
A posterior probability is computed inside the model: it is only as good as the prior and the likelihood. GP regression uses a Gaussian likelihood with variance $\lambda$ that need not be the actual noise law; the frequentist bounds of Module 3 keep the same formulas but treat $\lambda$ as a regulariser. A Gaussian fitted to the iterates of an optimiser is at best an approximate posterior. Also keep $\mathbb E[X\mid A]$ and $\mathbb E[X\mathbf 1_A]$ apart: they differ by the factor $\mathbb P(A)$.
Where this is used
Priors over $f$ and posterior bands: Module 1; $\mathbb E[Z\mid Z\ge\nu^\ast]$ and $\mathbb E[Z\mathbf 1_A]=\mathbb P(A)\mathbb E[Z\mid A]$ in the CVaR derivation: Module 1. Hyperpriors and composing parameter-box and function coverage: Module 3. Marginal likelihood, ML-II and MAP: Module 3, Module 4, Module 5. Truncated Gaussian policies $\pi(\cdot\mid s)$: Module 6. Ensembles as mixtures: Module 7. Transition kernels, initial laws and total probability: Module 8; Bradley–Terry likelihoods: Module 8. The tower property: Module 9. Fitted-Gaussian approximate posteriors: Module 9. Parameter posteriors $p(\theta\mid\mathcal D)$: Module 10. Credible-region truncation and nested probabilities: Module 11. Conditioning on the calibration set, total variance and the 80/20 mixture: Module 15, Module 15 explorer.

Practice — Condition on the information you actually have

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S4 — Easy: Restrict and renormalise

Roll a fair six-sided die. Let $A$ mean an even result and $B$ mean a result greater than $3$. Find $\mathbb P(A)$, $\mathbb P(B)$ and $\mathbb P(A\mid B)$.

Review if needed: this section and weighted expectations.

Show hint
Inside $B$, the remaining equally likely results are $4,5,6$.
Show worked solution
  1. $A=\{2,4,6\}$ and $B=\{4,5,6\}$ each have probability $3/6=1/2$.
  2. The intersection is $A\cap B=\{4,6\}$, of probability $2/6$.
  3. Divide by the probability of the information: $\mathbb P(A\mid B)=(2/6)/(3/6)=2/3$. Conditioning changed the denominator because only three results remain possible.
Exercise C.S5 — Medium: Bayes by counting imaginary runs

A fault occurs in $10\%$ of runs. An alarm fires on $80\%$ of faulty runs and $20\%$ of healthy runs. Find the alarm probability and the fault probability after an alarm.

Review if needed: this section and weighted expectations.

Show hint
Imagine $1000$ runs. Separate true alarms from false alarms before dividing.
Show worked solution
  1. Of $1000$ hypothetical runs, $100$ are faulty and $900$ healthy. They produce $80$ true alarms and $180$ false alarms.
  2. Total probability therefore gives $\mathbb P(\text{alarm})=0.8(0.1)+0.2(0.9)=0.26$.
  3. Among the $260$ alarms, only $80$ indicate faults. Bayes gives $\mathbb P(\text{fault}\mid\text{alarm})=80/260=4/13\approx0.3077$. The detector's $0.8$ sensitivity answers the reversed conditional question.
Exercise C.S6 — Hard: Separate noise from disagreement

Choose a model label $L\in\{1,2\}$ with equal probabilities. Conditional on $L=1$, $X$ has mean $0$ and variance $1$; conditional on $L=2$, it has mean $4$ and variance $1$. Find the unconditional mean and variance without assuming either conditional law is Gaussian.

Review if needed: this section and weighted expectations.

Show hint
Total variance is average within-model variance plus variance of the model means.
Show worked solution
  1. The tower rule averages the conditional means: $\mathbb E[X]=(0+4)/2=2$.
  2. The within-model term is $\mathbb E[\operatorname{Var}(X\mid L)]=(1+1)/2=1$.
  3. The conditional mean is $0$ or $4$, so its variance is $[(0-2)^2+(4-2)^2]/2=4$. Add the terms: $\operatorname{Var}(X)=1+4=5$. Averaging only the two variances would miss model disagreement.

3. Markov Chains, Stationary Distributions & Monte Carlo

Start here — Transitions, long-run laws and Monte Carlo

A trajectory is one realised sequence; a distribution records how likely each state is across repeated sequences. A row distribution $(1,0)$ means starting in the first state for sure. Multiplying it by a transition matrix gives the law one step later, not a single sampled next state.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review matrix-vector multiplication.

Definition — Markov chain, transition matrix, stationary distribution
A sequence $X_0,X_1,\dots$ on states $\{1,\dots,n\}$ is a Markov chain if the next state depends on the past only through the present: $\mathbb P(X_{t+1}=j\mid X_t=i,\text{past})=P_{ij}$. The transition matrix $P$ has nonnegative entries and rows summing to $1$. With the law of $X_t$ written as a row vector $p_t$, total probability gives $p_{t+1}=p_tP$, so $p_t=p_0P^t$. A stationary distribution is a probability vector with $\pi=\pi P$: a left eigenvector of $P$ for eigenvalue $1$.

Worked example. Let $P=\begin{bmatrix}0.9&0.1\\0.5&0.5\end{bmatrix}$ (state 1 nominal, state 2 degraded). $\pi=\pi P$ gives $\pi_2=0.1\pi_1+0.5\pi_2$, so $\pi_2=\pi_1/5$ and $\pi=(5/6,1/6)$. From state 2: $p_1=(0.5,0.5)$, $p_2=(0.7,0.3)$, $p_3=(0.78,0.22)$, $p_4=(0.812,0.188)$; the gap to $\pi$ shrinks by the factor $0.4$ per step, the second eigenvalue of $P$ ($\operatorname{tr}P-1$). The chain never stops jumping; only its distribution settles, and the approach phase is the transient. If every state can reach every other (irreducible), $\pi$ is unique and positive; if moreover the chain is aperiodic (the possible return times to a state have greatest common divisor $1$; for an irreducible chain one self-loop $P_{ii}\gt0$, as here, suffices), $p_t\to\pi$ from any start. Periodicity does block convergence: $P=\begin{bmatrix}0&1\\1&0\end{bmatrix}$ has the unique $\pi=(\tfrac12,\tfrac12)$, yet started in state 1 its law alternates $(1,0),(0,1),(1,0),\dots$ for ever. A chain with one closed recurrent class plus transient states (unichain) also has a unique $\pi$.

Definition — Absorbing and transient states, fundamental matrix
A state is absorbing if $P_{ii}=1$ (crashed, terminated), transient if the chain eventually leaves it for ever, recurrent if it returns again and again. In an absorbing chain every state is transient or absorbing; ordering the transient states first, $P=\begin{bmatrix}Q&R\\0&I\end{bmatrix}$ with a substochastic $Q$ (rows sum to at most $1$). If $Q^t\to0$, the expected numbers of visits are the entries of the fundamental matrix $N=\sum_{t\ge0}Q^t=(I-Q)^{-1}$ (a matrix geometric series), and $N\mathbf 1$ is the expected time to absorption. With zero cost after absorption, undiscounted total costs are then finite. (In a general chain the lower-right block is the transition matrix among the recurrent states rather than $I$, and $N$ counts visits before the chain enters a recurrent class.)

Worked example. $Q=\begin{bmatrix}0.5&0.3\\0.2&0.4\end{bmatrix}$: $\det(I-Q)=0.5\cdot0.6-0.3\cdot0.2=0.24$ and $N=\tfrac1{0.24}\begin{bmatrix}0.6&0.3\\0.2&0.5\end{bmatrix}=\begin{bmatrix}2.5&1.25\\0.833&2.083\end{bmatrix}$. From state 1 the chain spends on average $2.5+1.25=3.75$ steps before absorption. (For $V\ge0$, the drift condition $\mathbb E[V(X_{t+1})\mid X_t=x]\le V(x)-1$ for all $x$ outside a set $C$ is the probabilistic Lyapunov (Foster) criterion: from $x$ the chain reaches $C$ after at most $V(x)$ steps on average.)

Key equation — Stationary variance of a noisy linear system
Let $x_{t+1}=a\,x_t+w_t$ with $w_t$ i.i.d., mean $0$, variance $\sigma^2$, independent of $x_0$. Since $x_t$ depends only on $x_0,w_0,\dots,w_{t-1}$, it is independent of $w_t$, so
$$\mathbb E[x_{t+1}]=a\,\mathbb E[x_t],\qquad v_{t+1}=a^2v_t+\sigma^2\ \xrightarrow{\ |a|\lt1\ }\ v_\infty=\frac{\sigma^2}{1-a^2},\qquad \operatorname{Cov}(x_t,x_{t+k})=a^kv_t .$$
With Gaussian noise the stationary law is $\mathcal N(0,\sigma^2/(1-a^2))$.

Worked example. $a=0.9$, $\sigma=0.1$: $v_\infty=0.01/0.19=0.0526$, a stationary standard deviation of $0.229$, $2.3$ times the per-step noise, because noise accumulates. In Module 1's loop $x_{t+1}=x_t-k(x_t-0.8)+w_t$ the error $e_t=x_t-0.8$ has $a=1-k$ and $v_\infty=\sigma^2/(k(2-k))$. Three different notions: the deterministic equilibrium ($\sigma=0$, $e=0$); stability of the recursion ($|a|\lt1$); the stationary distribution ($\sigma\gt0$: the state keeps moving, its law no longer changes).

Random functions over time. The recursion $f_t=\sqrt{1-\varepsilon}\,f_{t-1}+\sqrt{\varepsilon}\,g_t$ with $\varepsilon\in[0,1]$, centred independent innovations $g_t$ of variance $s^2$, independent of the centred $f_0$ with $\operatorname{Var}f_0=s^2$ keeps $\operatorname{Var}f_t=(1-\varepsilon)s^2+\varepsilon s^2=s^2$ for every $t$, while $\operatorname{Cov}(f_t,f_{t-k})=(1-\varepsilon)^{k/2}s^2$ decays: memory fades and the process reverts to its mean ($\varepsilon=0$ frozen, $\varepsilon=1$ fresh each step). With $a=1$ and i.i.d. centred increments of variance $\sigma^2\gt0$ independent of $x_0$, the random walk $x_t=x_0+\sum_{s\lt t}w_s$ has variance growing like $t\sigma^2$: no stationary law and no mean reversion. Sped up to $n$ steps per unit of time and with each step divided by $\sigma\sqrt n$, $W_n(t)=\frac1{\sigma\sqrt n}\sum_{s\lt\lfloor nt\rfloor}w_s$ has $\operatorname{Var}W_n(t)=\lfloor nt\rfloor/n\to t$, and as $n\to\infty$ it converges in distribution (Donsker's theorem) to the Wiener process $W$: $W(0)=0$, continuous paths and independent increments $W(t)-W(s)\sim\mathcal N(0,t-s)$, hence for $s\le t$, $\operatorname{Cov}(W(s),W(t))=\operatorname{Cov}\big(W(s),W(s)+(W(t)-W(s))\big)=\operatorname{Var}W(s)=s=\min(s,t)$.

Definition — Monte Carlo estimate, bias, standard error
To estimate $m=\mathbb E[g(X)]$, average i.i.d. draws: $\hat m_N=\frac1N\sum_{i=1}^Ng(X_i)$. It is unbiased ($\mathbb E\hat m_N=m$) with $\operatorname{Var}\hat m_N=\operatorname{Var}g(X)/N$. The standard error $\mathrm{SE}=s/\sqrt N$, with the sample standard deviation $s=\big(\frac1{N-1}\sum_{i=1}^N(g(X_i)-\hat m_N)^2\big)^{1/2}$ ($N\ge2$), estimates the standard deviation of $\hat m_N$; for a proportion $\hat p=k/N$ the plug-in value is $\sqrt{\hat p(1-\hat p)/N}$. Central limit theorem: if $0\lt\sigma^2=\operatorname{Var}g(X)\lt\infty$, then $\mathbb P\big(\sqrt N(\hat m_N-m)/\sigma\le z\big)\to\Phi(z)$ for every $z$, with $\Phi$ the standard normal CDF (Section 4), and the same holds with $s$ in place of $\sigma$. This normal approximation, $\hat m_N\approx\mathcal N(m,\sigma^2/N)$, is what justifies "$\hat m_N\pm1.96\,\mathrm{SE}$"; it is asymptotic, not a finite-$N$ guarantee. An estimator's bias is $\mathbb E[\text{estimate}]-\text{target}$, and mean squared error $=$ bias$^2+$ variance.

Worked example (200 episodes). $40$ of $N=200$ episodes violate: $\hat p=0.2$, $\mathrm{SE}=\sqrt{0.2\cdot0.8/200}=0.028$, and the normal-approximation 95% interval is $0.2\pm1.96\cdot0.028=[0.145,\,0.255]$ ($1.96$ is the $97.5\%$ quantile of the standard normal, Section 4). With zero violations the formula gives $\mathrm{SE}=0$, which is meaningless. The exact statement: if the true rate were $p$, all $200$ runs are clean with probability $(1-p)^{200}$, which is below $0.05$ once $p\gt1-0.05^{1/200}=0.0149\approx3/200$ (the "rule of three"). Truncation bias: estimating $\mathbb E\sum_{t\ge0}\gamma^tc_t$ with $c_t\in[0,1]$ from episodes cut at horizon $H$ underestimates by at most $\gamma^H/(1-\gamma)$, which is $0.657$ for $\gamma=0.99$, $H=500$.

Pitfall — a standard error is not a guarantee
"$\pm1$ SE" contains the truth only about 68% of the time, and only when the normal approximation is good (not for small $N$ or $\hat p$ near $0$ or $1$). A confidence interval is a procedure with a stated coverage (Section 6); exact binomial bounds are in Section 10. Random sampling never covers a region exhaustively: the largest value over random draws is a lower bound on a supremum, never an upper bound. Finally, "$\theta_t\to\theta^\ast$ almost surely" (a statement about whole random sequences, like the strong law) differs from $\mathbb E|\theta_t-\theta^\ast|\to0$, and neither is a finite-time high-probability bound.
Where this is used
Stationary spread $\sigma/\sqrt{k(2-k)}$, transients and the "$\pm$" standard errors over $200$ episodes: Module 1, its panel. Autoregressive random functions and a Wiener-process temporal kernel: Module 5. Transient, absorbing and unichain models: Module 8; Monte Carlo constraint estimates, truncation bias and almost-sure convergence of primal-dual iterates: Module 8. Transient undiscounted CMDPs and expected visits: Module 11. Sampled lower bounds on a Lipschitz constant: Module 12. Standard errors of 30 simulated runs: Module 15.

Practice — Transitions, long-run laws and Monte Carlo

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S7 — Easy: Advance a distribution one step

A chain has states $A,B$ and row-stochastic transition matrix $P=\begin{bmatrix}0.8&0.2\\0.3&0.7\end{bmatrix}$. Start in $A$ with certainty. Find the distributions after one and two steps.

Review if needed: this section and matrix-vector multiplication.

Show hint
Use a row distribution $p_t$ and $p_{t+1}=p_tP$.
Show worked solution
  1. The initial row is $p_0=(1,0)$. Multiplying selects the first row: $p_1=(0.8,0.2)$.
  2. To reach $A$ in two steps, add the disjoint paths: $0.8(0.8)+0.2(0.3)=0.70$.
  3. Similarly $\mathbb P(s_2=B)=0.8(0.2)+0.2(0.7)=0.30$, so $p_2=(0.7,0.3)$. These entries sum to one, providing a useful arithmetic check.
Exercise C.S8 — Medium: Solve a stationary distribution

For the same $P$, solve $p_*P=p_*$ with $p_*=(a,1-a)$. Does stationarity mean that the chain stops moving?

Review if needed: this section and matrix-vector multiplication.

Show hint
Write only the first coordinate equation, then use the normalisation.
Show worked solution
  1. The first coordinate gives $a=0.8a+0.3(1-a)=0.5a+0.3$.
  2. Therefore $a=0.6$ and $p_*=(0.6,0.4)$. Check the other coordinate: $0.6(0.2)+0.4(0.7)=0.4$.
  3. Stationarity describes an unchanged distribution. Individual paths still switch states: from $A$ the next state is $B$ with probability $0.2$. A random trajectory and its law are different objects.
Exercise C.S9 — Hard: Why copying data does not increase sample size

Let $Z_1,\dots,Z_{100}$ be independent Bernoulli variables with success probability $0.2$. Compare the variance of their average with an average of $100$ recorded entries formed by repeating each of $50$ independent Bernoulli draws twice. Both averages are unbiased; are they equally precise?

Review if needed: this section and matrix-vector multiplication.

Show hint
The repeated-data average simplifies to an average of only $50$ independent variables.
Show worked solution
  1. A Bernoulli draw has variance $p(1-p)=0.2(0.8)=0.16$. Independence gives variance $0.16/100=0.0016$ for the first mean.
  2. The second mean is $(2/100)\sum_{i=1}^{50}Z_i=(1/50)\sum_{i=1}^{50}Z_i$, so its variance is $0.16/50=0.0032$.
  3. The standard deviations are $0.04$ and $\sqrt{0.0032}\approx0.05657$. Copying observations preserves the expectation but doubles this variance; counting dependent entries as independent understates uncertainty.

4. The Multivariate Gaussian & Gaussian Conditioning

Start here — Standardise and condition Gaussian laws

In $\mathcal N(10,4)$, the mean is $10$, the variance is $4$ and the standard deviation is $2$. Standardising $12$ gives $(12-10)/2=1$. Master this scalar calculation before the block-matrix conditioning formula.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review block matrices and Schur complements.

Definition — Normal law, $\Phi$, tails and quantiles
$X\sim\mathcal N(\mu,\sigma^2)$ with $\sigma\gt0$ has density $\frac{1}{\sqrt{2\pi\sigma^2}}e^{-(x-\mu)^2/(2\sigma^2)}$. Standardising, $Z=(X-\mu)/\sigma\sim\mathcal N(0,1)$, with density $\varphi(z)=e^{-z^2/2}/\sqrt{2\pi}$ and CDF $\Phi(z)=\mathbb P(Z\le z)$. Symmetry gives $\Phi(-z)=1-\Phi(z)$; the upper tail is $Q(z)=1-\Phi(z)=\tfrac12\operatorname{erfc}(z/\sqrt2)$ with $\operatorname{erfc}(x)=\tfrac2{\sqrt\pi}\int_x^\infty e^{-u^2}du$; the quantile $z_p=\Phi^{-1}(p)$ solves $\Phi(z_p)=p$. Hence
$$\mathbb P(X\gt\lambda)=1-\Phi\Big(\frac{\lambda-\mu}{\sigma}\Big),\qquad \mathbb P(|X-\mu|\gt c\,\sigma)=2\Phi(-c),\qquad \mathbb P(X\le\mu+z_p\sigma)=p .$$
If $\sigma=0$, $X$ is the constant $\mu$ and $\mathbb P(X\gt\lambda)=\mathbf 1\{\mu\gt\lambda\}$, a case the formula does not cover.
Rounded standard-normal probabilities and quantiles.
$z$$1$$1.2816$$1.6449$$1.96$$2$$2.3263$$3$$3.0902$
$\Phi(z)$$0.8413$$0.90$$0.95$$0.975$$0.9772$$0.99$$0.99865$$0.999$
$2\Phi(-z)$$0.3173$$0.20$$0.10$$0.05$$0.0455$$0.02$$0.0027$$0.002$

Worked example (one-sided safety probability). If the posterior of $f(x)$ is $\mathcal N(\mu,\sigma^2)$, then $\mathbb P(f(x)\ge\mu+\beta\sigma)=1-\Phi(\beta)=\Phi(-\beta)$. Requiring this to be at least $\alpha$ means $\Phi(\beta)\le1-\alpha$; for $\alpha=0.9$ that is $\beta\le-1.2816$. A safety probability above one half therefore forces a negative multiplier, i.e. a lower confidence bound; an optimistic $\beta\ge0$ certifies at most probability $\tfrac12$. Numerics: $Q(10)=7.6\cdot10^{-24}$, but $1-\Phi(10)$ evaluated in double precision is exactly $0$ because $\Phi(10)$ rounds to $1$ (cancellation). Tail probabilities should be computed from $\operatorname{erfc}$ directly; the formula is exact, the subtraction is not.

Definition — Multivariate normal
$X\sim\mathcal N(m,\Sigma)$ in $\mathbb R^n$ means $X=m+LZ$ with $Z$ a vector of independent standard normals and $LL^\top=\Sigma$. If $\Sigma\succ0$, $X$ has the density
$$p(x)=(2\pi)^{-n/2}\det(\Sigma)^{-1/2}\exp\!\big(-\tfrac12(x-m)^\top\Sigma^{-1}(x-m)\big),$$
whose level sets are the ellipsoids $(x-m)^\top\Sigma^{-1}(x-m)=c$ (Primer A). If $\Sigma$ is only PSD the law is degenerate: it lives on an affine subspace and has no density with respect to full $n$-dimensional volume. $\mathcal N(0,\sigma^2I)$ is isotropic: independent coordinates, spherical level sets, the same law after any rotation.
Fact — Affine maps, marginals, independence, full support
(a) $AX+b\sim\mathcal N(Am+b,\,A\Sigma A^\top)$, because $AX+b=(Am+b)+(AL)Z$. Every scalar projection is Gaussian: $u^\top X\sim\mathcal N(u^\top m,\,u^\top\Sigma u)$; for $\varepsilon\sim\mathcal N(0,\sigma^2I)$, $u^\top\varepsilon\sim\mathcal N(0,\sigma^2\|u\|^2)$. (b) Any sub-vector is Gaussian with the corresponding blocks of $m$ and $\Sigma$. (c) For jointly Gaussian vectors, uncorrelated means independent: a Gaussian law is fixed by its mean and covariance, and a block-diagonal $\Sigma$ has a block-diagonal $L$, so the blocks are built from disjoint groups of independent normals (when $\Sigma\succ0$: the density factorises). (d) If $\Sigma\succ0$ the density is positive everywhere, so every nonempty open ball has positive probability (full support). A random matrix $S$ is matrix-normal when the vector $\operatorname{vec}(S)$ of its stacked columns is Gaussian with covariance $V\otimes U$ (row covariance $U$, column covariance $V$); it is nondegenerate iff $U,V\succ0$.

Worked example (Gaussian chance constraint). Let $x\sim\mathcal N(m,\Sigma)$ with $m=(0.5,0.5)$, $\Sigma=\begin{bmatrix}0.04&0.01\\0.01&0.09\end{bmatrix}$ and $h=(1,1)$. Then $h^\top x\sim\mathcal N(1,\,0.04+0.09+2\cdot0.01)=\mathcal N(1,0.15)$ and $\mathbb P(h^\top x\le2)=\Phi(1/0.387)=\Phi(2.58)=0.995$. In general $\mathbb P(h^\top x\le b)\ge p\iff h^\top m+\Phi^{-1}(p)\sqrt{h^\top\Sigma h}\le b$: a deterministic, tightened constraint (here $1+1.645\cdot0.387=1.64\le2$ for $p=0.95$). The equivalence is exact only if $x$ really is Gaussian.

Worked example (repeated measurements). Let $y_1,\dots,y_m$ be i.i.d. $\mathcal N(f,\sigma^2)$. Then $\bar y\sim\mathcal N(f,\sigma^2/m)$, and since $\sum_i(y_i-f)^2=\sum_i(y_i-\bar y)^2+m(\bar y-f)^2$ (the cross term $2(\bar y-f)\sum_i(y_i-\bar y)$ vanishes), the likelihood of $f$ is $e^{-m(\bar y-f)^2/(2\sigma^2)}$ times a factor free of $f$: the mean with noise variance $\sigma^2/m$ carries all the information about $f$.

Pitfall — Gaussian marginals are not a Gaussian vector
Let $X\sim\mathcal N(0,1)$ and $Y=SX$ with an independent fair sign $S=\pm1$. Then $Y\sim\mathcal N(0,1)$ and $\operatorname{Cov}(X,Y)=\mathbb E[S]\,\mathbb E[X^2]=0$, yet $X+Y=0$ with probability $\tfrac12$, so $(X,Y)$ is not jointly Gaussian and not independent ($|Y|=|X|$). Fact (c) and the conditioning formula need joint Gaussianity. Similarly, a network that outputs a Gaussian mean and covariance is a model with unbounded support; it cannot be the same claim as "the noise is bounded".
Theorem — Gaussian conditioning via the Schur complement
Let $\begin{bmatrix}x\\y\end{bmatrix}\sim\mathcal N\Big(\begin{bmatrix}m_x\\m_y\end{bmatrix},\begin{bmatrix}\Sigma_{xx}&\Sigma_{xy}\\\Sigma_{yx}&\Sigma_{yy}\end{bmatrix}\Big)$ with $\Sigma_{yy}\succ0$. For every observed value $y$,
$$x\mid y\ \sim\ \mathcal N\Big(m_x+\Sigma_{xy}\Sigma_{yy}^{-1}(y-m_y),\ \ \Sigma_{xx}-\Sigma_{xy}\Sigma_{yy}^{-1}\Sigma_{yx}\Big).$$
The conditional mean is affine in $y$. The conditional covariance is the Schur complement of $\Sigma_{yy}$ (Primer A): it does not depend on the observed value and is never larger than $\Sigma_{xx}$ in the PSD order. Proof: the walkthrough below.

Precision addition. For a scalar prior $f\sim\mathcal N(m_0,s_0^2)$ and one observation $y=f+\varepsilon$ with noise $\varepsilon\sim\mathcal N(0,\sigma^2)$ independent of $f$ ($s_0,\sigma\gt0$), the theorem with $\Sigma_{xx}=\Sigma_{xy}=s_0^2$, $\Sigma_{yy}=s_0^2+\sigma^2$ gives posterior variance $s^2=s_0^2\sigma^2/(s_0^2+\sigma^2)$, i.e.

$$\frac1{s^2}=\frac1{s_0^2}+\frac1{\sigma^2},\qquad \mathbb E[f\mid y]=s^2\Big(\frac{m_0}{s_0^2}+\frac{y}{\sigma^2}\Big):$$

precisions (inverse variances) add and the mean is a precision-weighted average; $m$ repeated observations enter through $\bar y$ with precision $m/\sigma^2$. Conditioning independent parts on their sum works the same way: for independent $X_1\sim\mathcal N(0,a)$, $X_2\sim\mathcal N(0,b)$ and $S=X_1+X_2$, $\mathbb E[X_1\mid S]=\frac{a}{a+b}S$ and $\operatorname{Var}(X_1\mid S)=\frac{ab}{a+b}$ (a simulator part and a residual part of an objective, say).

Definition — Gaussian process and GP regression (preview of Module 3)
A Gaussian process $f\sim\mathcal{GP}(0,k)$ is a random function whose values at any finite set of inputs are jointly Gaussian with $\operatorname{Cov}(f(x),f(x'))=k(x,x')$, e.g. the squared-exponential kernel $k(x,x')=s^2\exp\!\big(-\|x-x'\|^2/(2\ell^2)\big)$ with output scale $s$ and length-scale $\ell$. With data $y_i=f(x_i)+\varepsilon_i$ at fixed inputs $x_1,\dots,x_t$, $\varepsilon_i\sim\mathcal N(0,\sigma^2)$ i.i.d. and independent of $f$, the vector $(f(x),y_1,\dots,y_t)$ is jointly Gaussian, and the theorem with $\Sigma_{xx}=k(x,x)$, $\Sigma_{xy}=k_t(x)^\top=[k(x,x_1),\dots,k(x,x_t)]$, $\Sigma_{yy}=K_t+\sigma^2I$ ($K_t$ the Gram matrix) gives
$$\mu_t(x)=k_t(x)^\top(K_t+\sigma^2I)^{-1}y,\qquad \sigma_t^2(x)=k(x,x)-k_t(x)^\top(K_t+\sigma^2I)^{-1}k_t(x).$$
$\sigma_t^2(x)$ is the latent variance of $f(x)$; a new noisy observation at $x$ has predictive variance $\sigma_t^2(x)+\sigma^2$. If each input is chosen from earlier observations (adaptive queries), the vector need not be jointly Gaussian, yet conditioning one observation at a time, with each query fixed once the past is known, gives the same formulas at the inputs actually queried. The term $\sigma^2I$ acts as a ridge regulariser (Module 3 calls it $\lambda$). Any linear operation on $f$ (differences, sums, $f$ evaluated along a fixed policy) is jointly Gaussian with the rest. The marginal likelihood of kernel parameters $\vartheta$ is the density of $y\sim\mathcal N(0,K_\vartheta+\sigma^2I)$:
$$\log p(y\mid\vartheta)=-\tfrac12y^\top(K_\vartheta+\sigma^2I)^{-1}y-\tfrac12\log\det(K_\vartheta+\sigma^2I)-\tfrac t2\log2\pi,$$
a data-fit term plus a complexity penalty. Scalar example: one observation $y=2$ of $f\sim\mathcal N(0,s^2)$ with $\sigma^2=1$ gives $y\sim\mathcal N(0,v)$, $v=s^2+1$; setting $\frac{d}{dv}\big(-\frac{y^2}{2v}-\frac12\log v\big)=\frac{y^2}{2v^2}-\frac1{2v}=0$ gives $v=y^2=4$, so ML-II picks $s^2=3$.

A truncated Gaussian on $[a_{\rm lo},a_{\rm hi}]$ has density $\varphi\big(\tfrac{a-m}{s}\big)\big/\big(s\,[\Phi(\tfrac{a_{\rm hi}-m}{s})-\Phi(\tfrac{a_{\rm lo}-m}{s})]\big)$ on the interval (Section 2's renormalisation), and seeded Gaussian draws are the standard way to generate random test networks, weights and noise; they sample, they do not cover.

Where this is used
$\varepsilon\sim\mathcal N(0,\sigma^2I)$, $\Phi$ and quantiles: Module 1, Module 15, Module 13. "$(y_t,f(x))$ is jointly Gaussian": Module 3. $\Phi(\beta_t)\le1-\alpha$ and negative multipliers: Module 4; conditioning on a simulation and precision addition: Module 4; noise variance $\sigma^2/m$: Module 4. $2\Phi(-2)\approx0.0455$: Module 5. Exceedance $1-F(\lambda)$: Module 7. Gaussian cost critics $\mathcal N(Q_c^\pi,V_c^\pi)$: Module 8. Gaussian noise and policies: Module 9. Gaussian networks and affine noise maps: Module 10. A GP composed with a policy; chance constraints $\Pr(h^\top x_k\le b)\ge p$: Module 11, Module 11. Seeded Gaussian weights: Module 12. Matrix-normal posteriors and full support: Module 15, Module 11.

Practice — Standardise and condition Gaussian laws

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S10 — Easy: Variance is not standard deviation

Let $X\sim\mathcal N(10,4)$. Find $\mathbb P(X\le12)$ and $\mathbb P(8\le X\le12)$ using $\Phi(1)\approx0.8413$.

Review if needed: this section and block matrices and Schur complements.

Show hint
In $\mathcal N(\mu,\sigma^2)$ the second number is the variance. Here $\sigma=2$.
Show worked solution
  1. Standardise with $Z=(X-10)/2$. The threshold $12$ becomes $(12-10)/2=1$.
  2. Hence $\mathbb P(X\le12)=\Phi(1)\approx0.8413$.
  3. The interval becomes $-1\le Z\le1$. By symmetry its probability is $\Phi(1)-\Phi(-1)=2\Phi(1)-1\approx0.6826$. A one-standard-deviation interval does not have $95\%$ coverage.
Exercise C.S11 — Medium: One noisy measurement

A scalar $f$ has prior $\mathcal N(0,4)$. Observe $y=f+\varepsilon=3$, where $\varepsilon\sim\mathcal N(0,1)$ is independent of $f$. Find the posterior mean and variance, and the variance of a future noisy measurement with independent noise variance $1$.

Review if needed: this section and block matrices and Schur complements.

Show hint
Add precisions: posterior precision is $1/4+1$. Latent and observation uncertainty differ.
Show worked solution
  1. Posterior precision is $1/4+1=5/4$, so the variance is $s^2=4/5=0.8$.
  2. The precision-weighted mean is $s^2(0/4+3/1)=12/5=2.4$. It lies between the prior mean and the observation, nearer the more precise observation.
  3. A future measurement adds independent noise, so its predictive variance is $0.8+1=1.8$. The latent variance $0.8$ alone would understate measurement uncertainty.
Exercise C.S12 — Hard: A chance constraint along a direction

Let $X$ be jointly Gaussian with mean $(1,2)$ and covariance $\begin{bmatrix}1&0.5\\0.5&4\end{bmatrix}$. For $S=X_1+X_2$, compute its mean and variance. Find the smallest $b$ satisfying $\mathbb P(S\le b)\ge0.95$, using $\Phi^{-1}(0.95)\approx1.64485$.

Review if needed: this section and block matrices and Schur complements.

Show hint
Use $S=h^\top X$ with $h=(1,1)$. Include both cross-covariance terms.
Show worked solution
  1. An affine projection of a jointly Gaussian vector is Gaussian. Its mean is $1+2=3$.
  2. Its variance is $h^\top\Sigma h=1+4+2(0.5)=6$, so $S\sim\mathcal N(3,6)$.
  3. The smallest threshold is the exact $95\%$ quantile: $b_\ast=3+\sqrt6\,\Phi^{-1}(0.95)\approx7.0291$. Substituting the supplied rounded quantile gives the estimate $3+1.64485\sqrt6\approx7.0290$, which is strictly below $b_\ast$ and does not meet the exact $0.95$ probability requirement. This uses the one-sided quantile; the familiar $1.96$ is a rounded radius for a two-sided $95\%$ interval.

5. Concentration: Markov, Chebyshev, Hoeffding & Sub-Gaussian Noise

Start here — Choose a bound whose assumptions hold

A tail bound is an upper limit on a probability, not a prediction that the limit is attained. If a nonnegative cost has mean $2$, Markov bounds the chance of cost at least $8$ by $2/8=1/4$. Stronger bounds below require additional assumptions; check them before substituting numbers.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review logarithms and rates.

A standard error says how far an average typically lands from its mean. A safety argument needs a bound on the probability of a large deviation that holds for every $N$, with no normal approximation. Each inequality below buys a faster-decaying tail with a stronger assumption.

Theorem — Markov and Chebyshev inequalities
Markov: if $X\ge0$ and $a\gt0$, then $\mathbb P(X\ge a)\le\mathbb E[X]/a$. Proof. $a\,\mathbf 1\{X\ge a\}\le X$ pointwise; take expectations. $\square$
Chebyshev: if $\operatorname{Var}X\lt\infty$ and $a\gt0$, then $\mathbb P(|X-\mathbb EX|\ge a)\le\operatorname{Var}(X)/a^2$. Proof. Markov for $(X-\mathbb EX)^2$ at level $a^2$. $\square$
For the mean of $N$ i.i.d. terms of variance $\sigma^2$, $\operatorname{Var}\bar X_N=\sigma^2/N$ gives $\mathbb P(|\bar X_N-m|\ge t)\le\sigma^2/(Nt^2)$: polynomial decay.
Theorem — The Chernoff method and Gaussian tails
With the moment-generating function (MGF) $M_X(\lambda)=\mathbb E[e^{\lambda X}]$, Markov applied to $e^{\lambda X}$ gives, for every $\lambda\gt0$, $\mathbb P(X\ge a)\le e^{-\lambda a}M_X(\lambda)$; then optimise over $\lambda$. For $Z\sim\mathcal N(0,1)$ and $a\gt0$, completing the square gives $M_Z(\lambda)=e^{\lambda^2/2}$. The minimiser is $\lambda=a\gt0$, so $\mathbb P(Z\ge a)\le\min_{\lambda\gt0}e^{-\lambda a+\lambda^2/2}=e^{-a^2/2}$. Two sharper facts for $c\gt0$:
$$\frac{c}{1+c^2}\varphi(c)\le1-\Phi(c)\le\frac{\varphi(c)}{c},\qquad \mathbb P(|Z|\gt c)\le e^{-c^2/2}.$$
The second follows from $\mathbb P(Z\gt c)=\int_0^\infty\varphi(u+c)\,du=e^{-c^2/2}\int_0^\infty\varphi(u)e^{-cu}du\le\tfrac12e^{-c^2/2}$. At $c=2$: $0.0216\le0.0228\le0.0270$, and $\mathbb P(|Z|\gt2)=0.0455\le e^{-2}=0.135$.

Worked example (standardised prediction errors). If, given the history, $f(x_t)\sim\mathcal N(\mu_t,\sigma_t^2)$ and the query $x_t$ was chosen from past data (so it is fixed once we condition on the history), then $\mathbb P\big(|f(x_t)-\mu_t|\gt\sqrt\rho\,\sigma_t\mid\text{history}\big)\le e^{-\rho/2}$. Choosing $\rho=2\ln(1/\delta)$ makes this $\delta$: for $\delta=0.05$, $\sqrt\rho=2.45$, slightly conservative against the exact two-sided $1.96$.

Definition — Sub-Gaussian random variable
A random variable $\varepsilon$ with $\mathbb E\varepsilon=0$ is $R$-sub-Gaussian if
$$\mathbb E\big[e^{\lambda\varepsilon}\big]\le e^{\lambda^2R^2/2}\qquad\text{for all }\lambda\in\mathbb R,$$
and conditionally $R$-sub-Gaussian if $\mathbb E[e^{\lambda\varepsilon_t}\mid\text{history}]\le e^{\lambda^2R^2/2}$ almost surely, the form used for adaptive data (Section 7). For $R\gt0$ and $a\gt0$, Chernoff gives $\mathbb P(\varepsilon\ge a)\le e^{-a^2/(2R^2)}$ and $\mathbb P(|\varepsilon|\ge a)\le2e^{-a^2/(2R^2)}$. When $R=0$, the MGF condition forces $\varepsilon=0$ almost surely, so every positive-threshold tail probability is zero. Expanding both sides for small $\lambda$ forces $\mathbb E\varepsilon=0$ and $\operatorname{Var}\varepsilon\le R^2$. $\mathcal N(0,\sigma^2)$ is $\sigma$-sub-Gaussian with equality, and a sum of independent $R_i$-sub-Gaussian terms is $\sqrt{\textstyle\sum_iR_i^2}$-sub-Gaussian (multiply the MGFs).
Lemma — Hoeffding's lemma: bounded and centred implies sub-Gaussian
If $a\le X\le b$ almost surely and $\mathbb EX=0$, then $\mathbb E[e^{\lambda X}]\le e^{\lambda^2(b-a)^2/8}$ for all $\lambda$: $X$ is $\tfrac{b-a}2$-sub-Gaussian. Zero-mean noise in $[-\sigma,\sigma]$ is $\sigma$-sub-Gaussian, and conditionally so if its conditional mean is zero and the bounds hold given the history.
Proof sketch — Hoeffding's lemma

If $a=b$, centring forces $X=0$ almost surely and the claim is immediate. Otherwise $a\lt b$. By convexity, $e^{\lambda x}$ lies below its chord on $[a,b]$: $e^{\lambda x}\le\frac{b-x}{b-a}e^{\lambda a}+\frac{x-a}{b-a}e^{\lambda b}$. Take expectations using $\mathbb EX=0$ and write $\theta=-a/(b-a)\in[0,1]$, $h=\lambda(b-a)$: $\mathbb Ee^{\lambda X}\le e^{L(h)}$ with $L(h)=-\theta h+\log(1-\theta+\theta e^h)$. Then $L(0)=0$, $L'(0)=0$ and $L''(h)=q(1-q)\le\tfrac14$ with $q=\theta e^h/(1-\theta+\theta e^h)\in[0,1]$. Taylor's theorem with remainder gives $L(h)\le h^2/8=\lambda^2(b-a)^2/8$. $\square$

Theorem — Hoeffding's inequality
If $N\ge1$, $a\lt b$, and $X_1,\dots,X_N$ are independent with $X_i\in[a,b]$, then for every $t\gt0$
$$\mathbb P\big(\bar X_N-\mathbb E\bar X_N\ge t\big)\le e^{-2Nt^2/(b-a)^2},\qquad \mathbb P\big(|\bar X_N-\mathbb E\bar X_N|\ge t\big)\le2e^{-2Nt^2/(b-a)^2}.$$
Proof. Chernoff for $S=\sum_i(X_i-\mathbb EX_i)$: independence factorises the MGF and Hoeffding's lemma bounds each factor, so $\mathbb P(S\ge Nt)\le e^{-\lambda Nt+N\lambda^2(b-a)^2/8}$; the minimiser $\lambda=4t/(b-a)^2$ gives the claim. $\square$ Hence $N\ge(b-a)^2\ln(2/\delta)/(2t^2)$ samples give $|\bar X_N-\mathbb E\bar X_N|\lt t$ with probability at least $1-\delta$ (one-sided: $\ln(1/\delta)$).

Worked example (how many runs?). Outcomes in $[0,1]$, accuracy $t=0.05$, failure probability $\delta=0.05$. Chebyshev with $\operatorname{Var}\le\tfrac14$: $N\ge1/(4\delta t^2)=2000$. Hoeffding: $N\ge\ln(40)/(2\cdot0.0025)=737.8$, so $738$. The central-limit approximation $(1.96\cdot0.5/0.05)^2\approx385$ is smaller but is not a guarantee. For rare events Hoeffding is loose; the Chernoff–KL bound $\mathbb P(\mathrm{Bin}(N,p)\ge Nq)\le e^{-N\,\mathrm{kl}(q\|p)}$ for $q\gt p$ (and the mirror image for $q\lt p$), with the KL divergence between Bernoulli laws $\mathrm{kl}(q\|p)=q\ln\frac qp+(1-q)\ln\frac{1-q}{1-p}$ (Section 8), is much sharper: for $p=0.01$, $q=0.03$, $N=1000$ it gives $1.9\cdot10^{-6}$ where Hoeffding gives $0.45$ (the exact value is $2\cdot10^{-7}$).

Zero-mean noisehard boundstd. dev.best $R$Hoeffding $R$
$\mathcal U(-1,1)$$1$$1/\sqrt3\approx0.577$$1/\sqrt3\approx0.577$$1$
$\pm0.5$ with probability $\tfrac12$ each$0.5$$0.5$$0.5$$0.5$
$0.99$ w.p. $0.01$, $-0.01$ w.p. $0.99$$0.99$$0.0995$$\sqrt{0.98/(2\ln99)}\approx0.327$$0.5$
$\mathcal N(0,\sigma^2)$none$\sigma$$\sigma$n/a
Student-$t$, 3 d.o.f.none$\sqrt3=1.73$none: not sub-Gaussiann/a

Heavy and uneven noise. A Student-$t$ variable with $\nu\in\{1,2,\dots\}$ degrees of freedom is $T=Z/\sqrt{V/\nu}$, where $Z,Z_1,\dots,Z_\nu$ are independent standard normals and $V=\sum_{j=1}^\nu Z_j^2$. Its density decays only polynomially, like $|t|^{-(\nu+1)}$, so the absolute moments $\mathbb E|T|^k$ of order $k\ge\nu$ are infinite and $\mathbb Ee^{\lambda T}=\infty$ for every $\lambda\ne0$: no sub-Gaussian parameter exists. For $\nu=3$ (variance $3$), $\mathbb P(|T|\gt5)=0.015$ against $0.004$ for $\mathcal N(0,3)$, and $\mathbb P(|T|\gt10)=0.002$ against $8\cdot10^{-9}$. Heteroscedastic noise $\varepsilon_t=s(x_t)\xi_t$ with $\xi_t\sim\mathcal N(0,1)$ independent of the past and $|s(x)|\le R$ everywhere is conditionally $R$-sub-Gaussian: one envelope $R$ covers every input.

Pitfall — $R$ is neither the standard deviation nor the likelihood noise
$R$ is an assumption about the actual noise law. It is at least the standard deviation and can be far larger (third row: $3.3\times$). A hard bound gives a valid $R$ via Hoeffding's lemma, but only for centred noise: bounded noise with a bias is not sub-Gaussian in this sense at all. And $R$ need not equal the noise standard deviation $\sqrt\lambda$ used in the GP likelihood.
Where this is used
The sub-Gaussian parameter $R$ in regret and confidence bounds: Module 1; $R$ versus the regulariser $\lambda$: Module 3; heteroscedastic and heavy-tailed noise: Module 3. $\sigma$-sub-Gaussian noise: Module 4, Module 6. Conditionally $R$-sub-Gaussian noise: Module 5; Hoeffding's lemma for noise in $[-B_\varepsilon,B_\varepsilon]$: Module 5; the $e^{-\rho/2}$ Gaussian tail: Module 5. Validation sample sizes $\ln(1/\alpha)/(2\epsilon^2)$: Module 11. Student-$t$ residuals: Module 15.

Practice — Choose a bound whose assumptions hold

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S13 — Easy: An upper bound can be loose

A nonnegative random cost $X$ has mean $2$. Bound $\mathbb P(X\ge8)$ with Markov's inequality. What does the same method say about $\mathbb P(X\ge1)$?

Review if needed: this section and logarithms and rates.

Show hint
A probability cannot exceed one, even when an inequality returns a larger number.
Show worked solution
  1. Markov applies because $X\ge0$: $\mathbb P(X\ge8)\le\mathbb E[X]/8=2/8=1/4$.
  2. At threshold $1$ the algebra gives $\mathbb P(X\ge1)\le2$. Combining with the universal probability bound gives at most $1$.
  3. This second result is valid but uninformative. A bound is an upper limit, not an estimate of the actual tail probability, and these assumptions alone need not give a useful limit at every threshold.
Exercise C.S14 — Medium: Plan a Hoeffding sample size

Independent observations lie in $[0,1]$ and have a common mean $\mu$. How many observations suffice to bound $|\bar X_N-\mu|$ by $0.1$ with confidence at least $0.95$ using Hoeffding?

Review if needed: this section and logarithms and rates.

Show hint
Solve $2e^{-2N(0.1)^2}\le0.05$ and round upward.
Show worked solution
  1. Two-sided Hoeffding gives failure probability at most $2e^{-0.02N}$. Divide by $2$: $e^{-0.02N}\le0.025$.
  2. Taking logarithms and dividing by the negative coefficient reverses the inequality: $N\ge\ln(40)/0.02\approx184.44397$.
  3. Use $N=185$, the smallest integer certified by this bound. Rounding down gives a failure bound slightly above $0.05$. The derivation requires independence and the stated range.
Exercise C.S15 — Hard: A bounded bias survives averaging

Let independent errors be uniform on $[0,2]$. A learner treats them as zero-mean noise and chooses $R=2$. Explain why the zero-mean sub-Gaussian condition fails. Centre the errors correctly and give a valid Hoeffding sub-Gaussian parameter for the centred errors.

Review if needed: this section and logarithms and rates.

Show hint
First compute the expectation. The centred interval has length $2$, and Hoeffding uses half that length.
Show worked solution
  1. The error mean is $1$, so the sample mean converges to $1$, not $0$. A hard bound does not remove bias.
  2. For a zero-mean sub-Gaussian condition, the MGF must obey $\mathbb E e^{\lambda\varepsilon}\le e^{\lambda^2R^2/2}$ for both signs near zero. Its left-hand side has expansion $1+\lambda\mathbb E\varepsilon+O(\lambda^2)=1+\lambda+O(\lambda^2)$, contradicting the bound for small positive $\lambda$.
  3. Set $\xi=\varepsilon-1$. Then $\mathbb E\xi=0$ and $\xi\in[-1,1]$. Hoeffding's lemma certifies $R=(1-(-1))/2=1$. The observation model must still account for the removed bias.

6. “With Probability at Least $1-\delta$”: Union Bounds & Confidence Statements

Start here — Budget failure probability explicitly

A $95\%$ statement about one quantity and a $95\%$ statement about every quantity are different events. Ten failure budgets of $0.005$ add to a total budget of $0.05$. Write the desired event first, then decide how the confidence budget must be shared.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review unions and quantifiers.

Definition — Reading a high-probability guarantee
"With probability at least $1-\delta$, $\mathcal S$" names a random experiment and a good event $G=\{\mathcal S\text{ holds}\}$, and claims $\mathbb P(G)\ge1-\delta$; $\delta$ is the failure probability. Quantifiers written after "with probability" sit inside the event:
$$\underbrace{\mathbb P\big(\forall t,\forall x:\ |f(x)-\mu_{t-1}(x)|\le\beta_t\sigma_{t-1}(x)\big)\ge1-\delta}_{\text{uniform: one event covers every round and input}}\qquad\text{vs.}\qquad \underbrace{\forall t,x:\ \mathbb P\big(|f(x)-\mu_{t-1}(x)|\le\beta_t\sigma_{t-1}(x)\big)\ge1-\delta}_{\text{pointwise}}$$
On the uniform event every decision of the algorithm may rely on the band. The pointwise version says nothing about all rounds at once, nor about an input $x_t$ that the algorithm picked because of the data.
Theorem — Union bound (Boole's inequality)
For any finitely or countably many events, dependent or not, $\mathbb P\big(\bigcup_iA_i\big)\le\sum_i\mathbb P(A_i)$. Proof. $\mathbf 1_{\cup_iA_i}\le\sum_i\mathbf 1_{A_i}$ pointwise; take expectations (Tonelli for countably many terms). $\square$ With failure events $F_i=G_i^c$: $\mathbb P\big(\bigcap_iG_i\big)=1-\mathbb P\big(\bigcup_iF_i\big)\ge1-\sum_i\mathbb P(F_i)$. Giving each of $n$ guarantees failure probability $\delta/n$ makes all of them hold jointly with probability at least $1-\delta$.

Worked example (what joint coverage costs). A two-sided Gaussian band at one point with $\delta=0.05$ needs $\beta=1.96$. For $T=100$ rounds at $\delta/T$ each it needs $\Phi^{-1}(1-0.00025)=3.48$; for $T=10^4$, $4.56$: the price grows only like $\sqrt{\log T}$. If the per-step failures were independent with probability $0.001$, joint success over $100$ steps would be exactly $0.999^{100}=0.905$ against the union bound's $0.9$: barely conservative, and the union bound stays valid under dependence, where the product formula does not. The same logic turns per-step chance constraints into a joint one: $\mathbb P(x_t\notin C)\le\delta$ for each $t$ does not give $\mathbb P(\exists t\le T:\ x_t\notin C)\le\delta$, but $\mathbb P(x_t\notin C)\le\delta/T$ for each $t$ does.

Anytime budgets. To cover all $t=1,2,\dots$ at once, spend a summable sequence: $\delta_t=\frac{\delta}{t(t+1)}$ gives $\sum_{t\ge1}\delta_t=\delta\sum_{t\ge1}\big(\frac1t-\frac1{t+1}\big)=\delta$ by telescoping; $\delta_t=\delta/\pi_t$ with $\pi_t=\pi^2t^2/6$, so that $\sum_t\pi_t^{-1}=1$, does the same via $\sum_t1/t^2=\pi^2/6$. For $\delta=0.05$ and $\delta_t=\delta/(t(t+1))$, a two-sided Gaussian band needs $\beta_t=\Phi^{-1}(1-\delta_t/2)=2.24,\ 3.51,\ 4.57,\ 5.45$ at $t=1,10,100,1000$.

Definition — Confidence interval versus credible interval
A confidence interval at level $1-\delta$ is a procedure mapping data to $[L(\mathcal D),U(\mathcal D)]$ such that $\mathbb P_\theta(L\le\theta\le U)\ge1-\delta$ for every fixed value of the unknown $\theta$; the probability is over repetitions of the experiment, and a computed interval either contains $\theta$ or not. Examples: $\bar y\pm1.96\,\sigma/\sqrt N$ for a Gaussian mean with known $\sigma$; $\bar X\pm\sqrt{\ln(2/\delta)/(2N)}$ for $[0,1]$-valued data (Hoeffding). A credible interval is Bayesian: $\mathbb P(\theta\in[L,U]\mid\mathcal D)\ge1-\delta$ under the posterior, with $\theta$ random and the data fixed.
Frequentist band (RKHS)Bayesian band (GP posterior)
the unknown $f$fixed, with $\|f\|_k\le B$random, $f\sim\mathcal{GP}(0,k)$
source of randomnessmeasurement noise (and the algorithm's own)the prior over $f$ and the noise
"probability $1-\delta$"over repeated runs on this $f$over functions from the prior, given the data
guarantee lost when$\|f\|_k\gt B$ or the noise is not conditionally sub-Gaussianthe prior or the likelihood is wrong

Uniform over inputs. On a finite domain a union bound over the $|D|$ points only adds $\log|D|$ under the square root: with the Gaussian tail of Section 5 the multiplier becomes $\beta_t=\sqrt{2\log(|D|\pi_t/\delta)}$. On a continuum there are infinitely many points: one needs a discretisation plus a Lipschitz argument, or a self-normalised martingale bound (Section 7) that controls the whole function at once. Nested (PAC) statements. When a bound is itself calibrated from random data, two probabilities appear: $\mathbb P_{\mathcal Z}\big\{\mathbb P(\text{good}\mid\mathcal Z)\ge1-\gamma\big\}\ge1-\kappa$, "probably ($1-\kappa$, over the calibration sample $\mathcal Z$) approximately ($1-\gamma$, over fresh draws) correct". Example: let $B$ be the maximum of $m$ i.i.d. samples of a continuous quantity with CDF $F$. $F(B)$ is the fraction of fresh draws that $B$ covers, and $\mathbb P\{F(B)\lt1-\gamma\}=(1-\gamma)^m$ because all $m$ samples must fall below the $(1-\gamma)$-quantile. For $\gamma=0.05$ and $\kappa=0.01$, $m\ge\ln0.01/\ln0.95=89.8$: $90$ samples.

Pitfall — repeated use and selection
A validation test that wrongly accepts a bad candidate with probability $\alpha=0.01$, run on up to $K=10$ candidates until one passes, can wrongly accept with probability up to $10\cdot0.01=0.1$; testing each attempt at $\delta/K$ restores $\delta$, provided each candidate is frozen before a fresh validation sample is drawn for it, so that every attempt keeps error probability at most $\delta/K$ given the earlier ones (reusing one validation set to both choose and test voids that per-test level). The probability of being bad given acceptance is yet another number, which can exceed $\alpha$ when most candidates are bad (Section 2's base rate). Finally, empirical coverage on past tasks (calibration) is an estimate with its own standard error, not a guarantee for a new task.
Where this is used
Union bounds and "$f$ fixed" frequentist bands: Module 1. Bands "for all $x$ and all $t$": Module 3. "With probability at least $1-\delta$ over the whole run" and union bounds over $n$ safety GPs: Module 4, Module 4. The good event and frequentist versus Bayesian randomness: Module 5; $\sum_t\pi_t^{-1}=1$: Module 5; nested confidence $1-\kappa$ with coverage $(1-\gamma)(1-\delta)$: Module 5. Every query safe, union bounds over comparisons: Module 6, Module 6. Joint chance constraints over a horizon: Module 8, Module 15. All-time prediction-error events: Module 10. At most $K$ validation attempts: Module 11. Per-call versus repeated use: Module 15.

Practice — Budget failure probability explicitly

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S16 — Easy: One statement or all statements?

Three safety checks each fail with probability at most $0.01$. Give a lower bound on the probability that all three pass. Must the failures be independent?

Review if needed: this section and unions and quantifiers.

Show hint
The complement of all passing is the union of the failure events.
Show worked solution
  1. Call the failure events $F_1,F_2,F_3$. The event that at least one check fails is $F_1\cup F_2\cup F_3$.
  2. The union bound gives $\mathbb P(F_1\cup F_2\cup F_3)\le0.01+0.01+0.01=0.03$.
  3. Take the complement: all pass with probability at least $0.97$. No independence is needed. Multiplying $0.99^3$ would require independence and would answer a stronger, differently assumed calculation.
Exercise C.S17 — Medium: A finite grid of confidence intervals

You want simultaneous confidence $0.95$ for $10$ sample means. Each uses $N$ independent observations in $[0,1]$ with a common mean $\mu_i$ within that data set, and must estimate its $\mu_i$ with absolute error at most $0.1$. Assign equal failure budgets and find a sufficient common $N$. The ten data sets may depend on one another.

Review if needed: this section and unions and quantifiers.

Show hint
Give each mean budget $0.05/10$, then apply two-sided Hoeffding within that data set.
Show worked solution
  1. Each mean receives failure budget $\delta_i=0.005$. Independence is required among the observations used for each application of Hoeffding.
  2. Solve $2e^{-0.02N}\le0.005$: $N\ge\ln(400)/0.02\approx299.5732$. Thus $300$ observations per mean suffice.
  3. The union bound adds ten failure budgets to $0.05$. It does not require the different means to be independent. A pointwise $95\%$ interval for each mean would provide only a $50\%$ lower bound for all ten together.
Exercise C.S18 — Hard: Guarantees at every time

For times $t=1,2,\dots$, assign failure budgets $\delta_t=0.05/[t(t+1)]$. Prove that all time-indexed statements hold together with probability at least $0.95$, provided each has failure probability at most $\delta_t$. Can you instead assign $0.05$ at every time?

Review if needed: this section and unions and quantifiers.

Show hint
Use $1/[t(t+1)]=1/t-1/(t+1)$ and take the limit of its partial sums.
Show worked solution
  1. The sum through time $T$ telescopes to $\sum_{t=1}^T\delta_t=0.05(1-1/(T+1))$.
  2. As $T\to\infty$, the total budget is $0.05$. The countable union bound therefore limits the probability of any failure, at any time, to $0.05$.
  3. A fixed budget $0.05$ per time sums to infinity, giving no useful simultaneous bound. For example, independent failures of probability $0.05$ eventually occur with probability one, since the probability of no failure through $T$ is $0.95^T\to0$.

7. Adaptive Data, Filtrations & Martingales

Start here — Use only information available before the draw

Think of a filtration as a notebook containing everything observed so far. A choice made from that notebook is fixed when conditioning on the past; new noise is still random. This is why adaptively chosen experiments can need conditional assumptions even when ordinary independent-sample formulas look familiar.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review conditional expectation.

A safe-exploration algorithm chooses its next query $x_t$ from everything it has seen. The data $(x_1,y_1),(x_2,y_2),\dots$ are then neither independent nor identically distributed: $x_t$ depends on past noise, and so may the spread of the next measurement. What survives is a "fresh noise" property, and martingales are its language.

Definition — Filtration, adapted, predictable, martingale difference
A filtration $\mathcal F_0\subseteq\mathcal F_1\subseteq\cdots$ records what is known at each time; here $\mathcal F_t$ is everything observed up to round $t$ ($x_1,y_1,\dots,x_t,y_t$ and any internal randomness). A process is adapted ($\mathcal F_t$-measurable) if $Z_t$ is a function of the information at time $t$, and predictable if $Z_t$ is already known at time $t-1$: the query $x_t$, chosen before its noise is drawn, is $\mathcal F_{t-1}$-measurable. Noise $\varepsilon_t$ is a martingale difference sequence if it is adapted and $\mathbb E[\varepsilon_t\mid\mathcal F_{t-1}]=0$: zero mean given the whole past.

Why "zero-mean given the past" and not just "zero-mean". Let $\varepsilon_1=\pm1$ with probability $\tfrac12$ each and $\varepsilon_2=\varepsilon_1$ (the sensor repeats its error). Both have mean zero, but $\mathbb E[\varepsilon_2\mid\varepsilon_1]=\varepsilon_1\ne0$ and $\operatorname{Var}(\varepsilon_1+\varepsilon_2)=4$ instead of $2$: averaging does not cancel the error. Conversely, heteroscedastic noise $\varepsilon_t=s(x_t)\xi_t$ with fresh standard normal $\xi_t$ and adaptively chosen $x_t$ is not i.i.d., yet $\mathbb E[\varepsilon_t\mid\mathcal F_{t-1}]=s(x_t)\,\mathbb E[\xi_t]=0$ (take out what is known). For such sequences, and $s\lt t$, $\mathbb E[\varepsilon_s\varepsilon_t]=\mathbb E\big[\varepsilon_s\,\mathbb E[\varepsilon_t\mid\mathcal F_{t-1}]\big]=0$, so $\operatorname{Var}\sum_t\varepsilon_t=\sum_t\mathbb E\varepsilon_t^2$ exactly as for independent noise.

Definition — Martingale, supermartingale, stopping time
An adapted, integrable process $M_t$ is a martingale if $\mathbb E[M_t\mid\mathcal F_{t-1}]=M_{t-1}$ (a fair game, e.g. the partial sums $S_t=\sum_{s\le t}\varepsilon_s$ of a martingale difference sequence), and a supermartingale if $\mathbb E[M_t\mid\mathcal F_{t-1}]\le M_{t-1}$ (the conditional expectation drifts down). A stopping time $\tau$ is a random time whose decision "stop now" uses only current information: the event $\{\tau=t\}$ is determined by $\mathcal F_t$. "Stop the first time the estimate looks safe" is one; "stop one step before the first failure" is not.
Theorem — Optional stopping and Ville's maximal inequality
(a) If $M$ is a supermartingale and $\tau$ a stopping time with $\tau\le T$ for a fixed $T$, then $\mathbb E[M_\tau]\le\mathbb E[M_0]$; for $M\ge0$ the same holds for every almost surely finite $\tau$. (b) Ville: if $M\ge0$ is a supermartingale, then for every $c\gt0$
$$\mathbb P\big(\exists t\ge0:\ M_t\ge c\big)\le\mathbb E[M_0]/c .$$
Proof of (b). Let $\tau$ be the first $t$ with $M_t\ge c$ and fix $T$. Then $\tau\wedge T=\min(\tau,T)$ is a bounded stopping time and $M_{\tau\wedge T}\ge c\,\mathbf 1\{\tau\le T\}$, so $c\,\mathbb P(\tau\le T)\le\mathbb E[M_{\tau\wedge T}]\le\mathbb E[M_0]$; let $T\to\infty$. $\square$ Ville is Markov's inequality made time-uniform: one event covers all $t$.
Pitfall — optional stopping needs its conditions
Bet one unit on a fair coin, double the stake after every loss and stop at the first win. The winnings form a martingale with $M_0=0$ and the stopping time is finite almost surely, yet $M_\tau=1$ always. The stopping time is unbounded and $M$ is not bounded below, so neither version of (a) applies. A safety argument that stops "when things look good" must check these conditions.
Theorem — Azuma–Hoeffding (statement)
If $\varepsilon_t$ is a martingale difference sequence that is conditionally $R$-sub-Gaussian (for instance $|\varepsilon_t|\le R$), then for a fixed $T$ and $a\gt0$, $\mathbb P\big(\sum_{t=1}^T\varepsilon_t\ge a\big)\le e^{-a^2/(2TR^2)}$. The proof is Hoeffding's with the product of MGFs replaced by the supermartingale $M_t^\lambda=\exp(\lambda S_t-\lambda^2R^2t/2)$: $\mathbb E[M_t^\lambda\mid\mathcal F_{t-1}]=M_{t-1}^\lambda\,\mathbb E[e^{\lambda\varepsilon_t}\mid\mathcal F_{t-1}]\,e^{-\lambda^2R^2/2}\le M_{t-1}^\lambda$, with $M_0^\lambda=1$.

The method of mixtures: one bound for all times. Ville applied to $M^\lambda$ is time-uniform, but each fixed $\lambda$ is tuned to one scale of $S_t$. The remedy is to average over $\lambda$, since a nonnegative mixture of supermartingales is again one. With $R=1$ and $\lambda\sim\mathcal N(0,1/v)$, completing the square gives

$$M_t=\int e^{\lambda S_t-\lambda^2t/2}\,\mathcal N(\lambda;0,v^{-1})\,d\lambda=\sqrt{\frac{v}{v+t}}\;\exp\!\Big(\frac{S_t^2}{2(v+t)}\Big),\qquad M_0=1 .$$

Ville with $c=1/\delta$: with probability at least $1-\delta$, simultaneously for all $t$, $|S_t|\lt\sqrt{2(v+t)\big[\ln(1/\delta)+\tfrac12\ln(1+t/v)\big]}$, a sum self-normalised by its accumulated variance $v+t$. For $v=1$, $\delta=0.05$, $t=100$: $|S_t|\lt32.7$, against $27.2$ from Hoeffding valid at $t=100$ only, and $50.8$ from a union bound with $\delta_t=\delta/(t(t+1))$. Module 3 does the same in feature space: $v+t$ becomes the matrix $V+\sum_sX_sX_s^\top$ and $\sqrt{v/(v+t)}$ a determinant ratio, whose logarithm is, up to sign, the information gain of Section 8. Martingale noise also drives stochastic approximation: updates $\theta_{t+1}=\theta_t+\eta_t(h(\theta_t)+\varepsilon_t)$ with $\sum_t\eta_t=\infty$, $\sum_t\eta_t^2\lt\infty$ (Robbins–Monro), with martingale-difference noise of bounded conditional second moment, make the weighted noise series converge; together with stability and regularity assumptions they average out the noise $\sum_t\eta_t\varepsilon_t$ and, under further conditions, converge almost surely to stable zeros of $h$; primal-dual methods run two such recursions with step sizes decaying at different rates (two timescales).

Where this is used
Noise "zero-mean conditioned on the history": Module 1, Module 4, Module 5 ($\mathcal F_t$- versus $\mathcal F_{t-1}$-measurable), Module 6. Martingale difference noise, one supermartingale per direction, Gaussian mixtures, Ville and stopping times: Module 3. Supermartingale certificates and optional stopping: Module 9. Robbins–Monro steps and almost-sure convergence: Module 8.

Practice — Use only information available before the draw

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S19 — Easy: A fair random walk

Let $\varepsilon_1,\varepsilon_2,\dots$ be independent fair signs, taking $-1$ and $1$ with equal probability. Put $S_t=\sum_{i=1}^t\varepsilon_i$, with $S_0=0$. What is $\mathbb E[S_{t+1}\mid\mathcal F_t]$, where $\mathcal F_t$ records the first $t$ signs?

Review if needed: this section and conditional expectation.

Show hint
At time $t$, $S_t$ is known and the next independent sign still has mean zero.
Show worked solution
  1. Expand the next state: $S_{t+1}=S_t+\varepsilon_{t+1}$.
  2. Conditioning on $\mathcal F_t$ leaves the known term unchanged, while independence gives $\mathbb E[\varepsilon_{t+1}\mid\mathcal F_t]=0$.
  3. Thus $\mathbb E[S_{t+1}\mid\mathcal F_t]=S_t$. Each $S_t$ is integrable and determined by the recorded past, so these are the martingale conditions. The walk can move on every step despite having no conditional drift.
Exercise C.S20 — Medium: An adaptive multiplier can preserve zero drift

Before seeing a fair sign $\varepsilon_t$, choose $a_t=2$ if the current random-walk sum $S_{t-1}\ge0$, and $a_t=1$ otherwise. Define $D_t=a_t\varepsilon_t$. Show that $\mathbb E[D_t\mid\mathcal F_{t-1}]=0$ and find a valid conditional sub-Gaussian parameter.

Review if needed: this section and conditional expectation.

Show hint
The multiplier is already known when conditioning on the past; its magnitude never exceeds $2$.
Show worked solution
  1. $a_t$ is a function of the past, so it can be taken outside the conditional expectation: $\mathbb E[D_t\mid\mathcal F_{t-1}]=a_t\mathbb E[\varepsilon_t\mid\mathcal F_{t-1}]=0$.
  2. Given the past, $D_t$ lies in $[-a_t,a_t]$. Conditional Hoeffding certifies parameter $a_t$.
  3. Since $a_t\le2$, the uniform choice $R=2$ is valid at every time. The increments need not be independent; predictability and a conditional zero-mean bound are the properties used here.
Exercise C.S21 — Hard: Looking ahead breaks the argument

A learner first observes a fair sign $\varepsilon_t$ and then chooses $a_t=\varepsilon_t$. It claims that $D_t=a_t\varepsilon_t$ has mean zero because the original noise is fair. Compute its conditional mean and identify the failed step.

Review if needed: this section and conditional expectation.

Show hint
List the two possible sign values and square them.
Show worked solution
  1. If $\varepsilon_t=1$, then $D_t=1$; if $\varepsilon_t=-1$, then $D_t=(-1)(-1)=1$. Thus $D_t=1$ surely.
  2. Consequently $\mathbb E[D_t\mid\mathcal F_{t-1}]=1$, and its accumulated sum grows deterministically rather than forming a zero-drift martingale.
  3. The multiplier was chosen using the new noise, so it is not known from $\mathcal F_{t-1}$. Pulling it outside that conditional expectation is invalid. Unconditional fairness of the original noise is insufficient after such a choice.

8. Entropy, KL Divergence, Total Variation & Mutual Information

Start here — Compare distributions, not individual samples

Here the objects being compared are whole probability laws. For $p=(0.75,0.25)$ and $q=(0.5,0.5)$, the first outcome's probability changes by $0.25$. TV asks how much event probabilities can differ; KL averages logarithmic probability ratios and depends on direction.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review discrete probability laws.

Definition — Entropy (discrete and differential), nats
For a probability vector $p=(p_1,\dots,p_n)$, $H(p)=-\sum_ip_i\log p_i$ with $0\log0=0$. With natural logarithms the unit is the nat ($1$ nat $=1/\ln2\approx1.44$ bits). $0\le H(p)\le\log n$, with equality on the right iff $p$ is uniform: by Jensen (concave $\log$), $H=\sum_ip_i\log\frac1{p_i}\le\log\sum_{i:p_i\gt0}p_i\frac1{p_i}\le\log n$. For a density the differential entropy $h(p)=-\int p\log p$ may be negative and changes under rescaling; for $\mathcal N(m,\Sigma)$ in $\mathbb R^n$ with $\Sigma\succ0$, $h=\tfrac12\log\det(2\pi e\,\Sigma)$. Conditional entropy $H(X\mid Y)=\mathbb E_y[H(X\mid Y=y)]$ obeys the chain rule $H(X,Y)=H(Y)+H(X\mid Y)$.

Worked example. The policy $(0.7,0.2,0.1)$ has $H=0.7\ln\frac1{0.7}+0.2\ln5+0.1\ln10=0.802$ nats ($1.157$ bits), below $\ln3=1.099$; a fair coin has $\ln2=0.693$; $\mathcal U(0,\tfrac12)$ has $h=\ln\tfrac12=-0.693\lt0$. An entropy bonus with a temperature rewards spread-out policies. The expected entropy reduction of a measurement $Y$ about $X$, $H(X)-\mathbb E_y[H(X\mid Y=y)]$, is the mutual information below. A model with low predictive entropy is confident, which is not the same as accurate.

Definition — Kullback–Leibler divergence
$\mathrm{KL}(p\,\|\,q)=\sum_ip_i\log\frac{p_i}{q_i}$ (or $\int p\log\frac pq$), with $0\log\frac0q=0$ and $\mathrm{KL}=+\infty$ if some $q_i=0\lt p_i$. Gibbs: $\mathrm{KL}(p\|q)\ge0$ with equality iff $p=q$. Proof. By Jensen, $-\mathrm{KL}(p\|q)=\sum_ip_i\log\frac{q_i}{p_i}\le\log\sum_{i:p_i\gt0}q_i\le0$. $\square$ KL is not symmetric and not a distance. For Gaussians, $\mathrm{KL}\big(\mathcal N(m_1,s_1^2)\|\mathcal N(m_2,s_2^2)\big)=\ln\frac{s_2}{s_1}+\frac{s_1^2+(m_1-m_2)^2}{2s_2^2}-\frac12$. KL is also the Bregman divergence of the negative entropy $\phi(p)=\sum_ip_i\log p_i$: $\phi(p)-\phi(q)-\nabla\phi(q)^\top(p-q)=\mathrm{KL}(p\|q)$ for probability vectors with all $q_i\gt0$, where the gradient, with entries $\log q_i+1$, exists.

Worked example (direction matters). $p=(0.5,0.5)$, $q=(0.9,0.1)$: $\mathrm{KL}(p\|q)=0.5\ln\frac{0.5}{0.9}+0.5\ln5=0.511$ but $\mathrm{KL}(q\|p)=0.9\ln1.8+0.1\ln0.2=0.368$. If $q=(1,0)$ excludes the second action, $\mathrm{KL}(p\|q)=\infty$ while $\mathrm{KL}(q\|p)=\ln2$: a new policy that tries an action the old one never takes is infinitely far in $\mathrm{KL}(\text{new}\|\text{old})$. From a uniform $q$ over $|\mathcal A|$ actions, $\mathrm{KL}(p\|q)=\log|\mathcal A|-H(p)\le\log|\mathcal A|$, the usual bound on an initial divergence.

Maximum likelihood is forward KL: $\mathbb E_{x\sim p^\ast}[\log q_\theta(x)]=-H(p^\ast)-\mathrm{KL}(p^\ast\|q_\theta)$, and $H(p^\ast)$ does not depend on $\theta$, so maximising the expected log-likelihood minimises $\mathrm{KL}(p^\ast\|q_\theta)$; a weighted likelihood $\sum_iw_i\log\pi_\theta(a_i\mid s_i)$ fits $\pi_\theta$ to the reweighted target in the same forward direction.

Variational inference and EM rest on the identity $\log p_\theta(x)=\mathbb E_{z\sim q}\big[\log\frac{p_\theta(x,z)}{q(z)}\big]+\mathrm{KL}\big(q\,\|\,p_\theta(z\mid x)\big)$ for any law $q$ of a latent $z$ with $\mathrm{KL}\big(q\,\|\,p_\theta(z\mid x)\big)\lt\infty$ (in particular, $q$ puts no mass where the posterior has none): the first term (the ELBO) is a lower bound on the log-likelihood, tight when $q$ is the posterior. (For other $q$ the ELBO is $-\infty$: the bound still holds, the identity would read $-\infty+\infty$.) EM alternates an E-step (set $q$ to the posterior, or fit it) and an M-step (maximise the ELBO over $\theta$).

Definition — Total variation; Pinsker's inequality
$d_{\rm TV}(p,q)=\sup_A|p(A)-q(A)|=\tfrac12\sum_i|p_i-q_i|=\tfrac12\|p-q\|_1$ (densities: $\tfrac12\int|p-q|$; without densities, the supremum over events). It is a distance between laws, with values in $[0,1]$: for any $g$ with values in $[0,1]$, $|\mathbb E_pg-\mathbb E_qg|\le d_{\rm TV}(p,q)$, and $d_{\rm TV}$ is the smallest possible $\mathbb P(X\ne Y)$ over all ways of coupling $X\sim p$ with $Y\sim q$. Pinsker: with natural logarithms, $d_{\rm TV}(p,q)\le\sqrt{\mathrm{KL}(p\|q)/2}$, in either KL direction because $d_{\rm TV}$ is symmetric. (Proof idea: recording only whether the event $A=\{p\gt q\}$ occurs keeps $d_{\rm TV}$ unchanged and can only lower KL, so the two-point case suffices, a one-variable calculus inequality.)

Worked example. For $p=(0.5,0.5)$, $q=(0.9,0.1)$: $d_{\rm TV}=\tfrac12(0.4+0.4)=0.4$, and Pinsker gives $0.4\le\sqrt{0.511/2}=0.505$ and $0.4\le\sqrt{0.368/2}=0.429$. A trust region $\mathrm{KL}\le\epsilon$ therefore caps every event probability change at $\sqrt{\epsilon/2}$. If two laws of a whole data sequence are within $d_{\rm TV}=\epsilon$, then every event, such as "the test point is covered", changes probability by at most $\epsilon$; this compares laws, not the realised samples.

$f$-divergences generalise both: for convex $f$ with $f(1)=0$, $D_f(p\|q)=\sum_iq_if(p_i/q_i)=\mathbb E_q[f(p/q)]\ge0$ (Jensen), defined when $p_i=0$ wherever $q_i=0$. $f(w)=w\log w$ gives KL, $f(w)=\tfrac12|w-1|$ gives $d_{\rm TV}$, and $f(w)=\tfrac12(w-1)^2$ gives half the Pearson $\chi^2$ divergence $\sum_i(p_i-q_i)^2/q_i$ (for the example above, $\chi^2=0.4^2/0.9+0.4^2/0.1=1.78$). The Wasserstein-1 distance for laws on $\mathbb R$ with finite first absolute moments is $W_1(p,q)=\inf\mathbb E|X-Y|$ over couplings $=\sup\{\mathbb E_pg-\mathbb E_qg:\ g\ \text{1-Lipschitz}\}$ measures how far mass must move: for point masses at $0$ and $\epsilon\gt0$, $d_{\rm TV}=1$ and $\mathrm{KL}=\infty$, but $W_1=\epsilon$. Its 1-Lipschitz "critics" are why Lipschitz networks appear in Wasserstein GANs.

Definition — Mutual information; the Gaussian formula
$I(X;Y)=H(X)-H(X\mid Y)=\mathrm{KL}\big(p(x,y)\,\|\,p(x)p(y)\big)\ge0$: symmetric, zero iff $X$ and $Y$ are independent, the expected uncertainty reduction about $X$ from observing $Y$. For $y=f+\varepsilon\in\mathbb R^t$ with $f\sim\mathcal N(0,K)$ and independent $\varepsilon\sim\mathcal N(0,\sigma^2I)$ with $\sigma\gt0$: $y\sim\mathcal N(0,K+\sigma^2I)$ and $y\mid f\sim\mathcal N(f,\sigma^2I)$, so
$$I(y;f)=h(y)-h(y\mid f)=\tfrac12\log\det\big(2\pi e(K+\sigma^2I)\big)-\tfrac12\log\det\big(2\pi e\,\sigma^2I\big)=\tfrac12\log\det\big(I+\sigma^{-2}K\big).$$
The maximum information gain $\gamma_T=\max_{x_1,\dots,x_T\in D}\tfrac12\log\det(I+\sigma^{-2}K_T)$ maximises over query designs (repeated inputs allowed); assume finite $D$, or compact $D$ with a continuous kernel, to ensure a maximiser exists, and use a supremum otherwise. It depends on the kernel, the domain, the noise parameter ($\lambda$ in Module 3) and $T$, not on data.

Worked example. Unit prior variances, $\sigma^2=0.25$ (so $\sigma^{-2}K=4K$). Two uncorrelated points: $\tfrac12\ln\det(5I)=\tfrac12\ln25=1.609$ nats. Correlation $0.5$: $\det\begin{bmatrix}5&2\\2&5\end{bmatrix}=21$, $\tfrac12\ln21=1.522$: correlated measurements tell us less. The same point twice: $\det\begin{bmatrix}5&4\\4&5\end{bmatrix}=9$, $\tfrac12\ln9=\tfrac12\ln(1+2\cdot4)=1.099$, exactly one measurement with noise variance $\sigma^2/2$. On a one-point domain $\gamma_T=\tfrac12\ln(1+4T)$: $0.80$, $1.86$, $3.00$ nats for $T=1,10,100$. Such slow growth is best seen on a logarithmic axis, where equal vertical steps mean equal ratios.

Where this is used
$\gamma_t$: Module 1; entropy, conditional entropy, the Gaussian log-det formula, nats: Module 3. Expected entropy reduction (entropy search): Module 4. $\beta_t$ on a log scale, nats: Module 5. Entropy temperature and $H\le\log n$: Module 7. $L^1$ as twice total variation: Module 8; the initial divergence $\le\log|\mathcal A|$: Module 8. KL, TV and support between action distributions: Module 9; Pinsker: Module 9; weighted maximum likelihood, EM and Bregman projections: Module 9; $f$-divergences and $\chi^2$: Module 9. Predictive entropy $H(\hat S_{t+1})$: Module 10. Wasserstein critics: Module 12, Module 13. $d_{\rm TV}$ between data-sequence laws: Module 15.

Practice — Compare distributions, not individual samples

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S22 — Easy: Entropy of a fair and a biased coin

Using natural logarithms, compute the entropy of a fair Bernoulli variable and a Bernoulli variable with success probability $1/4$. Use $H(p)=-p\ln p-(1-p)\ln(1-p)$.

Review if needed: this section and discrete probability laws.

Show hint
Both outcomes contribute, even if you call one of them a failure.
Show worked solution
  1. For the fair coin, both terms are $-(1/2)\ln(1/2)$, so $H(1/2)=\ln2\approx0.693147$ nats.
  2. For the biased coin, $H(1/4)=-(1/4)\ln(1/4)-(3/4)\ln(3/4)\approx0.562335$ nats.
  3. The fair coin has higher entropy because its result is less predictable. These numbers use natural logs; base-two logs would express the same information in bits.
Exercise C.S23 — Medium: Total variation and directional KL

For $p=(0.75,0.25)$ and $q=(0.5,0.5)$, compute $\operatorname{TV}(p,q)$, $D_{\rm KL}(p\|q)$ and $D_{\rm KL}(q\|p)$.

Review if needed: this section and discrete probability laws.

Show hint
TV is half the sum of absolute probability differences. In KL, the first distribution supplies the averaging weights.
Show worked solution
  1. $\operatorname{TV}(p,q)=(|0.75-0.5|+|0.25-0.5|)/2=0.25$.
  2. $D_{\rm KL}(p\|q)=0.75\ln(1.5)+0.25\ln(0.5)\approx0.130812$ nats.
  3. Reversing the weights gives $D_{\rm KL}(q\|p)=0.5\ln(2/3)+0.5\ln2\approx0.143841$. The unequal answers show that KL is directional; it is not a distance metric.
Exercise C.S24 — Hard: Support mismatch and a useless KL bound

Let $p=(1,0)$ and $q=(0.5,0.5)$. Compute both KL directions and TV, using the convention $0\ln(0/q)=0$. Apply Pinsker to the finite KL direction.

Review if needed: this section and discrete probability laws.

Show hint
Positive mass in the first law where the second law is zero makes that KL infinite.
Show worked solution
  1. $D_{\rm KL}(p\|q)=1\ln(1/0.5)+0=\ln2\approx0.693147$.
  2. $D_{\rm KL}(q\|p)=+\infty$, because the second outcome has $q$-probability $0.5$ but $p$-probability zero. TV is still finite: $(0.5+0.5)/2=0.5$.
  3. Pinsker gives $\operatorname{TV}(p,q)\le\sqrt{\ln2/2}\approx0.588705$, consistent with $0.5$ but not exact. Applying it to the infinite direction would provide no information.

9. Quantiles, Value-at-Risk & CVaR

Start here — Read a tail with discrete atoms

A quantile is a threshold; CVaR is a tail average. With probability mass at a threshold, selecting the worst $10\%$ can require taking only part of that mass. Draw or list the CDF before using a conditional-tail shortcut.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review CDFs and atoms.

Definition — Quantile function, VaR and CVaR (cost convention)
For a cost $Z$ (large is bad) with CDF $F$, the quantile function (generalised inverse) $F^{-1}(u)=\inf\{z:\ F(z)\ge u\}$, $u\in(0,1)$, handles flat pieces and jumps of $F$. For a confidence level $\alpha\in(0,1)$,
$$\operatorname{VaR}_\alpha(Z)=F^{-1}(\alpha),\qquad \operatorname{CVaR}_\alpha(Z)=\frac1{1-\alpha}\int_\alpha^1\operatorname{VaR}_u(Z)\,du ,$$
the average of the worst $(1-\alpha)$-fraction of outcomes. If $U\sim\mathcal U(0,1)$, then $F^{-1}(U)$ has the law of $Z$ (inverse-transform sampling), so $\mathbb E[Z]=\int_0^1F^{-1}(u)\,du$: $\operatorname{CVaR}_\alpha(Z)\to\mathbb E[Z]$ as $\alpha\to0$, and $\operatorname{CVaR}_\alpha(Z)\to\operatorname{ess\,sup}Z$ as $\alpha\to1$.
0 0.7 1 u 1 5 quantile function F⁻¹(u) α = 0.85 tail area 0.55

Worked example (splitting an atom). Let $Z\in\{0,1,5\}$ with probabilities $0.7,0.2,0.1$. Then $F^{-1}(u)=0$ on $(0,0.7]$, $1$ on $(0.7,0.9]$ and $5$ on $(0.9,1)$ (figure), and $\mathbb E[Z]=\int_0^1F^{-1}=0.2+0.5=0.7$. At $\alpha=0.85$: $\operatorname{VaR}_{0.85}=1$ and $\operatorname{CVaR}_{0.85}=\frac{0.05\cdot1+0.1\cdot5}{0.15}=3.67$. The atom at $1$ occupies $u\in(0.7,0.9]$ and only its top $0.05$ lies in the tail: it is included fractionally. The naive $\mathbb E[Z\mid Z\ge\operatorname{VaR}]=0.7/0.3=2.33$ is wrong here; it equals CVaR when $F$ is continuous at the quantile.

Theorem — Rockafellar–Uryasev formula
For integrable $Z$ and $\alpha\in(0,1)$,
$$\operatorname{CVaR}_\alpha(Z)=\min_{\nu\in\mathbb R}\Big\{\nu+\frac{1}{1-\alpha}\,\mathbb E\big[(Z-\nu)^+\big]\Big\},$$
with the minimum attained at every $\alpha$-quantile, in particular at $\nu=\operatorname{VaR}_\alpha(Z)$. Why: the objective is convex in $\nu$ with right and left derivatives $1-\mathbb P(Z\gt\nu)/(1-\alpha)$ and $1-\mathbb P(Z\ge\nu)/(1-\alpha)$. A convex function of one variable is minimal where the left derivative is $\le0\le$ the right derivative, i.e. where $\mathbb P(Z\gt\nu)\le1-\alpha\le\mathbb P(Z\ge\nu)$: exactly at the $\alpha$-quantiles. Module 1 derives it step by step (walkthrough). In the example, $\nu=1$ gives $1+\frac{0.1\cdot4}{0.15}=3.67$, while $\nu=0$ gives $4.67$ and $\nu=5$ gives $5$.

Gaussian CVaR. For $Z\sim\mathcal N(\mu,\sigma^2)$, $\operatorname{VaR}_\alpha=\mu+\sigma\Phi^{-1}(\alpha)$ and, from $\mathbb E[Z\mid Z\ge q]=\mu+\sigma\varphi(z_q)/(1-\Phi(z_q))$ with $z_q=(q-\mu)/\sigma$, $\operatorname{CVaR}_\alpha=\mu+\sigma\,\varphi(\Phi^{-1}(\alpha))/(1-\alpha)$; at $\alpha=0.95$ this is $\mu+2.063\,\sigma$. Papers that write $\alpha$ for the tail fraction print $\mu+\sigma\varphi(\Phi^{-1}(\alpha))/\alpha$, the same quantity since $\varphi$ is even. In a Gaussian cost critic written $\mathcal N(Q_c^\pi,V_c^\pi)$ the second argument $V_c^\pi$ is a variance (take its square root), not the cost value function.

Caveat — tail conventions
(1) $\alpha$ may be the confidence level (worst $1-\alpha$ averaged, $\alpha\to1$ risk-averse; used here and in Modules 1 and 8) or the tail fraction ($\alpha\to0$ risk-averse). (2) For costs the bad tail is the upper one; for rewards it is the lower one, and CVaR of a reward averages the lowest outcomes. Check the formula, not the words.

Chance, expectation and CVaR constraints. For an episode cost $Z$: $\mathbb E[Z]\le d$ constrains the average, $\mathbb P(Z\gt0)\le\delta$ (equivalently $\operatorname{VaR}_{1-\delta}(Z)\le0$) the frequency of failure, and $\operatorname{CVaR}_\alpha(Z)\le d$ frequency and magnitude together. If $Z=100$ with probability $0.01$ and $0$ otherwise: $\mathbb E[Z]=1$, $\mathbb P(Z\gt0)=0.01$ and $\operatorname{CVaR}_{0.95}(Z)=\frac{0.01\cdot100}{0.05}=20$: with budget $d=2$ and level $\delta=0.05$ the mean and chance constraints hold, and only the CVaR constraint ($20\gt2$) sees the rare catastrophe. A finite-horizon chance constraint $\mathbb P(\forall t\in\{1,\dots,T\}:\ s_t\in\mathcal S)\ge1-\delta$, with $T\ge1$ and $s_0\in\mathcal S$ almost surely, concerns the whole trajectory; it is implied by per-step levels $\delta/T$ (Section 6) and by an expected number of violations $\mathbb E[N]\le\delta$ (Section 1).

Definition — Coherent risk measure
A risk measure $\rho$ on costs is coherent if it is monotone ($Z\le Z'$ a.s. $\Rightarrow\rho(Z)\le\rho(Z')$), translation equivariant ($\rho(Z+c)=\rho(Z)+c$), positively homogeneous ($\rho(\lambda Z)=\lambda\rho(Z)$ for $\lambda\ge0$) and subadditive ($\rho(Z+Z')\le\rho(Z)+\rho(Z')$). CVaR is coherent; VaR is not subadditive: two independent costs equal to $100$ with probability $0.04$ (else $0$) each have $\operatorname{VaR}_{0.95}=0$, but their sum is $0$ only with probability $0.96^2=0.9216\lt0.95$, so $\operatorname{VaR}_{0.95}(\text{sum})=100$.

Empirical quantiles, robust summaries and expectiles. Sorting $N$ observed values gives empirical quantiles (median, quartiles). The interquartile mean averages the middle $50\%$ and is robust to outlying runs; a bootstrap interval resamples the $N$ runs with replacement many times and reads off percentiles of the recomputed statistic. These describe one random experiment; they are not bounds on the next network or seed. Quantiles minimise an asymmetric absolute loss: for integrable $Z$, $\operatorname{VaR}_\tau\in\arg\min_m\mathbb E[(\tau-\mathbf 1\{Z\lt m\})(Z-m)]$, where the minimisers form an interval of $\tau$-quantiles whose smallest point is $F^{-1}(\tau)$ (for $Z\in\{0,1\}$ with probabilities $\tfrac12,\tfrac12$ and $\tau=\tfrac12$ every $m\in[0,1]$ minimises). For $\mathbb E[Z^2]\lt\infty$ the $\tau$-expectile minimises the asymmetric squared loss $\mathbb E[|\tau-\mathbf 1\{Z\lt m\}|(Z-m)^2]$. $\tau=\tfrac12$ gives the mean, and as $\tau\to1$ ($\tau\to0$) the expectile tends to the essential supremum (infimum), which is how offline RL approximates a maximum (minimum) over actions seen in the data.

Where this is used
Quantile integration $\int_\alpha^1\operatorname{VaR}_u\,du$, atom splitting and $\operatorname{ess\,sup}$: Module 1, Module 1; coherent risk: Module 1. $\operatorname{CVaR}_\alpha$ of a cumulative cost, tail conventions and the Gaussian closed form: Module 8, Module 8. Finite-horizon chance constraints: Module 7. Interquartile means with bootstrap intervals; expectile regression: Module 9, Module 9. Medians and quartiles over random seeds: Module 12.

Practice — Read a tail with discrete atoms

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S25 — Easy: Find the first threshold reaching the target

A loss $L$ equals $0$, $10$, $100$ with probabilities $0.8$, $0.15$, $0.05$. Using $\operatorname{VaR}_\alpha(L)=\inf\{z:F_L(z)\ge\alpha\}$, find VaR at levels $0.8$, $0.9$ and $0.95$.

Review if needed: this section and CDFs and atoms.

Show hint
Write the cumulative masses at the three possible loss values. The definition uses $\ge$, not $\gt$.
Show worked solution
  1. The CDF reaches $0.8$ at loss $0$, $0.95$ at loss $10$, and $1$ at loss $100$.
  2. The first threshold reaching $0.8$ is $0$, so $\operatorname{VaR}_{0.8}=0$. The first reaching $0.9$ is $10$, so $\operatorname{VaR}_{0.9}=10$.
  3. At level $0.95$, equality at $10$ suffices, giving $\operatorname{VaR}_{0.95}=10$. This quantile convention matters at atoms: a $5\%$ chance of loss $100$ remains beyond that threshold.
Exercise C.S26 — Medium: Take the worst ten percent, including part of an atom

For the same law, compute $\operatorname{CVaR}_{0.9}(L)$ as the average of the worst $10\%$ of probability mass. Compare it with $\mathbb E[L]$ and with $\mathbb E[L\mid L\ge10]$.

Review if needed: this section and CDFs and atoms.

Show hint
Use all $5\%$ mass at $100$ and only $5\%$ of the $15\%$ mass at $10$.
Show worked solution
  1. The worst $10\%$ consists of mass $0.05$ at $100$ and mass $0.05$ at $10$. Its mean is $(0.05(100)+0.05(10))/0.1=55$.
  2. The full mean is $0.8(0)+0.15(10)+0.05(100)=6.5$.
  3. Conditioning on $L\ge10$ instead uses $20\%$ mass and gives $6.5/0.2=32.5$. It is not CVaR: the atom at VaR must be split to select precisely the desired tail mass.
Exercise C.S27 — Hard: Verify the optimisation formula at a kink

For the same loss, minimise $g(\nu)=\nu+10\mathbb E[(L-\nu)^+]$, where $z^+=\max(z,0)$. Find its slopes on $(-\infty,0)$, $(0,10)$, $(10,100)$ and $(100,\infty)$, and its minimum.

Review if needed: this section and CDFs and atoms.

Show hint
Away from atoms, $g'(\nu)=1-10\mathbb P(L\gt\nu)$. Track how the tail probability jumps.
Show worked solution
  1. The tail probabilities on the four intervals are $1$, $0.2$, $0.05$ and $0$, so the slopes are respectively $-9$, $-1$, $0.5$ and $1$.
  2. The function decreases up to $10$ and increases after $10$, so its minimum occurs at the kink $\nu=10$.
  3. Only loss $100$ contributes a positive excess there: $\mathbb E[(L-10)^+]=0.05(90)=4.5$. Hence $g(10)=10+10(4.5)=55$, agreeing with the split-tail calculation. A derivative need not exist at the minimiser.

10. Binomial Tails, Hypothesis Tests & Exchangeability

Start here — Separate a test outcome from its coverage

A test specifies which random data would count against a fixed hypothesis. With no failures in four independent runs, the likelihood under failure probability $p$ is $(1-p)^4$. This is a probability of data given a parameter, not a posterior probability of that parameter.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review conditional probabilities.

Definition — Bernoulli, binomial, product probability
A Bernoulli$(p)$ variable is $1$ (a "success", e.g. a safe run) with probability $p$ and $0$ otherwise: mean $p$, variance $p(1-p)$. The number of successes in $n$ independent trials is binomial, $K\sim\mathrm{Bin}(n,p)$, with $\mathbb P(K=k)=\binom nkp^k(1-p)^{n-k}$ for $k=0,\dots,n$, mean $np$ and variance $np(1-p)$: by independence each particular pattern of $k$ successes and $n-k$ failures has probability $p^k(1-p)^{n-k}$, and the binomial coefficient $\binom nk=\frac{n!}{k!\,(n-k)!}$ (with $0!=1$) counts the ways to choose which $k$ of the $n$ trials succeed. $P^N$ denotes the law of $N$ independent samples from $P$ (the product probability), so "$P^N\{\dots\}$" is a probability over the whole training set.

Worked example (binomial tails and the scenario bound). For $n=20$, $p=0.1$: $\mathbb P(K=0)=0.9^{20}=0.122$ and $\mathbb P(K\le1)=0.122+20\cdot0.1\cdot0.9^{19}=0.392$. For the scenario bound, let $\theta_N^\ast$ solve a convex program in $d$ decision variables whose $N$ constraints are sampled i.i.d. from $P$, and let $V(\theta)$ be the probability that the constraint of a fresh sample is violated by $\theta$. If every such program is feasible (with nonempty interior) and has a unique solution (or a fixed tie-break rule), the scenario theorem (Module 15) gives $P^N\{V(\theta_N^\ast)\gt\epsilon\}\le\sum_{i=0}^{d-1}\binom Ni\epsilon^i(1-\epsilon)^{N-i}$, exactly the lower tail $\mathbb P(\mathrm{Bin}(N,\epsilon)\le d-1)$: for $d=2$, $\epsilon=0.05$ it is $0.037$ at $N=100$, and $N=181$ is the first sample size that brings it below $10^{-3}$. The scalar case $d=1$ is the max-of-samples bound of Section 6; keeping the $(r+1)$-th largest of $m$ samples instead of the maximum changes the failure probability to $\mathbb P(\mathrm{Bin}(m,\gamma)\le r)$.

Definition — Clopper–Pearson confidence bounds
Given $k$ successes in $n$ trials, the one-sided lower confidence bound at level $1-\alpha$ is the $p_L$ with $\mathbb P_{p_L}(K\ge k)=\alpha$ ($p_L=0$ if $k=0$): the smallest success probability under which $k$ or more successes are still not too surprising. The upper bound $p_U$ solves $\mathbb P_{p_U}(K\le k)=\alpha$ for $k\lt n$ ($p_U=1$ if $k=n$). Both are valid for every $n$, not just asymptotically (hence "exact"): $\mathbb P_p(p_L\le p)\ge1-\alpha$ for every $p$. A two-sided interval at level $1-\alpha$ uses $\alpha/2$ on each side. At the extremes the one-sided bounds have closed forms: all successes gives $p_L=\alpha^{1/n}$ (solve $p^n=\alpha$), no success gives $p_U=1-\alpha^{1/n}$.

Worked example. $95$ successes in $100$ at $\alpha=0.05$: $p_L=0.898$, whereas the normal approximation $0.95-1.645\cdot0.0218=0.914$ is over-optimistic. $100$ successes in $100$ at $\alpha=0.001$: $p_L=0.001^{1/100}=0.933$; with $n=10^4$ it is $0.99931$, approaching $1$ only like $1-\ln(1/\alpha)/n$. In randomized smoothing the certified radius is $\sigma\Phi^{-1}(p_L)$, e.g. $0.5\cdot\Phi^{-1}(0.933)=0.75$.

Definition — Hypothesis test, false alarm, missed detection
A test decides between a null hypothesis $H_0$ (e.g. "the system has not changed") and an alternative $H_1$, rejecting $H_0$ when a statistic $T$ exceeds a threshold $c$. A false alarm (type I error) rejects a true $H_0$; its probability $\mathbb P_{H_0}(T\gt c)\le\alpha$ is the significance level. A missed detection (type II error) keeps a false $H_0$, with probability $\beta$; $1-\beta$ is the power. Raising $c$ trades false alarms for missed detections. Rejecting $H_0$ does not assign a posterior probability to $H_1$ (Section 2).

Worked example (an event trigger). Under the null model the standardised residual $r_t=(y_t-\mu_{t-1}(x_t))/\sqrt{\sigma_{t-1}^2(x_t)+\sigma^2}$ is $\mathcal N(0,1)$. Triggering a reset when $|r_t|\gt3$ gives false-alarm probability $0.0027$ per step, i.e. $2.7$ expected false alarms in $1000$ unchanged steps. To keep the probability of any false alarm over $1000$ steps below $0.05$ (union bound), test each step at $5\cdot10^{-5}$: $|r_t|\gt\Phi^{-1}(1-2.5\cdot10^{-5})=4.06$.

Lemma — Neyman–Pearson (statement)
For simple hypotheses $H_0:X\sim p_0$ and $H_1:X\sim p_1$, among all tests with false-alarm probability at most $\alpha$ the most powerful one rejects when the likelihood ratio $p_1(x)/p_0(x)$ exceeds a threshold chosen to make the level exactly $\alpha$ (randomising on ties). Example: for $\mathcal N(0,1)$ against $\mathcal N(\mu_1,1)$ with $\mu_1\gt0$ the ratio $e^{\mu_1x-\mu_1^2/2}$ increases in $x$, so the best test rejects when $x\gt\Phi^{-1}(1-\alpha)$ ($1.645$ at $\alpha=0.05$). Two-sample tests ask whether two samples share one law; the kernel maximum mean discrepancy $\mathrm{MMD}^2(P,Q)=\mathbb Ek(X,X')+\mathbb Ek(Y,Y')-2\,\mathbb Ek(X,Y)$ ($X,X'\sim P$, $Y,Y'\sim Q$ independent) vanishes iff $P=Q$ for a squared-exponential kernel, and its empirical version is compared with a threshold calibrated by permuting the pooled sample.
Definition — Exchangeability
$(Z_1,\dots,Z_n)$ is exchangeable if its joint law is unchanged by every permutation of the indices. i.i.d. implies exchangeable; the converse fails: draws without replacement from an urn are exchangeable but dependent. In conformal prediction the calibration scores and the test score must be jointly exchangeable.
Theorem — Uniform ranks and split-conformal coverage
If $S_1,\dots,S_{n+1}$ are exchangeable and almost surely distinct (e.g. i.i.d. with a continuous law), the rank of the test score $S_{n+1}$ among all $n+1$ scores is uniform on $\{1,\dots,n+1\}$. With $S_{(k)}$ the $k$-th smallest calibration score, $\mathbb P(S_{n+1}\le S_{(k)})=\frac k{n+1}$ for $1\le k\le n$, so $k=\lceil(n+1)(1-\alpha)\rceil$ gives coverage at least $1-\alpha$. If $\alpha\lt1/(n+1)$, then $k=n+1$: no calibration score is high enough, the threshold is $+\infty$ and the prediction set is everything (coverage $1$); using the largest score instead would cover only $n/(n+1)$. Proof. Permuting the scores does not change their joint law, so $S_{n+1}$ is equally likely to occupy each of the $n+1$ ranks; $S_{n+1}\le S_{(k)}$ iff its rank is at most $k$. $\square$ Example: $n=19$, $\alpha=0.1$: $k=18$ and the coverage is $18/20=0.9$.

Beta laws, the probability integral transform and conditional coverage. For $a,b\gt0$, the Beta$(a,b)$ law on $[0,1]$ has density proportional to $x^{a-1}(1-x)^{b-1}$, mean $\frac a{a+b}$ and variance $\frac{ab}{(a+b)^2(a+b+1)}$ (Beta$(1,11)$ was the posterior in Section 2).

If $S$ has a continuous CDF $F$, then $F(S)\sim\mathcal U(0,1)$ (the probability integral transform), and the $k$-th smallest of $n$ i.i.d. uniforms is Beta$(k,n+1-k)$. So if the calibration and test scores are i.i.d. with a continuous CDF $F$ (the score function fixed beforehand, e.g. fitted on separate data) and $1\le k\le n$, the coverage of one fixed calibration set, $C=\mathbb P(S_{n+1}\le S_{(k)}\mid S_1,\dots,S_n)=F(S_{(k)})$, is Beta$(k,n+1-k)$ whatever $F$ is.

Exchangeability with almost surely distinct scores fixes only its mean $\mathbb E[C]=\frac k{n+1}$ (with $S_2=1-S_1$, $S_1\sim\mathcal U(0,1)$, the pair is exchangeable, but for $n=k=1$ the coverage is $\mathbf 1\{S_1\ge\tfrac12\}$, not uniform).

For $n=19$, $k=18$: mean $0.9$, standard deviation $0.065$, and $\mathbb P(C\lt0.8)=19\cdot0.8^{18}\cdot0.2+0.8^{19}=0.083$. Testing on $m=2000$ fresh points adds binomial noise; by total variance (Section 2) the measured coverage has variance $\operatorname{Var}C+\mathbb E[C(1-C)]/m=0.00429+0.00004$, which equals $p(1-p)\frac{n+1+m}{m(n+2)}$ with $p=\frac k{n+1}$: the calibration set, not the test set, dominates the spread.

Where this is used
Jointly exchangeable calibration and test data: Module 1, Module 15 (uniform ranks, Beta$(k,n+1-k)$). Event triggers as tests of a stationary null model: Module 5. MMD-based tests: Module 7. Binomial tails and $P^N$ in scenario bounds: Module 11, Module 15. Monte Carlo confidence bounds in smoothing certificates: Module 13; one-sided Clopper–Pearson and $\alpha^{1/n}$: Module 15. Beta-binomial spread of simulated coverage: Module 15.

Practice — Separate a test outcome from its coverage

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise C.S28 — Easy: Exactly two failures

Four independent runs each fail with probability $0.1$. Find the probability of exactly two failures and the probability of at least one failure.

Review if needed: this section and conditional probabilities.

Show hint
For exactly two failures, count the possible pairs. For at least one, take the complement of zero failures.
Show worked solution
  1. A specified pair failing while the other two pass has probability $0.1^2(0.9)^2=0.0081$.
  2. There are $\binom42=6$ distinct pairs, so exactly two failures has probability $6(0.0081)=0.0486$.
  3. Zero failures has probability $0.9^4=0.6561$. Thus at least one has probability $1-0.6561=0.3439$. Independence is what permits these products.
Exercise C.S29 — Medium: Zero failures still leaves uncertainty

Observe zero failures in $100$ independent runs with a fixed unknown failure probability $p$. Find the exact one-sided $95\%$ upper confidence limit by solving $(1-p_U)^{100}=0.05$. Interpret it without assigning a posterior probability to $p$.

Review if needed: this section and conditional probabilities.

Show hint
Take the hundredth root. The confidence statement describes the repeated-data procedure.
Show worked solution
  1. Solving gives $p_U=1-0.05^{1/100}\approx0.029513$.
  2. If a proposed true $p$ exceeds this limit, seeing zero failures would have probability below $0.05$. Inverting these tests gives the upper confidence-limit procedure.
  3. The parameter $p$ is fixed in this frequentist statement; the data and reported limit are random. This is not a claim that the fixed $p$ has posterior probability $0.95$ of lying below the observed limit. In particular, zero observed failures does not prove $p=0$.
Exercise C.S30 — Hard: Ranks, ties and marginal coverage

There are $19$ calibration scores and one future score. Assume all $20$ scores are jointly exchangeable and distinct almost surely. A prediction rule accepts the future point when its score is at most the $18$th smallest calibration score. Find its marginal acceptance probability. Why need this not be $90\%$ for each subgroup?

Review if needed: this section and conditional probabilities.

Show hint
Among all $20$ scores the future score has a uniform rank. Compare that rank with $18$.
Show worked solution
  1. Exchangeability and absence of ties make the future score's rank uniform on $1,\dots,20$.
  2. It is at most the $18$th calibration score exactly when its overall rank is at most $18$. Hence acceptance probability is $18/20=0.9$.
  3. This averages over calibration data and the future point. For example, two equally common subgroups with conditional coverages $0.8$ and $1$ also average to $0.9$. Marginal coverage alone does not guarantee either subgroup's target, or conditional coverage for the observed calibration set.

Interactive: Concentration & Gaussian Conditioning

Part A draws 2000 independent samples of size up to $400$ from a law on $[0,1]$ (seeded, so results reproduce) and compares the observed frequency of a deviation $|\bar X_N-m|\ge t$ with Chebyshev, Hoeffding and the normal approximation. Part B conditions a 2-D Gaussian with standard deviations $\sigma_x,\sigma_y$ and correlation $\rho$ (Section 1) on $y=y_0$ with the Schur complement and checks the formula against the samples that fall in a thin slab around $y_0$.

A. Sample means versus Chebyshev and Hoeffding

Left: histogram of the 2000 sample means at the chosen $N$, the band $m\pm t$ (green) and the normal approximation $\mathcal N(m,\sigma^2/N)$ (grey). Right: $\mathbb P(|\bar X_N-m|\ge t)$ against $N$, both axes logarithmic: observed frequencies (teal; hollow on the floor when no run deviated), Chebyshev $\sigma^2/(Nt^2)$ (orange), Hoeffding $2e^{-2Nt^2}$ (blue), normal approximation (grey, dashed); the red line marks the chosen $N$.

B. Conditioning a 2-D Gaussian: Schur complement versus slicing

Left: $3000$ seeded samples of $(x,y)$ with $x=\sigma_xz_1$, $y=\sigma_y(\rho z_1+\sqrt{1-\rho^2}z_2)$; ellipses of Mahalanobis radius $1$ and $2$ (blue); the slab $|y-y_0|\lt0.1\sigma_y$ (orange points); the regression line $x=\mathbb E[x\mid y]$ (purple, dashed); the conditional mean (red ring). Right: prior density of $x$ (grey, dashed), conditional density from the Schur complement (orange) and histogram of $x$ over the slab.

What to look for. (A) The true deviation probability stays below both bounds, for every law: they are guarantees for anything with values in $[0,1]$. The observed frequency only estimates it from $2000$ runs, so where a bound drops below about $10^{-3}$ one or two deviating runs can lift the observed frequency above it (seed 1, Bernoulli$(0.5)$, $N=215$, $t=0.15$: $1/2000$ against Hoeffding's $1.3\cdot10^{-4}$). Chebyshev decays like $1/N$ and Hoeffding exponentially; at $t=0.1$ Chebyshev is still the tighter one up to $N\approx191$ for the uniform law (whose variance $1/12$ is far below the worst case $1/4$ that Hoeffding implicitly assumes), after which Hoeffding wins. The normal approximation follows the dots for smooth laws but is not a bound: for Bernoulli$(0.1)$ at $N=10$ the true deviation probability is $0.61$ while the approximation says $0.29$.

Gaussian conditioning panel. Dragging $y_0$ moves the conditional mean along the purple line but leaves the conditional variance $\sigma_x^2(1-\rho^2)$ unchanged; at $\rho=0$ the observation changes nothing, and as $|\rho|\to1$ it pins $x$ down. The slab statistics agree with the formula up to sampling error plus a small bias, because a slab of finite width is not the line $y=y_0$ (at the default settings the exact slab mean is $0.997$ instead of $1$, far inside the sampling error of about $0.06$); far in the tail the slab empties, and only the formula still works.

From the mathematics to a real decision

A probability calculation becomes useful when it changes an action. A sensor reading alone does not say whether to stop a process: that also depends on how often trouble occurs, how the sensor behaves, and what each action costs. This chapter follows that chain from assumptions to a decision, then transfers it to calibration and repeated operation. All numbers below define hypothetical models; they are not measurements of a particular machine.

What you will learn to do
  • Combine a base rate and a sensor model before choosing an action.
  • Translate posterior uncertainty into a tolerance statement with physical units.
  • Distinguish independent measurement noise from uncertainty shared by repeated measurements.
  • Separate a model probability, a statistical confidence statement, and an all-outcomes guarantee.

Begin with the decision, then describe the uncertainty

Imagine a small conveyor carrying sealed packages. A hidden fault can cause a package to jam the next station. Before releasing each package, a sensor either raises an alarm or stays quiet. Inspection takes time but finds and removes the fault perfectly in this simplified model. The operator must decide whether to inspect after seeing the sensor result.

Write $F$ for the event that the package is faulty and $A$ for an alarm. Assume the fault probability is $0.04$, the sensor alarms on $90\%$ of faulty packages, and it alarms on $8\%$ of sound packages. These are three different quantities: $\mathbb P(F)=0.04$, $\mathbb P(A\mid F)=0.90$, and $\mathbb P(A\mid F^c)=0.08$. The complement $F^c$ means sound. No independence assumption between the fault and the alarm is appropriate: detecting dependence is the sensor's purpose.

Measure consequences in a chosen unit of equivalent operating cost. Inspection costs $6$ units, whether or not a fault is present. Releasing a faulty package costs $30$ units; releasing a sound one costs zero. These values express the hypothetical operator's priorities. A different loss for a jam would legitimately produce a different decision from the same probabilities.

Definition — Conditional expected loss

After information $I$, let $p_I=\mathbb P(F\mid I)$. The conditional expected losses of inspection and release are $6$ and $30p_I$. Minimising expected loss therefore means inspecting when $30p_I\gt6$, or equivalently $p_I\gt0.20$. At equality both actions have the same expected loss in this model.

This threshold does not promise that a released package is sound. It specifies a tradeoff in expectation. If even one jam is unacceptable, replace the objective with that requirement before calculating; a small expected cost is a different mathematical claim.

Worked example 1 — Should an alarm trigger inspection?

Step 1: construct joint probabilities. Multiplication converts a conditional rate into a fraction of all packages. Faulty packages with alarms have probability $0.04(0.90)=0.036$. Sound packages with alarms have probability $0.96(0.08)=0.0768$. Adding these disjoint possibilities gives $\mathbb P(A)=0.1128$.

Step 2: condition on what was observed. Among the packages that alarm, the faulty fraction is the faulty-and-alarm probability divided by the entire alarm probability:

$$\mathbb P(F\mid A)=\frac{0.036}{0.1128}\approx0.31915,\qquad \mathbb P(F\mid A^c)=\frac{0.04(0.10)}{1-0.1128}=\frac{0.004}{0.8872}\approx0.004509.$$

The second calculation uses missed faults and all quiet packages. Each denominator describes the information actually available at the decision time.

Step 3: compare actions in each information state. After an alarm, release has expected loss $30(0.31915)\approx9.5745$ units, exceeding inspection's $6$. After silence, release costs only about $0.1353$ units in expectation. The optimal rule is therefore inspect on an alarm and release after silence.

Step 4: evaluate the entire rule. Inspection occurs with probability $0.1128$. A faulty package is released only when the fault is missed, with probability $0.004$. The expected cost per package is consequently

$$6(0.1128)+30(0.004)=0.7968\text{ cost units}.$$

Always releasing costs $30(0.04)=1.2$ units per package; always inspecting costs $6$. The sensor-based rule improves the stated objective compared with either constant action. This conclusion depends on the inspection model, cost values, and probabilities remaining applicable to the incoming packages.

Common wrong approach — Reverse the conditional probability

“The sensor catches $90\%$ of faults, so an alarm means a $90\%$ fault probability” reverses the conditioning. The $90\%$ denominator is all faulty packages; the decision concerns all alarming packages. Repair the calculation by constructing both routes into the alarm group. Even a capable detector can produce many false alarms when sound packages are common.

Worked example 2 — Combine calibration measurements without double counting

Now consider a displacement sensor with one unknown fixed offset $\theta$, measured in millimetres. Before calibration, model $\theta\sim\mathcal N(0,4)$; the variance has units $\mathrm{mm}^2$. Two reference measurements satisfy $y_1=\theta+\varepsilon_1$ and $y_2=\theta+\varepsilon_2$, where the noises have distributions $\mathcal N(0,1)$ and $\mathcal N(0,4)$. Assume both noises are independent of one another and of $\theta$. The hypothetical observed values are $y_1=2$ mm and $y_2=-1$ mm.

Step 1: identify the shared quantity. Both measurements observe the same offset. They are independent conditional on $\theta$, but not independent before conditioning: $\operatorname{Cov}(y_1,y_2)=\operatorname{Var}(\theta)=4\ \mathrm{mm}^2$. Averaging the readings as if they were unrelated draws of the offset would misdescribe the experiment.

Step 2: collect the quadratic terms. The prior density and two likelihoods multiply. Ignoring positive factors that do not depend on $\theta$, their negative twice-log-density is

$$\frac{\theta^2}{4}+(2-\theta)^2+\frac{(-1-\theta)^2}{4}=\frac32\theta^2-\frac72\theta+\frac{17}{4}.$$

The coefficient of $\theta^2$ is the posterior precision, the reciprocal of variance. Completing the square gives $\tfrac32(\theta-\tfrac76)^2$ plus a constant. Thus the posterior mean is $m=7/6$ mm and the posterior variance is $s^2=2/3\ \mathrm{mm}^2$. Equivalently, add precisions $1/4+1+1/4=3/2$ and precision-weighted observations $0/4+2/1-1/4=7/4$, then divide $7/4$ by $3/2$.

Step 3: specify the correction and requirement. Subtract $c=m$ from future readings to correct this fixed offset. The residual offset $\theta-c$ has posterior mean zero and standard deviation $s=\sqrt{2/3}\approx0.8165$ mm. Suppose the requirement concerns the offset alone: its magnitude should be at most $2$ mm with posterior probability at least $0.98$.

$$\mathbb P(|\theta-c|\le2\mid y_1,y_2)=2\Phi\!\left(\frac{2}{\sqrt{2/3}}\right)-1\approx0.98569.$$

Step 4: interpret the result. The correction meets that posterior requirement under the Gaussian model. The statement concerns uncertainty in the fixed offset, conditional on these readings. A new noisy reading contains fresh measurement noise as well; its error needs a predictive variance, considered in the exercises. Neither statement is a hard bound: Gaussian distributions allow arbitrarily large errors.

Apply the model to a changed decision

Attempt each question before opening its hint. State the event or random variable being bounded before choosing a formula. These applications deliberately change a decision or assumption rather than ask for another isolated probability calculation.

Exercise C.B1 — Easy: A new production line changes the inspection decision

Keep the sensor rates and costs from example 1, but change the incoming fault probability to $0.01$. Should an alarm still trigger inspection? Compare always releasing with retaining the old inspect-on-alarm rule.

Review: conditional probability and Bayes; the inspection decision.

Show hint

Recompute both routes into an alarm, then compare the posterior fault probability with $0.20$.

Show worked solution

The alarm probability is $0.01(0.90)+0.99(0.08)=0.0882$. Its fault probability is $0.009/0.0882=5/49\approx0.10204$. Release after an alarm costs $30(5/49)\approx3.0612$, below $6$, so release is preferred. Silence has an even smaller fault probability, $0.001/0.9118\approx0.001097$, and also favours release. Always releasing costs $30(0.01)=0.30$ units. The old rule costs $6(0.0882)+30(0.001)=0.5592$. Reusing an unchanged rule can therefore increase expected cost after the base rate changes.

Exercise C.B2 — Medium: Offset uncertainty is not reading uncertainty

After example 2, a new measurement has zero-mean Gaussian noise $\varepsilon_{\mathrm{new}}\sim\mathcal N(0,1\ \mathrm{mm}^2)$, independent of the offset and calibration noises. After subtracting the posterior mean offset, what is the probability that its total error lies within $2$ mm? Does the $0.98$ requirement hold for this new quantity?

Review: Gaussian conditioning and standardisation; the calibration model.

Show hint

The total error is $\theta-m+\varepsilon_{\mathrm{new}}$. Add the variances of these independent Gaussian terms conditional on the calibration data.

Show worked solution

The predictive mean is zero and variance is $2/3+1=5/3\ \mathrm{mm}^2$. Its standard deviation is $\sqrt{5/3}\approx1.2910$ mm. Standardisation gives probability $2\Phi(2/\sqrt{5/3})-1\approx0.87866$. It fails the $0.98$ requirement. Correcting the mean offset removes neither uncertainty about that offset nor fresh measurement noise. The earlier $0.98569$ probability answered a narrower question.

Exercise C.B3 — Hard: Repeated use shares the same uncertain offset

Average $100$ new corrected readings of the same fixed displacement after example 2. Their zero-mean noises are mutually independent and independent of the offset and calibration noises, each with variance $1\ \mathrm{mm}^2$. Find the average's error variance and its limiting value as the number of readings grows. Explain why the variance is not $(5/3)/100$.

Review: variance and covariance; shared offset uncertainty.

Show hint

Write the average error as one shared offset error plus an average of fresh noises. Only the second term is averaged away.

Show worked solution

For $n$ readings the average error is $(\theta-m)+n^{-1}\sum_{i=1}^n\varepsilon_i$. Independence gives variance $2/3+1/n$, hence $203/300\approx0.67667\ \mathrm{mm}^2$ at $n=100$. The limiting variance is $2/3$, with standard deviation about $0.8165$ mm. Distinct reading errors have covariance $2/3$ because they share the offset. Dividing each reading's entire variance by $100$ incorrectly assumes those errors are independent. Better calibration, rather than more repeated readings of an unknown displacement, is needed to reduce this uncertainty floor.

Exercise C.B4 — Hard: Plan a batch reliability requirement

A revised inspection process has an assumed per-package escape probability $q$. Require the probability of any escaped fault in a batch of $50$ packages to be at most $0.02$. Find a sufficient bound on $q$ without independence. If escapes are independent with equal probability, find the exact largest $q$. Does example 1's $q=0.004$ meet either bound?

Review: union bounds and simultaneous events; the escape probability.

Show hint

Use a union bound first. Under independence, compute the probability that all $50$ packages avoid an escape.

Show worked solution

The union bound gives batch failure probability at most $50q$, so $q\le0.02/50=0.0004$ is sufficient. Independence gives exact probability $1-(1-q)^{50}$; solving $1-(1-q)^{50}\le0.02$ yields $q\le1-0.98^{1/50}\approx0.000403973$. Example 1 exceeds both limits. Under independence its batch failure probability is $1-0.996^{50}\approx0.18160$. The slightly larger exact allowance relies on independence; the union-bound allowance does not. These are calculations under assumed rates, not confidence bounds inferred from test data.

Recall the claim before trusting the number

Close the examples and explain why an alarm's accuracy is insufficient to choose an action, why two calibration readings can share uncertainty despite independent noises, and why an offset tolerance differs from a reading tolerance. Then identify which quantity is averaged over packages, which is uncertain after calibration, and which is an event covering an entire batch.

The reusable sequence is: define the decision and units; state the random model; condition on available information; compare the quantities required by the objective; write the conclusion with its assumptions. Continue to Gaussian-process regression to extend Gaussian conditioning across inputs, or to risk constraints to compare average and tail requirements. When the decision changes a physical trajectory, Primer D's state-space models supply the next layer.

Exercises

These cumulative problems connect several ideas. If a step feels too large, return to the section practice route, where each topic has an Easy, Medium and Hard problem with a separate hint, worked solution and prerequisite review link.

Exercise C.1 — Monte Carlo estimates and zero failures

In $200$ independent simulated episodes, $14$ contain at least one violation. (a) Estimate the violation probability and its standard error. (b) Give the normal-approximation 95% interval. (c) Now suppose $0$ of $200$ episodes violate. What does the standard-error formula say, and what exact one-sided 95% upper bound can you give instead?

Show answer

(a) $\hat p=14/200=0.07$ and $\mathrm{SE}=\sqrt{0.07\cdot0.93/200}=\sqrt{0.0003255}\approx0.0180$.

(b) $0.07\pm1.96\sqrt{0.0003255}\approx[0.035,\,0.105]$, using a normal approximation to the sampling distribution of $\hat p$; these are approximate interval limits, not exact finite-sample confidence limits.

(c) $\hat p=0$ gives $\mathrm{SE}=0$, which says nothing. If the true rate is $p$, all $200$ episodes are clean with probability $(1-p)^{200}$. Values of $p$ that make this smaller than $0.05$ are rejected, leaving $p\le1-0.05^{1/200}\approx0.0149\approx3/200$ (since $\ln20\approx3$): the one-sided Clopper–Pearson bound. With 95% confidence the rate is below 1.5%, not zero.

Exercise C.2 — An alarm, a base rate and many steps

A change detector has false-alarm probability $0.01$ and detection probability $0.9$ per step, and a change occurs at a given step with prior probability $0.02$. (a) Compute $\mathbb P(\text{change}\mid\text{alarm})$. (b) Over $500$ steps without any change, how many false alarms do you expect, and what is the probability of at least one if the steps are independent? (c) Which per-step level keeps the probability of any false alarm in $500$ steps at most $0.05$ without assuming independence, and which two-sided Gaussian threshold on a standardised residual does it give?

Show answer

(a) Bayes: $\frac{0.9\cdot0.02}{0.9\cdot0.02+0.01\cdot0.98}=\frac{0.018}{0.0278}=\frac{90}{139}\approx0.647$. About one alarm in three is false even though the false-alarm rate is only 1%.

(b) By linearity, $500\cdot0.01=5$ expected false alarms; with independence, $\mathbb P(\ge1)=1-0.99^{500}\approx0.993$.

(c) Union bound: $\alpha=0.05/500=10^{-4}$ per step guarantees $\mathbb P(\text{any false alarm})\le500\cdot10^{-4}=0.05$ under any dependence. For a standard Gaussian residual, the exact two-sided threshold is $q=\Phi^{-1}(1-0.5\cdot10^{-4})\approx3.89$, and the alarm is $|r_t|\gt q$. For a guaranteed numerical implementation, use $q$ itself or the conservative threshold $3.89060$; rounding down to $3.89$ gives a per-step false-alarm probability strictly greater than $10^{-4}$.

Exercise C.3 — A Gaussian posterior and a safety probability

Prior $f\sim\mathcal N(0,1)$. Four measurements $y_i=f+\varepsilon_i$ with $\varepsilon_i\sim\mathcal N(0,0.25)$ i.i.d. and independent of $f$ have mean $\bar y=0.9$. (a) Compute the posterior mean and variance with precision addition. (b) Compute $\mathbb P(f\lt0.5\mid\text{data})$. (c) Is $f\ge0.3$ certified by the lower bound $\mu-2\sigma$, and what is the posterior probability that this bound fails?

Show answer

(a) $\bar y$ has noise variance $0.25/4=0.0625$, i.e. precision $16$. Posterior precision $1+16=17$, variance $1/17\approx0.0588$ (standard deviation $1/\sqrt{17}\approx0.2425$), mean $(1\cdot0+16\cdot0.9)/17=72/85\approx0.847$.

(b) $\mathbb P(f\lt0.5\mid\text{data})=\Phi\big((0.5-72/85)/(1/\sqrt{17})\big)\approx0.076$; the standardized argument is approximately $-1.431$.

(c) $\mu-2\sigma=72/85-2/\sqrt{17}\approx0.362\gt0.3$, so yes. The bound fails with posterior probability $\Phi(-2)\approx0.023$. This is a Bayesian statement inside the model; a whole run of such decisions needs a union bound over them (Section 6).

Exercise C.4 — How many runs, and which $R$?

Outcomes lie in $[0,1]$. (a) How many independent samples guarantee $|\bar X_N-m|\lt0.05$ with probability at least $0.99$, using Chebyshev with the worst-case variance and using Hoeffding? (b) Give a valid sub-Gaussian parameter for noise uniform on $[-0.2,0.2]$ and compare it with the standard deviation. (c) Why is noise uniform on $[0,0.2]$ not covered by (b)?

Show answer

(a) Chebyshev with $\operatorname{Var}\le\tfrac14$: $\frac{1/4}{N\cdot0.0025}\le0.01$ gives $N\ge10000$. Hoeffding: $2e^{-2N\cdot0.0025}\le0.01$ gives $N\ge\ln(200)/0.005\approx1059.7$, so $1060$.

(b) Hoeffding's lemma: $R=(b-a)/2=0.2$. The standard deviation is $\sigma=0.4/\sqrt{12}\approx0.115$; for the uniform law the smallest valid $R$ actually equals $\sigma$ (table in Section 5), so the lemma is conservative by a factor $\sqrt3$.

(c) Its mean is $0.1\ne0$. Sub-Gaussianity (and Hoeffding's lemma) require zero mean; the bias $0.1$ must be modelled separately, e.g. as a known offset or an unknown constant in the model.

Exercise C.5 — KL, total variation and Pinsker

Let $p=(0.6,0.3,0.1)$ and $q=(0.4,0.4,0.2)$. (a) Compute $\mathrm{KL}(p\|q)$, $\mathrm{KL}(q\|p)$ and $d_{\rm TV}(p,q)$. (b) Check Pinsker's inequality in both directions. (c) For $q'=(0.5,0.5,0)$, which of $\mathrm{KL}(p\|q')$ and $\mathrm{KL}(q'\|p)$ is infinite, and what does that mean for a trust region?

Show answer

(a) $\mathrm{KL}(p\|q)=0.6\ln1.5+0.3\ln0.75+0.1\ln0.5\approx0.2433-0.0863-0.0693=0.0877$; $\mathrm{KL}(q\|p)=0.4\ln\tfrac23+0.4\ln\tfrac43+0.2\ln2\approx-0.1622+0.1151+0.1386=0.0915$; $d_{\rm TV}=\tfrac12(0.2+0.1+0.1)=0.2$.

(b) $\sqrt{0.0877/2}\approx0.209\ge0.2$ and $\sqrt{0.0915/2}\approx0.214\ge0.2$: Pinsker holds and is nearly tight here.

(c) $\mathrm{KL}(p\|q')=\infty$ because $p$ puts mass $0.1$ where $q'$ puts none; $\mathrm{KL}(q'\|p)=0.5\ln\tfrac56+0.5\ln\tfrac53\approx0.164$ is finite. A constraint $\mathrm{KL}(\text{new}\|\text{old})\le\epsilon$ forbids the new policy to use any action the old one excludes.

Exercise C.6 — VaR, CVaR and the Gaussian shortcut

Episode costs are $Z\in\{0,2,10\}$ with probabilities $0.8,0.15,0.05$. (a) Compute $\mathbb E[Z]$, $\mathbb P(Z\gt0)$, $\operatorname{VaR}_{0.9}(Z)$ and $\operatorname{CVaR}_{0.9}(Z)$, the latter both as a tail average and from Rockafellar–Uryasev at $\nu=\operatorname{VaR}_{0.9}$. (b) Compute $\operatorname{CVaR}_{0.9}$ of a Gaussian with the same mean and variance. (c) Which of $\mathbb E[Z]\le1$, $\mathbb P(Z\gt0)\le0.25$, $\operatorname{CVaR}_{0.9}(Z)\le5$ hold?

Show answer

(a) $\mathbb E[Z]=0.15\cdot2+0.05\cdot10=0.8$ and $\mathbb P(Z\gt0)=0.2$. $F(0)=0.8\lt0.9\le F(2)=0.95$, so $\operatorname{VaR}_{0.9}=2$. The worst $10\%$ consists of the $0.05$ at $10$ and $0.05$ of the atom at $2$: $\operatorname{CVaR}_{0.9}=(0.5+0.1)/0.1=6$. RU: $2+\frac{0.05\cdot8}{0.1}=6$.

(b) $\operatorname{Var}Z=0.15\cdot4+0.05\cdot100-0.8^2=4.96$, so the standard deviation is $\sigma=\sqrt{4.96}\approx2.227$. For the Gaussian, $\operatorname{CVaR}_{0.9}=0.8+\sigma\,\varphi(\Phi^{-1}(0.9))/0.1\approx0.8+2.227\,\varphi(1.2816)/0.1\approx0.8+2.227\cdot1.755\approx4.71$. This is about $1.3$ below the true discrete tail average. The displayed inputs and final value are rounded approximations.

(c) The mean ($0.8\le1$) and chance ($0.2\le0.25$) constraints hold; the CVaR constraint fails ($6\gt5$), although the Gaussian shortcut ($4.71\le5$) would wrongly accept it.

Exercise C.7 — Conformal coverage is itself random

Split conformal prediction uses $n=19$ calibration scores and one test score, all i.i.d. with a continuous law, and $\alpha=0.1$. (a) Which order statistic is the threshold, and what is the marginal coverage? (b) The coverage $C$ of one fixed calibration set is random: give its law, mean, standard deviation and $\mathbb P(C\lt0.8)$. (c) The coverage is measured on $m=2000$ fresh test points. What is the standard deviation of the measured coverage, and which source of randomness dominates?

Show answer

(a) $k=\lceil20\cdot0.9\rceil=18$, the second largest score; by the rank argument the coverage is $18/20=0.9$.

(b) $C=F(S_{(18)})\sim$ Beta$(18,2)$: mean $0.9$, variance $\frac{18\cdot2}{20^2\cdot21}=3/700\approx0.00429$, standard deviation $\sqrt{3/700}\approx0.065$. $C\lt0.8$ iff at least $18$ of $19$ uniforms lie below $0.8$: $19\cdot0.8^{18}\cdot0.2+0.8^{19}\approx0.083$, about one calibration set in twelve.

(c) Given $C$, the test count is Bin$(2000,C)$. Total variance: $\operatorname{Var}C+\mathbb E[C(1-C)]/2000=3/700+(3/35)/2000=303/70000\approx0.004329$, standard deviation $\sqrt{303/70000}\approx0.0658$. The calibration set dominates; the finite test set adds only 1% to the variance.

Further Reading

ResourceWhat to read it for
Blitzstein & Hwang, Introduction to Probability, 2nd ed., CRC Press 2019 (free online)Sections 1–3: random variables, conditioning, Markov chains, inequalities; many worked problems
Pishro-Nik, Introduction to Probability, Statistics, and Random Processes, Kappa Research 2014 (open access)Sections 1, 4, 6, 10: CDFs and mixed laws, the multivariate normal, confidence intervals, hypothesis tests
Rasmussen & Williams, Gaussian Processes for Machine Learning, MIT Press 2006 (free PDF)Section 4: Gaussian identities (Appendix A), GP regression (Ch. 2), marginal likelihood (Ch. 5)
Vershynin, High-Dimensional Probability, Cambridge University Press 2018; 2nd ed. 2026 (free PDF)Section 5: sub-Gaussian variables, Hoeffding and Chernoff bounds
Lattimore & Szepesvári, Bandit Algorithms, Cambridge University Press 2020 (free PDF)Sections 5 and 7: Ch. 5 (concentration, sub-Gaussianity), Ch. 3 (martingales, stopping times), Ch. 20 (the method of mixtures)
Williams, Probability with Martingales, Cambridge University Press 1991Section 7: filtrations, conditional expectation, optional stopping, done rigorously
Levin & Peres (with Wilmer), Markov Chains and Mixing Times, 2nd ed., AMS 2017 (free PDF)Section 3: stationary distributions, convergence, transience
Cover & Thomas, Elements of Information Theory, 2nd ed., Wiley 2006Section 8: entropy, KL, mutual information, differential entropy of Gaussians
Rockafellar & Uryasev, “Optimization of conditional value-at-risk”, Journal of Risk 2(3), 2000Section 9: the CVaR minimisation formula
Wasserman, All of Statistics, Springer 2004Sections 6 and 10: confidence intervals, tests, the bootstrap, compactly
Angelopoulos & Bates, “A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification”, arXiv 2021Section 10: exchangeability, split conformal, conditional coverage

Flashcards