Refresher in Statistics
APM_51438_EP · Year 1 · Period 1
Introduction and overview
Independent study notes organised around the catalog label “Refresher in Statistics”, Year 1 · Period 1 — not an official syllabus or course-selection plan.
Undergraduate refresherPreparation for ML
The question this page answers
When does a number computed on a finite sample justify a claim about future data?
A test with 99% sensitivity can still leave only a 17% probability of disease after a positive result when prevalence is 1% and specificity is 95%: the denominator matters. A sample mean can look stable while its uncertainty estimate is wrong because observations share a source. Both problems return when evaluating a classifier or asking whether adding a graph actually helps a language model.
The approach is empirical first: calculate the counts, simulate the estimator, inspect the residuals — then state the model and its assumptions.
Source labels and study budget
- Catalog record: the SynapseS 2026–2027 sheet for
APM_51438_EPreports 12 h CTD (lectures–tutorials), period X-3A-P1 (17 Sep–18 Dec 2026), English, with Marine Le Morvan listed as responsible; total workload and ECTS are not displayed, so none is asserted. Its description, prerequisite and syllabus tabs are empty, and its assessment section for the LLGA track is empty too (details). - Suggested study budget: about 36 h for a full pass — the 12 h in class plus about 24 h of self-study, chapter by chapter in the session plan. This is an adjustable study estimate, not a teaching allocation or ECTS equivalence.
- Working background: basic algebra and calculus, vectors and matrices, Python/NumPy. See the Refresher in Computer Science if arrays are the obstacle.
What you will be able to do
- Handle probabilities, random variables, common distributions and random-vector notation.
- State the LLN and CLT, and recognize when their assumptions fail.
- Build estimators by moments or maximum likelihood; evaluate bias, variance, MSE.
- Construct confidence intervals and tests; distinguish what is concluded from what is not.
- Fit and diagnose a linear regression.
- Compute Bayesian updates; separate posterior uncertainty from frequentist coverage.
- Find the stationary law of a finite Markov chain and see why the Gibbs sampler targets it.
- Name the statistical tool behind an ML formula and the extra assumptions it needs.
Session plan
12 h in class = 4 sessions of 3 h. The volume is the one of the SynapseS 2026–2027 sheet (12 h CTD); the sheet publishes no session-by-session programme, so the split below is our proposal for covering the core of these notes in that time. Level 1 = foundations (reviews, definitions, first worked examples), 2 = core methods, 3 = advanced theory; the level never goes down from one session to the next.
| Session | Hours | Level | Content | Practice |
|---|---|---|---|---|
| 1 | 3 h | 1 | ch. 1 The language of probability: conditioning, independence, Bayes’ formula, Simpson’s paradox | Ex. 1–2 |
| 2 | 3 h | 1 | ch. 2 Random variables: CDF, change of variables, moments and MGF, Markov and Chebyshev, conditional expectation, finite Markov chains and the Gibbs sampler | Ex. 4, 9, 12 |
| 3 | 3 h | 2 | ch. 4 Convergence and limit theorems: LLN, CLT, delta method, bootstrap | Ex. 3; lab: the CLT by simulation (example 4.7) |
| 4 | 3 h | 2 | ch. 5 Parametric estimation: bias-variance, maximum likelihood, Fisher information, moments and plug-in | Ex. 10–11 |
Self-study, outside the 12 h (about 24 h; ≈ 36 h in all): ch. 3 Common distributions (≈ 3 h, Ex. 5; section 3.4 optional) · ch. 6 Intervals and tests (≈ 5 h, Ex. 6, 8, 13; required before Period 2) · ch. 7 Linear regression (≈ 5 h, Ex. 14–15; required before Period 2) · ch. 8 Bayesian statistics (≈ 3 h, Ex. 7) · ch. 9 From statistics to ML (≈ 3 h) · exit checkpoint and capstone evaluation kit (≈ 1 h) · ch. 10 Missing data (≈ 4 h, Ex. 16).
Read ch. 3 before session 3: chapters 4 and 5 use its table and the gamma sums of section 3.2.
Notation
Site-wide conventions: see the notation page; deviations on this page:
- \mathbb{P} is a probability measure and P the data distribution: a dataset D_n=\{(X_i,Y_i)\}_{i=1}^n is drawn iid from P. In section 2.7, P is a transition matrix, as for random walks on graph pages.
- With one argument, \ell(\theta) is the log-likelihood, maximized, and L(\theta) the likelihood (chapters 3, 5, 8, 9). A loss has two arguments, \ell(\hat y,y), prediction first, and is minimized. The risk and empirical risk are R(f) and \hat R_n(f) (chapter 9).
- Chapter 7 writes p for the number of regression coefficients, intercept included, so X\in\mathbb{R}^{n\times p}; elsewhere d counts features.
- \pi is a prior density in chapter 8 and a stationary law in section 2.7.
Before you start
Try the three positioning checks below before the first session and before choosing a route. A correct answer includes the reasoning or the assumption, not just the final number.
- Conditioning. A population of 10,000 people has a disease prevalence of 1%, and a test has sensitivity 99% and specificity 95%. How many true and false positives should you expect, and what fraction of the positive results concern infected people? If the denominator is unclear, read Bayes’ formula and the worked tree.
- Sampling uncertainty. You observe independent Gaussian variables with known \sigma=2, sample size n=25 and mean \bar x=10.4. Compute a 95% confidence interval for the mean, and say what happens to its width at n=100. Would the same calculation be justified for 25 strongly related nodes of a single graph? Review convergence and the CLT and confidence intervals.
- Likelihood and evaluation. For Bernoulli observations (1,0,1,1,0), write the likelihood and find its maximizer. Does a lower training negative log-likelihood establish that a larger model predicts better? Review MLE derivations, ERM and cross-entropy.
Positioning answers
- The expected counts are 99 true positives and 495 false positives, so the fraction of positives that are infected is 99/(99+495)=1/6\approx 0.167 — not the sensitivity.
- The standard error is 2/\sqrt{25}=0.4 and the interval is [9.616,11.184]. At n=100 the width halves. Related nodes do not provide 25 independent observations, so the covariance terms cannot be dropped.
- The likelihood is L(p)=p^3(1-p)^2, maximized at \hat p=3/5=0.6. A lower training loss alone is insufficient, because the selection used the training data: evaluate on held-out units.
Reading route
This page is a reading proposal, not a compulsory linear course.
- Core — the 12 h in class. The four sessions of the session plan cover conditioning and Bayes’ formula, random variables and moments, the LLN, the CLT and the bootstrap and estimation. Read the distribution table before session 3 and keep it as a reference. Useful checks are exercises 1–4 and 9–12.
- Self-study before Machine Learning — about 17 h. Chapter 3 (≈ 3 h), then confidence intervals and p-values in chapter 6 (≈ 5 h), least squares and regression diagnostics in chapter 7 (≈ 5 h), and the bridge to ML in chapter 9 with the exit checkpoint (≈ 4 h). Exercises 5, 6, 8 and 13–15 check these chapters. Chapters 6 and 7 are required before Period 2: its courses assume tests, intervals and regression.
- Deepen — about 7 h, as the next problem requires. Bayesian statistics (≈ 3 h, exercise 7) and missing data (≈ 4 h, exercise 16), together with the proofs of the in-class chapters, Gaussian conditioning and the measure-theoretic layer.
- Skip or defer — when the checks already pass. Do not restart from σ-algebras just because they come first: if the three positioning checks are secure, skim chapters 1 and 2 (except Markov chains) and spend the time saved on chapter 9 and the exit checkpoint. Exact ANOVA, the full distribution table and the missing-data papers can remain references until needed.
When a section is weak, reproduce its numerical example, run the code, and then attempt the corresponding exercise before reading the solution. The completion criterion is evidence you can reproduce — a calculation, a simulation, a failure mode — not hours logged.
Contents
- Introduction and overview
- Before you start
- Reading route
- 1. The language of probability
- 2. Random variables
- 3. Common probability distributions
- 4. Convergence and limit theorems
- 5. Parametric estimation
- 6. Confidence intervals and tests
- 7. Linear regression
- 8. Bayesian statistics
- 9. From statistics to machine learning
- 10. Missing data: mechanisms, baselines and research
- Exercises
- Exit checkpoint and connections
- Sources and scope
- Projects and assessment
- References
1. The language of probability
Before the σ-algebra: a number. A spam filter with 95% recall on mail that is only 2% spam yields, per 10,000 messages, ≈190 caught spam but ≈490 false positives if specificity is 95%. The model is not malfunctioning: the conditional probability was misread. Likewise, 99% aggregate accuracy can hide 20% error on a rare class. ML is a calculus of uncertainty; this chapter gives the vocabulary to avoid swapping denominators.
What breaks if you skip this chapter Three confusions to avoid: swapping P(A\mid B) for P(B\mid A) (the medical-test and spam mistakes), believing that pairwise independence implies mutual independence, and reading a p-value as the probability that H_0 is true. These traps return in A/B tests, classifier calibration and LLM evaluation.
Definition 1.1 — Measurable space A measurable space is a pair (\Omega, \mathcal{F}) where \Omega is the set of possible outcomes (the sample space) and \mathcal{F} \subseteq 2^\Omega is a σ-algebra: a family of subsets of \Omega containing \Omega, stable under complementation and countable unions. The elements of \mathcal{F} are the events: exactly the questions to which the model allows a probabilistic answer.
The σ-algebra as “available information” \mathcal{F} encodes information: if the observer of a die roll only sees the parity, the relevant σ-algebra is \{\varnothing, \{1,3,5\}, \{2,4,6\}, \Omega\}. This reading powers filtrations, conditioning and the missing-data models of chapter 10.
Definition 1.2 — Probability A probability on (\Omega,\mathcal{F}) is a map \mathbb{P} : \mathcal{F} \to [0,1] such that \mathbb{P}(\Omega)=1 and, for any family (A_n) of pairwise disjoint events: \mathbb{P}\Big(\bigcup_{n} A_n\Big) = \sum_{n} \mathbb{P}(A_n) \qquad (\sigma\text{-additivity}). The triple (\Omega, \mathcal{F}, \mathbb{P}) is a probability space.
Proposition 1.3 — Immediate properties For all events A, B:
- \mathbb{P}(A^c) = 1 - \mathbb{P}(A);
- monotonicity: A \subseteq B \Rightarrow \mathbb{P}(A) \leq \mathbb{P}(B);
- union bound: \mathbb{P}(A \cup B) \leq \mathbb{P}(A) + \mathbb{P}(B).
Proof. For the complement, write \Omega = A \sqcup A^c; σ-additivity gives 1 = \mathbb{P}(A) + \mathbb{P}(A^c).
For monotonicity, decompose B = A \sqcup (B \setminus A) with \mathbb{P}(B\setminus A) \geq 0.
For the union bound, decompose A \cup B = A \sqcup (B \setminus A) and note that B \setminus A \subseteq B. ∎
1.1. Conditioning and the law of total probability
Definition 1.4 — Conditional probability If \mathbb{P}(B) > 0: \mathbb{P}(A \mid B) = \dfrac{\mathbb{P}(A \cap B)}{\mathbb{P}(B)}. The map A \mapsto \mathbb{P}(A \mid B) is itself a probability on (\Omega, \mathcal{F}): the probability rules apply to it.
Theorem 1.5 — Law of total probability If (B_i)_{i \in I} is a finite or countable partition of \Omega into events of nonzero probability, then for every event A: \mathbb{P}(A) \;=\; \sum_{i \in I} \mathbb{P}(A \mid B_i)\,\mathbb{P}(B_i).
Proof. The sets A \cap B_i are pairwise disjoint (because the B_i are) and their union is A (because \bigcup_i B_i = \Omega). By σ-additivity and then by definition of conditioning, \mathbb{P}(A) = \sum_i \mathbb{P}(A \cap B_i) = \sum_i \mathbb{P}(A \mid B_i)\,\mathbb{P}(B_i). ∎
The multiplication formula follows directly: \mathbb{P}(A \cap B) = \mathbb{P}(A \mid B)\mathbb{P}(B), iterated for three events as \mathbb{P}(C \mid A \cap B)\,\mathbb{P}(B \mid A)\,\mathbb{P}(A). This is the skeleton of Markov models and LLM autoregression.
1.2. Independence
Definition 1.6 — Independence (three levels)
- Events: A and B are independent if \mathbb{P}(A \cap B) = \mathbb{P}(A)\,\mathbb{P}(B). A family is mutually independent if every finite subfamily factorizes; pairwise is not enough.
- Variables: 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 intervals A, B; with densities, f(x,y) = f_X(x) f_Y(y) almost everywhere.
- Conditional: “the future is independent of the past given the present” applies the same factorization to conditional probabilities — the Markov chains of section 2.7.
Two classic pitfalls Independence ≠ incompatibility. Two disjoint events with nonzero probabilities are never independent: \mathbb{P}(A \cap B) = 0 \neq \mathbb{P}(A)\mathbb{P}(B).
Pairwise ≠ mutual. Two fair dice: A = “the first die is even”, B = “the second die is even”, C = “the sum is even”. Then \mathbb{P}(A)=\mathbb{P}(B)=\mathbb{P}(C)=\tfrac12, every pair factorizes (\mathbb{P}(A \cap B) = \tfrac14, etc.), but \mathbb{P}(A \cap B \cap C) = \tfrac14 \neq \tfrac18: the family is not mutually independent.
1.3. Bayes’ formula
Theorem 1.7 — Bayes’ formula If (B_i)_{i\in I} is a finite or countable partition of \Omega into events of nonzero probabilities, then for every event A of nonzero probability: \mathbb{P}(B_k \mid A) \;=\; \frac{\mathbb{P}(A \mid B_k)\,\mathbb{P}(B_k)}{\sum_{i\in I} \mathbb{P}(A \mid B_i)\,\mathbb{P}(B_i)}.
Proof. Numerator: \mathbb{P}(A \mid B_k)\mathbb{P}(B_k) = \mathbb{P}(A \cap B_k) = \mathbb{P}(B_k \mid A)\mathbb{P}(A). Denominator: law of total probability (theorem 1.5) applied to \mathbb{P}(A). Divide. ∎
Example 1.8 — Medical test: keep the denominator visible A disease affects 1% of the population — this is the prior. A test has a sensitivity of 99% (\mathbb{P}(+ \mid M) = 0.99) and a specificity of 95% (\mathbb{P}(- \mid M^c) = 0.95, hence \mathbb{P}(+ \mid M^c) = 0.05). A patient tests positive, and Bayes’ formula gives \mathbb{P}(M \mid +) = \frac{0.99 \times 0.01}{0.99 \times 0.01 + 0.05 \times 0.99} = \frac{0.0099}{0.0594} \approx 0.167. Only 17%! Out of 10,000 people, expect about 99 true positives but also about 495 false positives. Intuition fails when it ignores the prevalence; Bayes’ formula puts it back in the denominator automatically.
Example 1.9 — Anti-spam filter (naive Bayes, with numbers) Suppose 40% of emails are spam, that the word “free” appears in 70% of spam emails and in 5% of legitimate emails. With the partition \{S, S^c\}, Bayes’ formula gives \mathbb{P}(S \mid \text{word}) = \frac{0.7 \times 0.4}{0.7 \times 0.4 + 0.05 \times 0.6} = \frac{0.28}{0.31} \approx 0.90. With several words assumed independent given the class, the likelihoods multiply: this is the naive Bayes classifier, a useful text baseline. Note the generative direction of the reasoning: estimate \mathbb{P}(\text{email} \mid S) from class-conditional counts, then invert it with Bayes to obtain the quantity of interest, \mathbb{P}(S \mid \text{email}).
Example 1.10 — Classification: Bayes rule To classify an input x among K classes under the 0–1 loss, the optimal prediction is \hat{y}(x) \;=\; \arg\max_k\; \mathbb{P}(y = k \mid x) \;\overset{\text{Bayes}}{=}\; \arg\max_k\; \underbrace{p(x \mid y = k)}_{\text{class-conditional}}\; \underbrace{\mathbb{P}(y = k)}_{\text{prior}}. This predictor is called the Bayes rule; it minimizes the population classification error, and its error rate is the Bayes error, the lowest achievable with this information. The true conditional law is usually unknown: logistic regression and softmax classifiers estimate it. An autoregressive language model also estimates next-token probabilities, but generation may sample instead of taking an argmax, and sequence-level objectives need not coincide with token-level 0–1 loss.
1.4. Simpson’s paradox
Example 1.11 — A correlation that reverses A hospital tests two protocols, A and B. Results (patients cured / treated):
| Group | Protocol A | Protocol B |
|---|---|---|
| Mild cases | 95 / 100 = 95% | 470 / 500 = 94% |
| Severe cases | 80 / 200 = 40% | 8 / 50 = 16% |
| Overall | 175 / 300 = 58% | 478 / 550 = 87% |
A is better within each subgroup, but B is better overall: A received mostly severe cases (200/300), B mostly mild cases (500/550). Severity is a confounding factor the global table mixes in.
Simpson, fairness and ML An aggregate association does not establish a causal effect. A model “neutral on average” may behave differently within subgroups. Inspect subgroup composition and data collection before concluding; adjustment should follow the study design and causal assumptions, not a blanket rule. These issues return in ML evaluation and chapter 10.
Key takeaways — chapter 1
- A σ-algebra is both the set of events and a level of information, and a probability is a σ-additive measure with total mass 1.
- The law of total probability splits an event according to a partition, and Bayes’ formula inverts the conditioning without dropping the prior.
- Mutual independence is strictly stronger than pairwise independence, and independence is not incompatibility.
- Simpson’s paradox shows that an aggregated association can reverse under stratification, so inspect the population composition and possible confounding before concluding.
2. Random variables
Chapter 1 gives probabilities to events, but data are numbers: a loss, a count, a measurement. This chapter models such numbers as random variables, describes them by their distribution, moments and first inequalities, and ends with finite Markov chains.
Definition 2.1 — Random variable A real random variable is a map X : \Omega \to \mathbb{R} such that every set \{X \leq t\} is an event of \mathcal{F}.
It is discrete if its image is at most countable, with a density if there exists f \geq 0 with \int f = 1 such that \mathbb{P}(X \in A) = \int_A f(x)\,dx.
The distribution of X is \mathbb{P}_X : A \mapsto \mathbb{P}(X \in A): probabilities and expectations involving X alone depend on it, not on the underlying sample space.
A standard model for a dataset is an n-tuple X_1, \dots, X_n that is iid (independent, identically distributed) according to an unknown distribution P. This is an assumption to check, not a property automatically shared by rows, graph nodes, tokens or repeated measurements.
2.1. Cumulative distribution function
Definition 2.2 F(t) = \mathbb{P}(X \leq t), defined on \mathbb{R}.
Theorem 2.3 — Characteristic properties F is nondecreasing, right-continuous with left limits, with \lim_{t \to -\infty} F(t) = 0 and \lim_{t \to +\infty} F(t) = 1. Conversely, any function satisfying these properties is the CDF of a unique distribution. Furthermore \mathbb{P}(a \lt X \leq b) = F(b) - F(a) and \mathbb{P}(X = a) = F(a) - F(a^-): F entirely determines the distribution.
Proof. For monotonicity, s \leq t implies \{X \leq s\} \subseteq \{X \leq t\}, so F(s) \leq F(t).
For the difference formula, decompose \{X \leq b\} = \{X \leq a\} \sqcup \{a \lt X \leq b\} and apply additivity.
Right-continuity, the limits and the point mass follow from the continuity of \mathbb{P} along monotone sequences of events (section 3.4), applied to \{X\leq t+1/m\}\downarrow\{X\leq t\}, \{X \leq n\} \uparrow \Omega, \{X \leq -n\} \downarrow \varnothing and \{a - \tfrac1m \lt X \leq a\} \downarrow \{X = a\}. The converse is admitted. ∎
Usage: the inverse simulation method If U \sim \mathcal{U}[0,1] and F is continuous, strictly increasing on its support, then X = F^{-1}(U) has distribution F, since \mathbb{P}(F^{-1}(U) \leq x) = \mathbb{P}(U \leq F(x)) = F(x). A generalized inverse extends the method; rejection sampling is the other classic route.
2.2. Variables with a density: change of variables
Theorem 2.4 — The Jacobian formula Let X have density f_X on an open set D \subseteq \mathbb{R}^d and let g : D \to \mathbb{R}^d be a C^1-diffeomorphism onto its image. Then Y = g(X) has density f_Y(y) \;=\; f_X\big(g^{-1}(y)\big)\,\left|\det J_{g^{-1}}(y)\right|, where J_{g^{-1}} is the Jacobian matrix of g^{-1}.
Proof. Case d=1, g increasing. For every t in the image, \mathbb{P}(Y \leq t) = \mathbb{P}(g(X) \leq t) = \mathbb{P}(X \leq g^{-1}(t)) = F_X(g^{-1}(t)); differentiating (chain rule) gives f_Y(t) = f_X(g^{-1}(t)) \cdot (g^{-1})'(t).
If g is decreasing, the direction of the inequality reverses and the derivative is negative: the absolute value restores the formula.
Vector case. The change-of-variables theorem for multiple integrals brings in |\det J|: local volume is dilated by the Jacobian factor, and a density must compensate inversely for the mass to remain 1. ∎
Example 2.5 — Two transformations to know how to redo
(a) Exponential by inversion. Let U \sim \mathcal{U}[0,1] and start from the target CDF F_X(x) = 1 - e^{-\lambda x} for x \geq 0. Its inverse is F^{-1}(u) = -\tfrac1\lambda\ln(1-u), so the variable X = -\tfrac{1}{\lambda}\ln(1-U) follows an \mathcal{E}(\lambda) distribution. Since 1-U is also uniform on [0,1], one equivalently writes X = -\tfrac1\lambda \ln U.
(b) Gaussian standardization. Let X \sim \mathcal{N}(\mu, \sigma^2) with \sigma>0 and Y = \tfrac{X-\mu}{\sigma}. Here g^{-1}(y) = \sigma y + \mu and (g^{-1})'(y) = \sigma, so the change-of-variables formula gives f_Y(y) = \tfrac{1}{\sigma\sqrt{2\pi}}\, e^{-\frac{(\sigma y + \mu - \mu)^2}{2\sigma^2}} \cdot \sigma = \tfrac{1}{\sqrt{2\pi}}\, e^{-y^2/2}, which is the standard Gaussian density: Y \sim \mathcal{N}(0,1).
2.3. Expectation, moments, moment generating function
Definition 2.6 — Expectation Discrete: \mathbb{E}[X] = \sum_x x\, p(x) if \sum |x| p(x) \lt \infty. With a density: \mathbb{E}[X] = \int x f(x)\,dx if \int |x| f(x)\,dx \lt \infty. More generally \mathbb{E}[h(X)] = \int h \,d\mathbb{P}_X when the expectation is defined—the transfer formula.
Proposition 2.7 — Linearity, positivity, products For integrable variables, \mathbb{E}[aX+bY] = a\,\mathbb{E}[X]+b\,\mathbb{E}[Y] with no independence assumption. Positivity: X \geq 0 \Rightarrow \mathbb{E}[X] \geq 0. Independent integrable variables satisfy X \perp Y \Rightarrow \mathbb{E}[XY] = \mathbb{E}[X]\mathbb{E}[Y].
Proposition 2.8 — Variance and moments \mathrm{Var}(X) = \mathbb{E}[(X-\mathbb{E}X)^2] = \mathbb{E}[X^2] - (\mathbb{E}X)^2; \mathrm{Var}(aX+b) = a^2\mathrm{Var}(X); \mathrm{Var}(aX+bY) = a^2\mathrm{Var}(X) + b^2\mathrm{Var}(Y) + 2ab\,\mathrm{Cov}(X,Y). The k-th moment is \mathbb{E}[X^k]; centered normalized moments of order 3 and 4 are skewness and kurtosis.
Example 2.8b — Discrete X, every step visible Let X\in\{1,2,3\} with probabilities \tfrac12,\tfrac13,\tfrac16: \mathbb{E}[X] = 1\cdot\tfrac12 + 2\cdot\tfrac13 + 3\cdot\tfrac16 = \tfrac53, \qquad \mathbb{E}[X^2] = 1\cdot\tfrac12 + 4\cdot\tfrac13 + 9\cdot\tfrac16 = \tfrac{10}{3}, \mathrm{Var}(X) = \tfrac{10}{3} - \big(\tfrac53\big)^2 = \tfrac{30-25}{9} = \tfrac59. Check: \mathbb{E}[(X-\tfrac53)^2] = (1-\tfrac53)^2\cdot\tfrac12 + (2-\tfrac53)^2\cdot\tfrac13 + (3-\tfrac53)^2\cdot\tfrac16 = \tfrac59.
Definition 2.9 — Moment generating function (MGF) The moment generating function of X is M_X(t) = \mathbb{E}[e^{tX}], assumed finite on an open neighborhood of 0.
Three properties are used throughout.
- (i) Moments are read off by differentiating: M_X^{(k)}(0) = \mathbb{E}[X^k].
- (ii) For independent variables the MGF of a sum factorizes: if X \perp Y, then \boxed{M_{X+Y}(t) = M_X(t)\,M_Y(t)}.
- (iii) An MGF finite around 0 characterizes the distribution.
The standard cases to know are the Bernoulli 1-p+pe^t, the Poisson e^{\lambda(e^t-1)}, the Gaussian e^{\mu t + \sigma^2 t^2/2} and the exponential \tfrac{\lambda}{\lambda - t} for t \lt \lambda.
Proof. For (ii), independence gives \mathbb{E}[e^{t(X+Y)}] = \mathbb{E}[e^{tX}]\,\mathbb{E}[e^{tY}]. For (i), neighborhood-finiteness justifies differentiating under the expectation, and evaluating at t=0 yields the moment. The uniqueness statement (iii) is admitted. ∎
2.4. Basic inequalities
Theorem 2.10 — Markov If X \geq 0 and a > 0: \mathbb{P}(X \geq a) \leq \dfrac{\mathbb{E}[X]}{a}.
Proof. \mathbb{E}[X] \geq \mathbb{E}[X\,\mathbf{1}_{X \geq a}] \geq a\,\mathbb{P}(X \geq a); isolate the probability. ∎
Example 2.10b — Markov with numbers Let X \geq 0 with \mathbb{E}[X]=2. Markov’s inequality bounds \mathbb{P}(X\geq 10)\;\leq\;\frac{2}{10}=0.2. Suppose in addition that \mathrm{Var}(X)=1. On the same event, the inclusion \{X\geq10\}\subseteq\{|X-2|\geq8\} lets Chebyshev take over: \mathbb{P}(X\geq10)\;\leq\;\mathbb{P}(|X-2|\geq8)\;\leq\;\frac{1}{64}\approx0.0156.
Theorem 2.11 — Chebyshev (and Bienaymé) If \mathrm{Var}(X) \lt \infty and t > 0: \mathbb{P}\big(|X - \mathbb{E}X| \geq t\big) \leq \dfrac{\mathrm{Var}(X)}{t^2}.
Proof. Apply Markov to the nonnegative variable Y = (X - \mathbb{E}X)^2 with a = t^2: \mathbb{P}(|X-\mathbb{E}X| \geq t) = \mathbb{P}(Y \geq t^2) \leq \mathbb{E}[Y]/t^2 = \mathrm{Var}(X)/t^2. ∎
Theorem 2.12 — Cauchy-Schwarz For square-integrable X,Y, |\mathbb{E}[XY]| \leq \sqrt{\mathbb{E}[X^2]\,\mathbb{E}[Y^2]}, with equality iff X and Y are linearly dependent in L^2. In particular |\rho_{X,Y}| \leq 1 whenever the correlation is defined.
Proof. For every \lambda \in \mathbb{R}, 0 \leq \mathbb{E}[(X + \lambda Y)^2] = \mathbb{E}[X^2] + 2\lambda\,\mathbb{E}[XY] + \lambda^2\mathbb{E}[Y^2]. If \mathbb{E}[Y^2]>0, this quadratic is nonnegative, hence its discriminant is \leq 0: 4\,\mathbb{E}[XY]^2 - 4\,\mathbb{E}[X^2]\mathbb{E}[Y^2] \leq 0. Equality means some linear combination is zero a.s. The case \mathbb{E}[Y^2]=0 is immediate. ∎
2.5. Covariance, correlation, independence: untangling
Definition 2.13 For square-integrable variables, \mathrm{Cov}(X,Y) = \mathbb{E}[(X-\mathbb{E}X)(Y-\mathbb{E}Y)] = \mathbb{E}[XY] - \mathbb{E}X\,\mathbb{E}Y. If both standard deviations are positive, \rho_{X,Y} = \mathrm{Cov}(X,Y)/(\sigma_X\sigma_Y) \in [-1,1].
Proposition 2.14 — The direction of the implications Independence implies \mathrm{Cov}(X,Y) = 0 whenever the moments exist. The converse is false, for three distinct reasons.
- Uncorrelated yet dependent. Take X uniform on \{-1,0,1\} and Y = X^2: then \mathrm{Cov}(X,Y) = 0 although Y is a deterministic function of X. Linear correlation does not detect nonlinear dependencies.
- Correlation without a causal link. Two variables driven by a common third cause can be highly correlated, as in the Simpson reversal of example 1.11.
- Extreme correlation is affine. If both variances are positive, |\rho| = 1 holds if and only if Y = aX+b almost surely for some a\neq0.
2.6. Random vectors and conditional expectation
For a vector with joint density, marginals integrate out the other variables: f_{X_1}(x_1) = \int f\,dx_2 \dots dx_d. The conditional density is f_{X\mid Y}(x \mid y) = f(x,y)/f_Y(y) when f_Y(y)>0, and Bayes reads in densities: f_{Y\mid X}(y \mid x) \propto f_{X\mid Y}(x\mid y)\, f_Y(y).
Definition 2.15 — Conditional expectation \mathbb{E}[X \mid Y = y] = \int x \, f_{X\mid Y}(x\mid y)\,dx, and \mathbb{E}[X \mid Y] = g(Y).
For square-integrable X, this is the best approximation of X by a function of Y in least squares: \mathbb{E}[(X - h(Y))^2] \geq \mathbb{E}[(X - g(Y))^2] for every square-integrable h(Y) — the projection theorem in L^2.
Tower property: \mathbb{E}[\mathbb{E}[X \mid Y]] = \mathbb{E}[X]. Law of total variance: \mathrm{Var}(X) = \mathbb{E}[\mathrm{Var}(X\mid Y)] + \mathrm{Var}(\mathbb{E}[X \mid Y]), variance within + variance between groups — the identity behind ANOVA.
Connection with regression The optimal predictor of Y from X under squared loss is the regression function x \mapsto \mathbb{E}[Y \mid X = x]; the irreducible error is \mathbb{E}[\mathrm{Var}(Y\mid X)]. Linear models, networks and forests approximate this object; other losses have other optimal targets.
2.7. Finite Markov chains
In a random walk on a graph or a bigram language model, the next value depends on the past only through the present.
Definition 2.16 — Finite Markov chain Let S=\{1,\dots,K\}. A sequence (X_t)_{t\geq0} with values in S is a Markov chain with transition matrix P\in\mathbb{R}^{K\times K} if \mathbb{P}(X_{t+1}=j\mid X_t=i,\,X_{t-1},\dots,X_0)=P_{ij}. Each row of P is a probability vector: P is row-stochastic. If the column vector \mu_t holds the law of X_t, then \mu_{t+1}^\top=\mu_t^\top P, \qquad \mu_t^\top=\mu_0^\top P^t. A probability vector \pi is stationary if \pi^\top P=\pi^\top.
Theorem 2.17 — Convergence to the stationary law (stated) If P is irreducible (every state can reach every other), the stationary law \pi exists, is unique and positive, and the fraction of time spent in state i tends to \pi_i almost surely: a law of large numbers for dependent draws.
If moreover P is aperiodic (return times to each state have greatest common divisor 1), then for every initial law \mu_0^\top P^t\xrightarrow[t\to\infty]{}\pi^\top . The proof is admitted.
Proposition 2.18 — Detailed balance implies stationarity If a probability vector \pi satisfies the detailed balance equations \pi_iP_{ij}=\pi_jP_{ji} for all i,j, then \pi is stationary, and the chain is called reversible.
Proof. Sum detailed balance over i and use that row j of P sums to 1: (\pi^\top P)_j=\sum_i\pi_iP_{ij}=\sum_i\pi_jP_{ji}=\pi_j . ∎
Detailed balance is checked one pair of states at a time; samplers are built to satisfy it for a target \pi.
Example 2.19 — A two-state chain, every number visible A user is reading (state 1) or idle (state 2), with P=\begin{pmatrix}0.9&0.1\\0.5&0.5\end{pmatrix}. Detailed balance 0.1\,\pi_1=0.5\,\pi_2 and \pi_1+\pi_2=1 give \pi=(5/6,\;1/6). The second eigenvalue of P is \operatorname{tr}P-1=0.4, so the gap between \mu_t and \pi shrinks by the factor 0.4 at each step: after 5 steps it is below 0.4^5\approx0.01, whatever the start.
Example 2.20 — The Gibbs sampler is a Markov chain To sample a target \pi on vectors x=(x_1,\dots,x_d), the Gibbs sampler repeats: pick a coordinate k uniformly, redraw x_k from \pi(\cdot\mid x_{-k}), keep the others.
Once k is picked, it moves x to y, with y_{-k}=x_{-k}, with probability \pi(y_k\mid x_{-k}), and \pi(x)\,\pi(y_k\mid x_{-k})=\pi(x_{-k})\,\pi(x_k\mid x_{-k})\,\pi(y_k\mid x_{-k}) is symmetric in x_k and y_k: detailed balance holds, so \pi is stationary. Collapsed Gibbs for topic models (Text Mining and NLP ch. 5) builds on this step.
2.8. Generating and manipulating distributions in Python
import numpy as np
rng = np.random.default_rng(seed=42) # modern generator (PCG64)
x = rng.normal(loc=0.0, scale=1.0, size=1000) # 1000 draws from N(0,1)
u = rng.uniform(0, 1, size=100_000)
# Inverse method (theorem 2.4 + section 2.1): uniform U -> exponential
lam = 2.0
expo = -np.log(1.0 - u) / lam
print(expo.mean().round(4), (1/lam)) # ~0.5 = E[X] of E(2)
# Histogram (empirical density) and the model density
import matplotlib.pyplot as plt
plt.hist(x, bins=40, density=True, alpha=.6, label='sample')
grid = np.linspace(-4, 4, 200)
plt.plot(grid, np.exp(-grid**2/2)/np.sqrt(2*np.pi), 'r', label='N(0,1) density')
plt.legend(); plt.show()
print(x.mean(), x.var(ddof=1)) # empirical mean, unbiased variance
print(np.quantile(x, [0.25, 0.5, 0.75])) # empirical quantiles (chap. 3)Key takeaways — chapter 2
- The CDF characterizes the distribution, and inverse-CDF sampling transforms uniforms into samples of any target law.
- Under a change of variables, f_Y(y) = f_X(g^{-1}(y))\,|\det J_{g^{-1}}(y)|; the Jacobian compensates for the local volume change.
- An MGF finite near 0 yields the moments by differentiation and factorizes over sums of independent variables.
- Markov’s inequality implies Chebyshev’s, which in turn proves the finite-variance LLN in chapter 4.
- Uncorrelated does not mean independent, as the counterexample Y = X^2 shows.
- Detailed balance implies stationarity, \pi^\top P=\pi^\top: this is how the Gibbs sampler targets \pi.
3. Common probability distributions
A dozen named distributions cover most of the models met in Machine Learning. These are reusable modeling “bricks”. Know their support, parameters, expectation and variance, and recognize when they appear. Use the table as a reference rather than a memorization gate.
| Distribution | Parameters | Expectation | Variance | Typical use in ML |
|---|---|---|---|---|
| Bernoulli p | p \in [0,1] | p | p(1-p) | binary label, classifier |
| Binomial \mathcal{B}(n,p) | n, p | np | np(1-p) | number of successes / errors over n trials |
| Multinomial \mathrm{Mult}(n,(p_1,\dots,p_K)) | n, probabilities p_k | np_k (per cell) | np_k(1-p_k) | class counts, categorical predictions, \chi^2 test |
| Geometric p | 0<p\leq1 | 1/p | (1-p)/p^2 | trials up to and including the first success; rejection sampling |
| Hypergeometric | N,K,n | nK/N | n\frac{K}{N}(1-\frac{K}{N})\frac{N-n}{N-1} | sampling without replacement |
| Uniform \mathcal{U}[a,b] | a<b | \tfrac{a+b}{2} | \tfrac{(b-a)^2}{12} | initialization, inverse-method simulation |
| Exponential \mathcal{E}(\lambda) | \lambda>0 | 1/\lambda | 1/\lambda^2 | lifetimes, queues, Poisson waiting times |
| Poisson \mathcal{P}(\lambda) | \lambda>0 | \lambda | \lambda | event counts, Poisson regression |
| Gamma \Gamma(a,b) (shape a, scale b) | a,b>0 | ab | ab^2 | aggregated durations, conjugate priors on precision |
| Beta \mathrm{Beta}(a,b) | a,b>0 | \tfrac{a}{a+b} | \tfrac{ab}{(a+b)^2(a+b+1)} | distribution of an unknown probability; Bernoulli conjugate prior |
| Gaussian \mathcal{N}(\mu,\sigma^2) | \mu,\sigma^2>0 | \mu | \sigma^2 | noise, Gaussian posterior models, diffusion |
| Chi-square \chi^2_k | k\in\mathbb{N}_{>0} | k | 2k | goodness-of-fit tests, squared deviations, empirical variance |
| Student t_k | k>0 | 0\ (k>1) | \tfrac{k}{k-2}\ (k>2) | confidence intervals in small Gaussian samples |
| Fisher \mathcal{F}(d_1,d_2) | d_1,d_2>0 | \tfrac{d_2}{d_2-2}\ (d_2>2) | \tfrac{2d_2^2(d_1+d_2-2)}{d_1(d_2-2)^2(d_2-4)}\ (d_2>4) | comparison of variances, ANOVA |
Conventions: Gamma uses shape and scale throughout these notes; the Laplace (double-exponential) distribution is distinct from Poisson and exponential — its link to \ell_1 regularization appears in chapter 8.
Definition 3.1 — Multivariate Gaussian distribution X \sim \mathcal{N}(\mu, \Sigma) with \mu \in \mathbb{R}^d and \Sigma a symmetric positive definite covariance matrix has density f(x) = \frac{1}{(2\pi)^{d/2}\,(\det\Sigma)^{1/2}} \exp\!\Big(-\tfrac12 (x-\mu)^\top \Sigma^{-1} (x-\mu)\Big). For a jointly Gaussian vector, uncorrelated components (\Sigma diagonal) are independent—a guarantee that does not hold for arbitrary distributions. An equivalent characterization is that every linear combination a^\top X is a real Gaussian. This characterization also covers degenerate Gaussian vectors with positive semidefinite covariance, which need not have a density on all of \mathbb{R}^d.
Example 3.0b — Bernoulli and exponential, plug-in numbers This example anticipates maximum likelihood (definition 5.4): come back to it after chapter 5 if the likelihood is new to you.
(Bernoulli). A coin has unknown bias p, and the observations x_{1:5}=(1,0,1,1,0) contain s=3 successes in n=5 trials. The likelihood and the log-likelihood are L(p)=p^3(1-p)^2, \qquad \ell(p)=3\log p + 2\log(1-p). Setting the derivative to zero gives the maximizer: \ell'(p)=\frac{3}{p}-\frac{2}{1-p}=0 \;\Longleftrightarrow\; 3(1-p)=2p \;\Longleftrightarrow\; \hat p_{\mathrm{MLE}}=\frac{3}{5}=0.6. The second derivative \ell''(0.6)=-3/(0.6)^2-2/(0.4)^2<0 confirms that this is a maximum.
(Exponential). The density is f(x)=\lambda e^{-\lambda x} for x>0, and the sample is (1.2,\,0.4,\,2.0) hours. The likelihood is \lambda^3 e^{-\lambda(1.2+0.4+2.0)}=\lambda^3 e^{-3.6\lambda}, and the score equation gives \frac{3}{\lambda}-3.6=0 \qquad\Longleftrightarrow\qquad \hat\lambda_{\mathrm{MLE}}=\frac{3}{3.6}=\frac{5}{6}\approx 0.833 \text{ per hour.} The plug-in estimate of the mean is \widehat{\mathbb{E}[X]}=1/\hat\lambda=1.2 hours, which matches the sample mean (1.2+0.4+2.0)/3=1.2.
3.1. Gaussians: marginals and conditionals
Theorem 3.2 — Gaussian conditioning Let (X, Y) be a Gaussian vector with mean (\mu_X, \mu_Y) and block covariance \Sigma = \begin{pmatrix} \Sigma_{XX} & \Sigma_{XY} \\ \Sigma_{YX} & \Sigma_{YY}\end{pmatrix}, with \Sigma_{XX} invertible. Then:
- Gaussian marginals: X \sim \mathcal{N}(\mu_X, \Sigma_{XX}) (projections of a Gaussian vector are Gaussian—by the linear characterization);
- Gaussian conditional: Y \mid X = x \;\sim\; \mathcal{N}\big(\mu_Y + \Sigma_{YX}\Sigma_{XX}^{-1}(x - \mu_X),\;\; \Sigma_{YY} - \Sigma_{YX}\Sigma_{XX}^{-1}\Sigma_{XY}\big). The conditional mean is affine in x and the conditional covariance is constant.
Proof. One can complete the square in the joint density, or construct an independent residual. Set A = \Sigma_{YX}\Sigma_{XX}^{-1} and the random vector Z = Y - \mu_Y - A(X-\mu_X). The vector \binom{X-\mu_X}{Z} is an affine transformation of the Gaussian (X,Y), hence Gaussian. Its cross-covariance is \mathrm{Cov}(X-\mu_X,Z) = \Sigma_{XY}-\Sigma_{XX}A^\top = \Sigma_{XY}-\Sigma_{XX}\Sigma_{XX}^{-1}\Sigma_{XY} =0. Joint Gaussianity turns zero cross-covariance into independence. Thus Z is independent of X, and Z\sim\mathcal{N}\big(0,\Sigma_{YY}-\Sigma_{YX}\Sigma_{XX}^{-1}\Sigma_{XY}\big). Rearrange Y=\mu_Y+A(X-\mu_X)+Z and then condition on X=x: the first two terms become a constant, while the residual distribution stays unchanged. ∎
Where this theorem is reused — preview Gaussian regression, Kalman filtering, Gaussian processes and latent-variable models all use it, as do the linear-Gaussian forward transitions of diffusion models — though learned reverse transitions are not exactly Gaussian.
Where they are taught: the Kalman filter, as recursive Gaussian conditioning, in Signal Processing ch. 7 (theorem 7.7); diffusion in Deep Learning section 9.4 (self-study) and, in depth, Multimodal Generative AI ch. 3. Gaussian processes have no chapter of their own, but their posterior mean is the kernel ridge regression of Machine Learning ch. 5.
In one sentence: conditioning a jointly Gaussian vector shifts the mean affinely and reduces the covariance by \Sigma_{YX}\Sigma_{XX}^{-1}\Sigma_{XY}.
3.2. Sums of variables: stability under convolution
Theorem 3.3 — Sums of independent variables If X \perp Y and densities exist, the density of X+Y is the convolution product f_{X+Y}(z) = \int f_X(x) f_Y(z-x)\,dx; use sums for discrete mass functions. Via the MGF (definition 2.9): M_{X+Y} = M_X M_Y. Families closed under sums of independent variables include:
| Family | Sum | MGF verification |
|---|---|---|
| \mathcal{B}(n_1,p), \mathcal{B}(n_2,p) | \mathcal{B}(n_1+n_2,p) | (1-p+pe^t)^{n_1+n_2} |
| \mathcal{P}(\lambda_1), \mathcal{P}(\lambda_2) | \mathcal{P}(\lambda_1+\lambda_2) | e^{(\lambda_1+\lambda_2)(e^t-1)} |
| \Gamma(a_1,b), \Gamma(a_2,b) | \Gamma(a_1+a_2,b) (same scale) | (1-bt)^{-(a_1+a_2)} |
| \mathcal{N}(\mu_1,\sigma_1^2), \mathcal{N}(\mu_2,\sigma_2^2) | \mathcal{N}(\mu_1+\mu_2,\sigma_1^2+\sigma_2^2) | e^{(\mu_1+\mu_2)t+(\sigma_1^2+\sigma_2^2)t^2/2} |
| \chi^2_{k_1}, \chi^2_{k_2} | \chi^2_{k_1+k_2} | special case of gamma |
A sample mean is a scaled sum; it need not belong to the same named family as the observations (a scaled binomial is not generally binomial). For iid variables with finite variance, its expectation stays constant and its variance is divided by n.
Example 3.4 — Gaussian sum, in one line of MGF For independent X \sim \mathcal{N}(\mu_1,\sigma_1^2) and Y \sim \mathcal{N}(\mu_2,\sigma_2^2), the MGF of the sum factorizes and recombines: M_{X+Y}(t) = e^{\mu_1 t + \sigma_1^2 t^2/2}\cdot e^{\mu_2 t + \sigma_2^2 t^2/2} = e^{(\mu_1+\mu_2)t + (\sigma_1^2+\sigma_2^2)t^2/2}. This is the MGF of \mathcal{N}(\mu_1+\mu_2, \sigma_1^2+\sigma_2^2). Variances add, so the standard deviation of the sum is \sqrt{\sigma_1^2+\sigma_2^2}, not \sigma_1+\sigma_2; averaging n independent observations produces the 1/\sqrt n reduction of chapter 4.
3.3. Order statistics
Proposition 3.5 — Distributions of the minimum and the maximum For X_1, \dots, X_n iid with cumulative distribution function F: \mathbb{P}(\max_i X_i \leq t) = F(t)^n, \qquad \mathbb{P}(\min_i X_i \leq t) = 1 - \big(1 - F(t)\big)^n. More generally X_{(k)} (the k-th smallest) serves to define quantiles: one convention for the empirical quantile of order q\in(0,1] is X_{(\lceil qn \rceil)}. Software may interpolate between adjacent order statistics.
Proof. \{\max \leq t\} = \bigcap_i \{X_i \leq t\} and the events are independent: product of the n probabilities F(t). Likewise \{\min > t\} = \bigcap_i \{X_i > t\}, with probability (1-F(t))^n. ∎
Example 3.6 — Maximum of uniforms and quantiles in code If X_i \sim \mathcal{U}[0,1], \max_i X_i has density n t^{n-1} on (0,1), the derivative of t^n: it is a \mathrm{Beta}(n,1) distribution with expectation \frac{n}{n+1}. With n = 9 trials, the expected best score is already 0.9. Selection pushes a maximum toward the extreme. If the scores are noisy validation measurements, this also illustrates why selecting the best reported score does not by itself demonstrate an improvement in population performance.
import numpy as np
rng = np.random.default_rng(0)
x = rng.uniform(0, 1, size=(10_000, 9))
print(x.max(axis=1).mean().round(3)) # ~0.900 = n/(n+1)
q = np.quantile(rng.normal(size=100_000), [0.05, 0.25, 0.5, 0.75, 0.95])
print(q.round(3)) # ~[-1.645 -0.674 0 0.674 1.645]The Gaussian and ML The Gaussian appears as regression noise, weight initialization, a diffusion building block and a conjugate prior — roles explained by linear stability, the CLT and affine conditioning. None makes Gaussianity a default truth about a dataset.
Key takeaways — chapter 3
- For each family in the table, know the expectation, the variance and a modeling scenario where it appears.
- Jointly Gaussian vectors have Gaussian marginals and Gaussian conditionals, with a conditional mean affine in the conditioning value.
- Densities of independent sums are convolutions, and the families closed under such sums are the binomial with shared p, the Poisson, the gamma with shared scale, the Gaussian and the \chi^2.
- The maximum has CDF F^n and the minimum has CDF 1-(1-F)^n; empirical quantiles follow by ordering the sample, possibly with interpolation.
3.4. Going further: the measure-theoretic layer
Self-study, optional. These remarks complete chapters 1, 2 and 4; the in-class sessions use at most their statements. Items 6 and 7 are best read after chapter 4.
Continuity along monotone sequences. If A_n\uparrow A, then \mathbb{P}(A_n)\uparrow\mathbb{P}(A). Set C_1=A_1 and C_n=A_n\setminus A_{n-1}: these sets are disjoint with union A, and \textstyle\sum_{k\leq n}\mathbb{P}(C_k)=\mathbb{P}(A_n), so σ-additivity concludes. Taking complements gives the decreasing case, A_n\downarrow A; theorem 2.3 uses both.
Why a σ-algebra (Vitali). On [0,1] there are subsets to which no length can be given: Vitali’s construction, which uses the axiom of choice, rules out a translation-invariant, σ-additive length on all subsets. This is why a probability is defined on a σ-algebra \mathcal{F} rather than on every subset of \Omega.
Borel sets and measurability. The Borel σ-algebra of \mathbb{R} is the smallest σ-algebra containing the intervals. A map X is measurable when X^{-1}(B)\in\mathcal{F} for every Borel set B. Checking the half-lines \{X\leq t\} suffices (definition 2.1), because they generate the Borel sets; for the same reason, independence of variables (definition 1.6) can be checked on intervals.
Two σ-algebras \mathcal{G} and \mathcal{H} are independent when every G\in\mathcal{G} and H\in\mathcal{H} satisfy \mathbb{P}(G\cap H)=\mathbb{P}(G)\,\mathbb{P}(H).
The law as a pushforward, and the converse of theorem 2.3. The distribution of X is the pushforward measure \mathbb{P}_X=\mathbb{P}\circ X^{-1} on the Borel sets. Conversely, every nondecreasing, right-continuous F with limits 0 and 1 is the CDF of a unique law: Carathéodory’s extension theorem extends the set function (a,b]\mapsto F(b)-F(a) from intervals to all Borel sets.
Tonelli–Fubini. For a measurable h\geq0, a double integral can be computed in either order (Tonelli), and the same holds for integrable h (Fubini). When X\perp Y, the joint law is the product measure \mathbb{P}_X\otimes\mathbb{P}_Y, and integrating xy in either order gives \mathbb{E}[XY]=\mathbb{E}[X]\mathbb{E}[Y] (proposition 2.7).
Almost sure convergence and Borel–Cantelli. The events A_n(\varepsilon)=\bigcup_{k\geq n}\{|X_k-X|>\varepsilon\} decrease to “deviations above \varepsilon infinitely often”, which has probability 0 under a.s. convergence, so \mathbb{P}(A_n(\varepsilon))\to0 by item 1. Since \{|X_n-X|>\varepsilon\}\subseteq A_n(\varepsilon), a.s. convergence implies convergence in probability (proposition 4.2).
The Borel–Cantelli lemmas say that if \sum_n\mathbb{P}(B_n)<\infty, almost surely only finitely many B_n occur; if the B_n are independent and \sum_n\mathbb{P}(B_n)=\infty, almost surely infinitely many occur. For the counterexample of proposition 4.2, \sum 1/n=\infty: the jumps X_n=n recur forever, so there is no a.s. convergence.
The same tools prove the strong law (\bar X_n\to\mu a.s. when \mathbb{E}|X_1|<\infty), from which the integrable-only weak law of theorem 4.3 follows, and Glivenko–Cantelli: the empirical CDF converges uniformly, \sup_t|F_n(t)-F(t)|\to0\quad\text{a.s.}
Characteristic functions and Lévy’s theorem. The characteristic function \varphi_X(t)=\mathbb{E}[e^{itX}] always exists and characterizes the law. Lévy’s continuity theorem: X_n\to X in distribution if and only if \varphi_{X_n}\to\varphi_X pointwise. With finite variance, \varphi_Z(t/\sqrt n)=1-t^2/(2n)+o(1/n), so \varphi_{S_n}(t)\to e^{-t^2/2}, which proves the CLT (theorem 4.4) without the MGF assumption of its proof sketch.
4. Convergence and limit theorems
ML optimizes on a finite sample and hopes for good performance on future data. Limit theorems describe how empirical averages behave under a sampling model — they do not by themselves justify selecting a predictor after inspecting that sample (chapter 9).
Definition 4.1 — Modes of convergence Let (X_n) and X be real random variables.
- Almost sure (a.s.): \mathbb{P}\big(\lim X_n = X\big) = 1;
- In probability: \forall \varepsilon > 0,\; \mathbb{P}(|X_n - X| > \varepsilon) \to 0;
- In L^p, p>0: \mathbb{E}|X_n - X|^p \to 0;
- In distribution: F_{X_n}(t) \to F_X(t) at every continuity point of F_X.
Proposition 4.2 — Implications Almost sure \Rightarrow in probability \Rightarrow in distribution; L^p \Rightarrow in probability. The converses are false in general.
Proof. For L^p \Rightarrow probability, apply Markov’s inequality to |X_n-X|^p.
For probability \Rightarrow distribution, take a continuity point t and bound F(t-\varepsilon) - \mathbb{P}(|X_n-X|>\varepsilon) \;\leq\; F_n(t) \;\leq\; F(t+\varepsilon) + \mathbb{P}(|X_n-X|>\varepsilon), then let \varepsilon\downarrow0.
For a counterexample, let the X_n be independent, equal to n with probability 1/n and to 0 otherwise. They converge to 0 in probability, yet \mathbb{E}|X_n|=1 rules out L^1 convergence.
Finally, X_n=(-1)^nZ with Z\sim\mathcal{N}(0,1) has a constant law, so it converges in distribution, but not in probability.
Section 3.4 proves the a.s. implication and shows that these variables do not converge a.s. ∎
Theorem 4.3 — (Weak) law of large numbers Let (X_n) be iid with \mathbb{E}|X_1| < \infty and \mu = \mathbb{E}X_1. Then \bar{X}_n = \frac{1}{n}\sum_{i=1}^n X_i \;\xrightarrow[n\to\infty]{\mathbb{P}}\; \mu .
Proof. Under the stronger finite-variance assumption \sigma^2 < \infty: \mathbb{E}[\bar X_n] = \mu by linearity, and by independence \mathrm{Var}(\bar X_n) = \sigma^2/n.
Chebyshev then gives \mathbb{P}(|\bar X_n - \mu| \geq \varepsilon) \leq \sigma^2/(n\varepsilon^2) \to 0. The integrable-only version is admitted (section 3.4). ∎
For bounded variables, Hoeffding’s exponential bound is stated and proved in Machine Learning ch. 0, Theorem 0.3.
Theorem 4.4 — Central limit theorem (CLT) Let (X_n) be iid, \mu = \mathbb{E}X_1, 0<\sigma^2 = \mathrm{Var}(X_1) < \infty. Then \frac{\bar{X}_n - \mu}{\sigma / \sqrt{n}} \;\xrightarrow[n\to\infty]{(\text{dist.})}\; \mathcal{N}(0,1). In other words, for sufficiently large n:
Key result — the CLT in practice \bar X_n \approx \mathcal{N}\big(\mu, \tfrac{\sigma^2}{n}\big)
The approximation quality depends on the distribution.
Example 4.4b — Fair die, written CLT table Fair die: \mu=3.5, \sigma^2=35/12\approx 2.9167. For n iid rolls, theory gives \mathrm{sd}(\bar X_n)=\sigma/\sqrt{n}. One Monte Carlo run (2000 repeats, seed 0) versus theory:
| n | Empirical mean of \bar X_n | Empirical sd | Theory \sigma/\sqrt{n} |
|---|---|---|---|
| 1 | 3.579 | 1.690 | 1.708 |
| 5 | 3.489 | 0.747 | 0.764 |
| 20 | 3.492 | 0.382 | 0.382 |
| 100 | 3.502 | 0.171 | 0.171 |
By n=20 the observed standard deviation closely matches the 1/\sqrt n calculation. The Gaussian shape is the CLT contribution; the variance identity itself is exact under independence and finite variance.
Proof. MGF sketch (extra assumption: the MGF exists around 0). With Z_i = \frac{X_i - \mu}{\sigma} and S_n = \frac1{\sqrt n}\sum_i Z_i, Taylor expansion gives M_Z(t/\sqrt n) = 1+\frac{t^2}{2n}+o(1/n), and independence yields M_{S_n}(t) = \Big(1 + \frac{t^2}{2n} + o\Big(\frac1n\Big)\Big)^{\!n} \to e^{t^2/2}, the MGF of \mathcal{N}(0,1), using (1+a/n)^n\to e^a.
Section 3.4 removes the MGF assumption. The limit is Gaussian regardless of the initial shape, within the assumptions. ∎
Proposition 4.5 — The 1/\sqrt n rate, with orders of magnitude The standard deviation of an iid sample mean is \sigma/\sqrt n. Concretely:
| n | 10 | 100 | 10,000 | 1,000,000 |
|---|---|---|---|---|
| error reduction factor | 3.2 | 10 | 100 | 1,000 |
Dividing this sampling standard error by 2 requires 4 times more independent observations; dividing it by 10 requires 100 times more. It is not a universal rate for every learning problem, nor a remedy for bias or distribution shift.
Theorem 4.6 — Delta method If \sqrt n (\bar X_n - \mu) \to \mathcal{N}(0, \sigma^2) in distribution and g is C^1 near \mu with g'(\mu) \neq 0, then \sqrt n\,\big(g(\bar X_n) - g(\mu)\big) \;\xrightarrow{(\text{dist.})}\; \mathcal{N}\big(0,\; \sigma^2\,g'(\mu)^2\big).
Proof. A Taylor expansion gives g(\bar X_n) = g(\mu) + g'(\mu)(\bar X_n - \mu) + o(|\bar X_n - \mu|). After multiplication by \sqrt n, the remainder is o_p(1): a quantity that converges to 0 in probability.
Slutsky’s lemma says that if Y_n converges in distribution to Y and Z_n converges in probability to a constant c, then Y_n + Z_n converges in distribution to Y + c.
The CLT gives the limit \mathcal N(0, g'(\mu)^2\sigma^2) for the linearized term, and Slutsky’s lemma shows that adding the vanishing remainder does not change it.
As an example, for g=\log with \mu>0, \sqrt n\,(\log\bar X_n-\log\mu)\;\xrightarrow{(\text{dist.})}\;\mathcal{N}\big(0,\ \sigma^2/\mu^2\big), and the logit of a probability estimator behaves the same way away from the boundaries 0 and 1. ∎
4.1. Empirical quantiles and the bootstrap
The empirical CDF F_n(t) = \frac1n \sum_i \mathbf{1}_{X_i \leq t} is a plug-in estimator of F, consistent at each t by the LLN. Quantiles follow by inversion.
To approximate uncertainty for a nonlinear statistic (median, ratio, AUC), the nonparametric bootstrap resamples B times with replacement, recomputes the statistic, and reads off the bootstrap quantiles:
import numpy as np
rng = np.random.default_rng(0)
x = rng.standard_t(df=3, size=200) # symmetric, heavy-tailed distribution
B = 5_000
boot_med = np.array([np.median(rng.choice(x, size=len(x), replace=True))
for _ in range(B)])
lo, hi = np.quantile(boot_med, [0.025, 0.975])
print(f"95% bootstrap CI of the median: [{lo:.3f}, {hi:.3f}]")
# Percentile interval = [2.5%, 97.5%] bootstrap quantiles; an approximation,
# not exact in finite samples. Validity depends on the statistic (bootstrap
# can fail for extrema) and on the independence structure: time series and
# related graph observations may need block or cluster resampling instead.Example 4.7 — Numerical verification of the CLT
import numpy as np
rng = np.random.default_rng(0)
for n in [1, 5, 30, 200]:
# 5000 repetitions of the mean of n independent uniforms [0,1]
means = rng.uniform(0, 1, size=(5000, n)).mean(axis=1)
std = means.std()
print(f"n={n:4d} observed std = {std:.4f} "
f"(theory 1/sqrt(12 n) = {1/np.sqrt(12*n):.4f})")The observed standard deviation approaches 1/\sqrt{12n}. Uniforms behave well by n=30 here, but there is no universal “30 samples is enough” rule: heavy tails, rare events and dependence break that shortcut.
When the row count is not the information count In general, \mathrm{Var}(\bar X_n) =\frac{1}{n^2}\left(\sum_i\mathrm{Var}(X_i) +2\sum_{i<j}\mathrm{Cov}(X_i,X_j)\right). The iid result drops the covariance terms; questions from one document, linked graph nodes or repeated device measurements retain them. Define the deployment target, split unit and uncertainty unit before reporting an iid standard error.
Key takeaways — chapter 4
- Almost sure convergence implies convergence in probability, which implies convergence in distribution; L^p convergence also implies convergence in probability, and none of the converses hold in general.
- The finite-variance LLN proof combines Chebyshev’s inequality with the identity \mathrm{Var}(\bar X_n)=\sigma^2/n.
- The CLT states that standardized fluctuations approach a Gaussian; the MGF sketch needs an extra assumption, while the characteristic-function proof only needs finite variance.
- The delta method propagates a limit through a derivative, and the bootstrap approximates a sampling distribution by resampling, subject to validity conditions.
- Independence and the sampling unit are part of the calculation, not optional footnotes.
5. Parametric estimation
Assume the data distribution belongs to a family \{p_\theta:\theta\in\Theta\} and seek \theta from an iid sample. This chapter develops bias/variance, likelihood and information; chapter 6 turns them into intervals and tests.
Definition 5.1 — Estimator, bias, squared risk An estimator \hat\theta_n = g(X_1,\dots,X_n) is a statistic used to estimate \theta. Its bias is b(\hat\theta) = \mathbb{E}_\theta[\hat\theta] - \theta, and its squared risk (mean squared error, MSE) is \mathbb{E}_\theta[(\hat\theta - \theta)^2].
Theorem 5.2 — Bias-variance decomposition \mathbb{E}[(\hat\theta - \theta)^2] = \underbrace{\big(\mathbb{E}[\hat\theta] - \theta\big)^2}_{\text{bias}^2} + \underbrace{\mathrm{Var}(\hat\theta)}_{\text{variance}}.
Proof. Set m=\mathbb{E}[\hat\theta] and write \hat\theta-\theta=(\hat\theta-m)+(m-\theta). Expand the square and take expectations: \mathbb{E}[(\hat\theta-m)^2] +2(m-\theta)\underbrace{\mathbb{E}[\hat\theta-m]}_{=0} +(m-\theta)^2 =\mathrm{Var}(\hat\theta)+b(\hat\theta)^2. The cross term vanishes by the definition of the expectation. ∎
Example 5.3 — Why n-1: bias of the empirical variance Consider the biased empirical variance S_n^2 = \frac1n\sum_i (X_i - \bar X_n)^2. The key identity is \sum_i (X_i-\bar X_n)^2=\sum_i(X_i-\mu)^2-n(\bar X_n-\mu)^2, and taking expectations gives (n-1)\sigma^2, so \mathbb{E}[S_n^2]=\frac{n-1}{n}\,\sigma^2<\sigma^2. The downward bias comes from estimating \mu with the same observations. Dividing by n-1 instead of n removes it — though unbiasedness of s^2 does not transfer to its square root s.
Definition 5.4 — Likelihood and maximum likelihood (MLE) The likelihood of an iid sample is L(\theta) = \prod_{i=1}^n p_\theta(X_i) (density or mass), viewed as a function of \theta for the observed data. The log-likelihood is \ell(\theta) = \sum_i \log p_\theta(X_i). A maximum likelihood estimator is \hat\theta_{\mathrm{MLE}} \in \arg\max_\theta \ell(\theta) when a maximizer exists.
Example 5.0b — Gaussian MLE with a 4-point sample Consider the observations x=(2.0,\,2.5,\,1.5,\,2.0) and a \mathcal{N}(\mu,\sigma^2) model with both parameters unknown. The MLE of the mean is the sample mean: \hat\mu = \bar x = \frac{2+2.5+1.5+2}{4} = 2.0. The MLE of the variance divides by n: \hat\sigma^2_{\mathrm{MLE}} = \frac1n\sum_i (x_i-\bar x)^2 = \frac{(0)^2+(0.5)^2+(-0.5)^2+(0)^2}{4} = 0.125. The unbiased estimator s^2 divides by n-1=3 instead, giving s^2=0.5/3\approx0.1667. At the MLE, the log-likelihood equals \ell=-\tfrac n2\log(2\pi\hat\sigma^2)-\tfrac n2.
5.1. Score and Fisher information
Definition 5.5 — Score The score is the derivative of the log-likelihood of one observation: s(\theta) = \nabla_\theta \log p_\theta(X). For an iid sample, the score is \sum_i s_i(\theta).
Theorem 5.6 — Two properties of the score Under regularity, including a suitable common support and justified differentiation under the integral: \text{(i)}\;\; \mathbb{E}_\theta[s(\theta)] = 0,\qquad \text{(ii)}\;\; \mathrm{Var}_\theta[s(\theta)] = \mathbb{E}_\theta[-\nabla^2_\theta\log p_\theta(X)] =:I(\theta). For a vector parameter, \mathrm{Var} denotes the covariance matrix. I(\theta) is the Fisher information: score variability, equivalently the negative expected curvature of the log-likelihood.
Proof. For (i), start from the identity \int p_\theta(x)\,dx = 1, valid for every \theta, and differentiate under the integral sign: 0=\int\nabla_\theta p_\theta(x)\,dx =\int\frac{\nabla_\theta p_\theta(x)}{p_\theta(x)}\,p_\theta(x)\,dx =\mathbb{E}_\theta[\nabla_\theta\log p_\theta(X)].
For (ii), differentiate \int\nabla_\theta p_\theta\,dx=0 a second time. Using the product identity \nabla^2p=(\nabla^2\log p)\,p+(\nabla\log p)(\nabla\log p)^\top p, we obtain 0=\mathbb{E}_\theta[\nabla^2_\theta\log p_\theta(X)] +\mathbb{E}_\theta\big[\nabla_\theta\log p_\theta(X)\, \nabla_\theta\log p_\theta(X)^\top\big].
Therefore \mathbb{E}[ss^\top]=-\mathbb{E}[\nabla^2\log p]=I(\theta), and the zero mean established in (i) makes this matrix the score covariance. ∎
Theorem 5.7 — Cramér-Rao bound For a scalar parameter and a regular unbiased estimator \hat\theta, with positive finite information: \mathrm{Var}(\hat\theta)\;\geq\;\frac{1}{I_n(\theta)}, \qquad I_n(\theta)=nI(\theta)\quad\text{(iid sample)}. Within this class, variance cannot be smaller than the inverse information. The efficiency ratio is 1/(I_n\,\mathrm{Var}(\hat\theta)). The bound does not say that every biased estimator has a larger MSE.
Theorem 5.8 — Asymptotic properties of the MLE Under regularity (correct specification, identifiability, fixed-dimensional interior parameter, smoothness, nonsingular information), the MLE is consistent and asymptotically normal: \sqrt n(\hat\theta_n-\theta^\star) \xrightarrow{(\text{dist.})} \mathcal{N}\big(0,I(\theta^\star)^{-1}\big). Boundary parameters, singular models, misspecification or growing dimension need separate analysis — no automatic guarantee for every neural-network likelihood.
5.2. MLE of the usual distributions, fully derived
Example 5.9 — Gaussian MLE For X_i\sim\mathcal{N}(\mu,\sigma^2), the log-likelihood is \ell(\mu,\sigma^2)=-\frac n2\log(2\pi\sigma^2)-\frac1{2\sigma^2}\sum_i(X_i-\mu)^2. Setting the \mu-derivative to zero, \frac1{\sigma^2}\sum_i(X_i-\mu)=0, yields \hat\mu_{\mathrm{MLE}}=\bar X_n. Setting the \sigma^2-derivative to zero then yields \hat\sigma^2_{\mathrm{MLE}}=\frac1n\sum_i(X_i-\bar X_n)^2. This is exactly the biased estimator of example 5.3: dividing by n-1 corrects the bias but can increase the MSE, so unbiasedness and minimum risk are different objectives.
Example 5.10 — Exponential MLE The exponential log-likelihood is \ell(\lambda)=n\log\lambda-\lambda\sum_iX_i. Its derivative vanishes when \ell'(\lambda)=\frac n\lambda-\sum_iX_i=0 \qquad\Longleftrightarrow\qquad \boxed{\hat\lambda=\frac1{\bar X_n}}. Since \ell''(\lambda)<0, this is the maximum. The estimator is nonlinear and biased, because \mathbb{E}[1/\bar X_n]\neq1/\mathbb{E}[\bar X_n]; it is nonetheless consistent by the LLN, and the delta method describes its fluctuations.
Example 5.11 — Bernoulli MLE With k=\sum_iX_i successes, the log-likelihood is \ell(p)=k\log p+(n-k)\log(1-p). For 0<k<n, setting the derivative to zero gives \ell'(p)=\frac kp-\frac{n-k}{1-p}=0 \qquad\Longleftrightarrow\qquad \boxed{\hat p=\frac{k}{n}}. For k=0 or k=n, the maximizer is the corresponding boundary value. The negative average log-likelihood is exactly the binary cross-entropy of this constant-probability model; conditional Bernoulli models give the usual classification loss.
Example 5.12 — Poisson MLE The Poisson log-likelihood is \ell(\lambda)=-n\lambda+\Big(\sum_iX_i\Big)\log\lambda-\sum_i\log(X_i!), and the score equation -n+\frac{\sum_iX_i}{\lambda}=0 gives \boxed{\hat\lambda=\bar X_n}, with \lambda=0 as the degenerate boundary case. The corresponding negative log-likelihood is the standard loss for count data such as events or clicks.
MLE = loss minimization Maximizing \ell = minimizing \frac1n\sum_i-\log p_\theta(X_i): with fixed Gaussian variance, scaled squared error; for Bernoulli outcomes, binary cross-entropy. Chapter 9 makes the conditional version explicit.
5.3. Method of moments and plug-in
Definition 5.13 — Method of moments The method of moments equates theoretical moments to the empirical ones m_k=\frac1n\sum_iX_i^k and solves for the parameters; for a Gaussian this gives \mu=m_1 and \sigma^2=m_2-m_1^2. Consistency requires the moments to exist, to identify the parameter, and the inverse map to be continuous. These estimators are often less efficient than a regular MLE but easier to compute, and they are useful for initializing iterative methods such as EM.
Definition 5.14 — Plug-in principle The plug-in principle estimates a distributional functional T(F) by T(F_n), where F_n is the empirical distribution: the mean, a proportion or a quantile are each estimated by their empirical counterpart. Consistency requires conditions on both the sample and the functional — Glivenko-Cantelli (section 3.4) does not make every conceivable functional consistent. The empirical risk of chapter 9 is itself a plug-in construction.
Key takeaways — chapter 5
- The MSE decomposes as bias² + variance, and the proof is the cancellation of a centered cross term.
- Under regularity the score has zero expectation, and the Fisher information is at once the score covariance and the negative expected curvature.
- The Cramér-Rao bound limits regular unbiased estimation, while MLE efficiency is an asymptotic result under regularity.
- Be able to re-derive the Gaussian, exponential, Bernoulli and Poisson MLEs from scratch.
- Moment and plug-in estimators are useful constructions, provided their identification and continuity conditions are checked.
6. Confidence intervals and tests
Chapter 5 produces point estimates; this chapter attaches an uncertainty statement to them. A confidence interval gives a range of parameter values with a guaranteed coverage, and a test decides whether the data contradict a reference hypothesis.
6.1. Confidence intervals: construction by pivot quantity
Definition 6.1 A confidence interval of level 1-\alpha for \theta is a statistic I(X_1,\dots,X_n) such that \mathbb{P}_\theta(\theta\in I)\geq1-\alpha for every parameter value in the model. An asymptotic interval replaces this finite-sample guarantee with a limiting one.
Theorem 6.2 — z interval (known variance), construction If X_i are iid \mathcal{N}(\mu,\sigma^2) with \sigma>0 known, then I=\Big[\bar X_n-z_{1-\alpha/2}\frac{\sigma}{\sqrt n}, \;\bar X_n+z_{1-\alpha/2}\frac{\sigma}{\sqrt n}\Big] is an exact confidence interval of level 1-\alpha, where z_q is the standard Gaussian quantile: z_{0.975}\approx1.96.
Proof. The pivot T=\frac{\bar X_n-\mu}{\sigma/\sqrt n} depends on data and parameter but has a parameter-free distribution: Gaussian stability gives T\sim\mathcal{N}(0,1), so \mathbb{P}(-z\leq T\leq z)=1-\alpha with z=z_{1-\alpha/2}.
The event \{-z\leq T\leq z\} is \{\bar X_n\pm z\sigma/\sqrt n \ni \mu\}: same event, same probability.
The interval is random before sampling; \mu is fixed — the frequentist statement is a property of the procedure, not a posterior probability for \mu. ∎
Proposition 6.3 — Student and chi-square Under the same iid Gaussian model:
- t interval, unknown variance: let S=\sqrt{\frac1{n-1}\sum_i(X_i-\bar X_n)^2}. Then \frac{\bar X_n-\mu}{S/\sqrt n}\sim t_{n-1}. The pivot is a standard Gaussian divided by an independent \sqrt{\chi^2_{n-1}/(n-1)}, using orthogonal Gaussian mean and residual components. The interval is \bar X_n\pm t_{1-\alpha/2,n-1}S/\sqrt n. It is wider than the z construction at the same estimated scale; t_k\to\mathcal{N}(0,1) as the denominator concentrates at 1.
- CI for variance: \frac{(n-1)S^2}{\sigma^2}\sim\chi^2_{n-1} gives \Big[\frac{(n-1)S^2}{\chi^2_{1-\alpha/2,n-1}}, \;\frac{(n-1)S^2}{\chi^2_{\alpha/2,n-1}}\Big]. The \chi^2 distribution is asymmetric, so the interval need not be symmetric around S^2.
Example 6.1b — z-interval, step table Suppose \sigma=2 is known, with n=25, \bar x=10.4 and level 95\%, so the critical value is z_{0.975}=1.96. The computation runs in three steps:
| Step | Computation |
|---|---|
| 1 | SE =\sigma/\sqrt n=2/5=0.4 |
| 2 | Margin =1.96\times0.4=0.784 |
| 3 | CI =10.4\pm0.784=[9.616,11.184] |
The interpretation is that the procedure covers \mu in 95% of repeated samples under the model; it is not a posterior statement of the form \mathbb{P}(\mu\in\mathrm{CI}\mid\text{data})=0.95. See the Bayesian contrast.
Example 6.3b — t-interval vs z, same numbers Now suppose \sigma is unknown and estimated by s=2.0, with the same n=25, \bar x=10.4 and level 95%. There are 24 degrees of freedom and t_{0.975,24}\approx2.064:
| Step | z (if \sigma=2 were known) | t (estimating \sigma) |
|---|---|---|
| SE | 2/5=0.4 | 0.4 |
| Crit. | 1.96 | 2.064 |
| CI | [9.616,11.184] | [9.574,11.226] |
The t interval is slightly wider — the price of estimating \sigma under the Gaussian model.
6.2. Hypothesis testing: the Neyman-Pearson framework
A test compares H_0 (null hypothesis) with H_1 (alternative). Choose a test statistic T and a rejection region R:
| We do not reject H_0 | We reject H_0 | |
|---|---|---|
| H_0 true | correct | type I error (probability at most the level \alpha) |
| H_1 true | type II error (probability \beta) | correct (probability 1-\beta, the power) |
Power depends on the particular alternative. The p-value is the probability, under the null model, of a statistic at least as extreme as the observed one; reject when p\leq\alpha. A more stringent threshold lowers power; more independent observations can raise it against a fixed nonzero effect — but cannot repair a biased design or a misspecified null.
Theorem 6.4 — Neyman-Pearson lemma To test two simple hypotheses H_0:\theta=\theta_0 and H_1:\theta=\theta_1, with densities or mass functions f_0,f_1, a most powerful level-\alpha test rejects for large likelihood ratio f_1(X)/f_0(X). Choose the threshold c to attain the level; randomization at equality may be needed for discrete data.
Proof. Let \varphi=\mathbf{1}_{f_1/f_0>c} have exact level \alpha and let \psi be any test with \mathbb{E}_0[\psi]\leq\alpha. Pointwise, (\varphi-\psi)(f_1-cf_0)\geq0 (both factors change sign together). Integrating: \mathbb{E}_1[\varphi]-\mathbb{E}_1[\psi] \geq c\big(\mathbb{E}_0[\varphi]-\mathbb{E}_0[\psi]\big)\geq0. With boundary randomization, f_1-cf_0=0 on the boundary and the same proof works. ∎
Scope Optimality holds for the stated pair of simple hypotheses — it motivates many tests but is not universal for composite ones. The t, chi-square and F distributions arise from exact Gaussian calculations or asymptotics. The Bayes classifier compares the same likelihood ratio, weighted by priors and costs.
6.3. Tests on means: z, t, Welch
| Test | Statistic | Assumptions | Use |
|---|---|---|---|
| z (one mean) | \sqrt n(\bar X-\mu_0)/\sigma | known \sigma; iid Gaussian for exactness, or justified CLT | compare a mean to a reference |
| one-sample t | \sqrt n(\bar X-\mu_0)/S | exact t_{n-1} under iid Gaussian sampling | same, unknown \sigma |
| paired t | t statistic on D_i=X_i-Y_i | independent pairs; Gaussian differences for exactness | compare two measurements on the same units |
| two-sample t (pooled) | \frac{\bar X-\bar Y}{S_p\sqrt{1/n+1/m}} | independent Gaussian groups, equal variances | compare two group means |
| Welch | \frac{\bar X-\bar Y}{\sqrt{S_X^2/n+S_Y^2/m}} | independent groups, unequal variances, approximate adjusted df | useful default for two independent means |
from scipy import stats
import numpy as np
rng = np.random.default_rng(3)
a = rng.normal(10.2, 2.0, 50) # group A
b = rng.normal( 9.4, 2.4, 60) # group B (different variance)
t_stat, p_value = stats.ttest_ind(a, b, equal_var=False) # Welch
print(f"t = {t_stat:.3f}, p = {p_value:.4f}")
# If p < 0.05, reject equality of means at the preselected 5% level.
# p does NOT mean "probability that the means are equal".6.4. Chi-square tests
Theorem 6.5 — Goodness of fit To test H_0:X\sim(p_1,\dots,p_K) with specified probabilities, let O_k be observed counts and E_k=np_k expected counts. For iid observations, T=\sum_{k=1}^K\frac{(O_k-E_k)^2}{E_k} \;\xrightarrow[n\to\infty]{(\text{dist.})}\;\chi^2_{K-1}. Sketch: a vector CLT on multinomial counts; the standardized fluctuations sum to zero, leaving a rank-K-1 Gaussian whose squared norm is \chi^2_{K-1}. Sparse expected counts degrade the approximation, and fitted probabilities change the degrees of freedom.
Example 6.6 — Is a die fair? A die is rolled 120 times, giving observed counts (18,20,16,22,24,20) where the fair-die model expects 20 everywhere. The statistic is T=\frac{(18-20)^2+(20-20)^2+(16-20)^2+(22-20)^2+(24-20)^2+(20-20)^2}{20} =\frac{4+0+16+4+16+0}{20}=2.0. With 5 degrees of freedom, the p-value is approximately 0.85: this sample provides no evidence against the fair-die model, which of course does not prove the die is fair.
Proposition 6.7 — Independence on a contingency table For an r\times c table with counts O_{ij} and margins n_{i\cdot},n_{\cdot j}, expected counts under independence are E_{ij}=n_{i\cdot}n_{\cdot j}/n, and under the usual large-count conditions T=\sum_{i,j}\frac{(O_{ij}-E_{ij})^2}{E_{ij}} \;\to\;\chi^2_{(r-1)(c-1)}. Margin constraints leave (r-1)(c-1) degrees of freedom. For a 2×2 table with cells a,b,c,d: T=\frac{n(ad-bc)^2}{(a+b)(c+d)(a+c)(b+d)}. Useful for categorical association checks and outcome-frequency audits across slices — a calibration claim needs its own calibration null.
6.5. One-way ANOVA
Theorem 6.8 — Decomposition and F test Let K groups have sizes n_k, observations Y_{kj}, group means \bar Y_k and overall mean \bar Y, with n=\sum_kn_k. Then \underbrace{\sum_{k,j}(Y_{kj}-\bar Y)^2}_{\text{SST (total)}} = \underbrace{\sum_kn_k(\bar Y_k-\bar Y)^2}_{\text{SSB (between groups)}} + \underbrace{\sum_{k,j}(Y_{kj}-\bar Y_k)^2}_{\text{SSW (residual)}}. The cross term cancels because \sum_j(Y_{kj}-\bar Y_k)=0 in each group. Under H_0 of equal means, independent Gaussian errors and a common variance, F=\frac{\mathrm{SSB}/(K-1)}{\mathrm{SSW}/(n-K)} \sim\mathcal{F}(K-1,n-K). Reject for large F. This compares between-group to within-group variation. ANOVA is also a linear model with group indicators, connecting to chapter 7.
import numpy as np
from scipy import stats
rng = np.random.default_rng(0)
g1, g2, g3 = rng.normal(5.0, 1, 30), rng.normal(5.3, 1, 30), rng.normal(5.1, 1, 30)
F, p = stats.f_oneway(g1, g2, g3)
print(f"F = {F:.3f}, p = {p:.4f}")
# Read the simulated result rather than assuming a particular p-value.
# Also inspect group means and effect sizes.6.6. p-values: correct reading and multiple testing
Pitfalls and good practices
- A p-value is not \mathbb{P}(H_0\mid\text{data}): “p=0.03, so H_0 has a 3% chance of being true” reverses the conditioning, exactly like the medical-test mistake.
- p>\alpha is not proof of no effect (low power); large samples can make negligible effects significant — report effect sizes and intervals.
- Multiple testing: with 20 independent true-null tests at 5%, \mathbb{P}(\text{at least one false positive})=1-0.95^{20}\approx64\%. Bonferroni tests each of m hypotheses at \alpha/m (union bound, no independence needed; conservative). Benjamini-Hochberg controls the false discovery rate under independence or positive dependence. Repeatedly choosing prompts, graph variants or configurations on one evaluation set is the same selection problem — a final p-value does not erase that history.
Key takeaways — chapter 6
- Construct a confidence interval by inverting a pivot with a known distribution, and distinguish exact from asymptotic coverage.
- The Neyman-Pearson lemma gives likelihood-ratio optimality for a pair of simple hypotheses.
- Welch’s test is a useful default for two independent means, and paired data call for a paired analysis.
- The \chi^2 statistic compares counts with model expectations, while ANOVA compares between-group and within-group variation.
- A p-value is a null tail probability for a statistic, not a posterior probability of H_0.
7. Linear regression
A complete predictive baseline in one model: loss, optimization, uncertainty, diagnostics. Write y=X\beta^\star+\varepsilon, \qquad X\in\mathbb{R}^{n\times p},\quad \beta^\star\in\mathbb{R}^p,\quad y,\varepsilon\in\mathbb{R}^n. p counts all coefficients, intercept included. For inference, treat X as fixed with full column rank, n>p, and \varepsilon\sim\mathcal{N}(0,\sigma^2I_n); least-squares fitting itself needs no Gaussian noise.
7.1. Least squares: the geometry of projection
Theorem 7.1 — Geometric characterization A minimizer of \|y-X\beta\|^2 is characterized by X^\top(y-X\hat\beta)=0 \qquad\text{(normal equations)}. The residual is orthogonal to the columns of X: \hat y=X\hat\beta is the orthogonal projection of y onto \mathrm{Im}(X).
The fitted vector is always unique; \hat\beta is unique when the columns of X are independent, in which case \hat\beta=(X^\top X)^{-1}X^\top y.
Proof. By computation: \|y-X\beta\|^2 is convex with gradient 2X^\top(X\beta-y).
By geometry: decompose y=\Pi y+(I-\Pi)y with \Pi the projection onto \mathrm{Im}(X); orthogonality gives \|y-X\beta\|^2=\|(I-\Pi)y\|^2+\|\Pi y-X\beta\|^2, where the first term is constant and the second vanishes at \hat y=\Pi y.
Hence the residual lies in \mathrm{Im}(X)^\perp — the normal equations — and \|y\|^2=\|\hat y\|^2+\|y-\hat y\|^2, the decomposition behind R^2. ∎
Theorem 7.2 — Gauss-Markov Under full column rank, \mathbb{E}[\varepsilon]=0 and \mathrm{Cov}(\varepsilon)=\sigma^2I_n, least squares has minimal covariance among estimators of \beta^\star that are linear in y and unbiased (“BLUE”). Gaussianity is not needed for this comparison. With Gaussian noise, least squares is also the MLE for \beta^\star.
Proof. Write a linear unbiased estimator as \delta=Cy, where CX=I_p. Set D=C-(X^\top X)^{-1}X^\top, so DX=0. Then \delta=\hat\beta+Dy, and CC^\top=(X^\top X)^{-1}+DD^\top, because the cross term (X^\top X)^{-1}X^\top D^\top=(X^\top X)^{-1}(DX)^\top vanishes.
Therefore \mathrm{Cov}(\delta) =\mathrm{Cov}(\hat\beta)+\sigma^2DD^\top \succcurlyeq \mathrm{Cov}(\hat\beta) =\sigma^2(X^\top X)^{-1}.
The matrix DD^\top is positive semidefinite, so every linear combination has at least as much variance under \delta. For Gaussian noise, the log-likelihood in \beta is -\frac1{2\sigma^2}\|y-X\beta\|^2+\text{const.}: maximizing it is least squares. ∎
7.2. Inference on the coefficients
Theorem 7.3 — Exact distribution of \hat\beta under Gaussian noise \hat\beta\sim\mathcal{N}\big(\beta^\star,\sigma^2(X^\top X)^{-1}\big), \qquad \frac{(n-p)\hat\sigma^2}{\sigma^2}\sim\chi^2_{n-p}, \qquad \hat\sigma^2=\frac{\|y-X\hat\beta\|^2}{n-p}. The coefficient estimator and residual variance estimator are independent.
Proof. The estimator \hat\beta=\beta^\star+(X^\top X)^{-1}X^\top\varepsilon is an affine transformation of a Gaussian vector, with covariance \sigma^2(X^\top X)^{-1}.
For the residual, r=(I-H)\varepsilon with H=X(X^\top X)^{-1}X^\top an orthogonal projector of rank n-p: \|r\|^2/\sigma^2\sim\chi^2_{n-p}.
Independence follows from H(I-H)=0 (zero cross-covariance, jointly Gaussian). Estimating p coefficients leaves n-p residual dimensions — same mechanism as n-1 for one mean. ∎
Proposition 7.4 — t tests and per-coefficient intervals t_j=\frac{\hat\beta_j}{\hat\sigma\sqrt{[(X^\top X)^{-1}]_{jj}}} \sim t_{n-p} \quad\text{under }H_0:\beta_j=0. A coefficient CI is \hat\beta_j\pm t_{1-\alpha/2,n-p}\hat\sigma\sqrt{[(X^\top X)^{-1}]_{jj}}. These are the classical regression-table calculations, conditional on the stated model and design. Choosing features after inspecting their significance requires additional selection-aware analysis.
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
n, p = 200, 3
X = np.column_stack([np.ones(n), rng.uniform(0, 10, n), rng.normal(0, 1, n)])
beta_star = np.array([1.0, 2.0, -0.5])
y = X @ beta_star + rng.normal(0, 2.0, n)
# Least squares + full inference by hand (theorem 7.3)
XtX_inv = np.linalg.inv(X.T @ X)
beta_hat = XtX_inv @ X.T @ y
resid = y - X @ beta_hat
sigma2_hat = resid @ resid / (n - p)
se = np.sqrt(np.diag(XtX_inv) * sigma2_hat)
t_stat = beta_hat / se
pvals = 2 * stats.t.sf(np.abs(t_stat), df=n - p)
print(np.c_[beta_hat, se, t_stat, pvals].round(4))
# A realized |t| near 1 gives a two-sided p near 0.3.
# For a prespecified pure-noise coefficient, however, the null p-value varies:
# it is not guaranteed to be nonsignificant in a particular sample.
# Same estimation with scikit-learn; this does not provide the inference table
from sklearn.linear_model import LinearRegression
print(LinearRegression().fit(X[:, 1:], y).coef_.round(3))The explicit inverse mirrors the formulas. For numerical fitting, prefer QR/SVD-based least squares such as np.linalg.lstsq(X, y, rcond=None), especially when columns are nearly dependent.
7.3. Goodness of fit and diagnostics
Proposition 7.5 — R^2 and adjusted R^2 For in-sample least squares with an intercept, R^2=1-\frac{\sum_i(y_i-\hat y_i)^2}{\sum_i(y_i-\bar y)^2} =\frac{\mathrm{SSB}}{\mathrm{SST}}, \qquad F=\frac{R^2/(p-1)}{(1-R^2)/(n-p)} (the Gaussian test that all slopes are zero). Adding columns mechanically increases training R^2; adjusted R^2=1-(1-R^2)\frac{n-1}{n-p} partially corrects, but model selection still needs validation — held-out R^2 can be negative.
Proposition 7.6 — Diagnostics to check systematically
- Residuals vs fitted values: look for a structureless scatter with roughly constant spread. A funnel shape indicates heteroscedasticity, which invalidates the classical standard errors unless a variance model or robust correction is used; curvature indicates a misspecified conditional mean.
- QQ-plot of residuals: this checks the Gaussian assumption behind the exact t/F inference, remembering that fitted residuals are constrained and are not iid draws.
- Leverages: the values h_{ii}=[H]_{ii} lie in [0,1] and sum to p. The heuristic h_{ii}>2p/n flags unusual predictor values to inspect, not to delete automatically; studentized residuals and Cook’s distance combine leverage and residual size.
- Multicollinearity: nearly dependent columns inflate (X^\top X)^{-1} and destabilize the coefficients. The remedies are to remove or combine redundant predictors, or to use ridge regularization.
Proposition 7.7 — Confidence interval vs prediction interval For a new predictor vector x_0\in\mathbb{R}^p, the CI for the mean x_0^\top\beta^\star is \hat y_0\pm t_{1-\alpha/2,n-p}\hat\sigma \sqrt{x_0^\top(X^\top X)^{-1}x_0}. For an independent future observation with the same Gaussian noise model, the prediction interval adds individual noise: \hat y_0\pm t_{1-\alpha/2,n-p}\hat\sigma \sqrt{1+x_0^\top(X^\top X)^{-1}x_0}. The “1+” makes it wider. Predicting an average outcome is not the same uncertainty problem as predicting an individual outcome.
Key takeaways — chapter 7
- Least squares is an orthogonal projection, so the residual is orthogonal to every column of X.
- Gauss-Markov makes OLS the best linear unbiased estimator under second-moment assumptions, and Gaussian noise additionally makes it the MLE.
- Gaussian coefficients combined with an independent \chi^2_{n-p} residual statistic yield the classical t tests.
- A confidence interval for the mean is not a prediction interval, and diagnostics plus held-out evaluation should precede any performance claim.
8. Bayesian statistics
After 8 successes in 10 trials, the empirical frequency is 0.8 but a uniform Beta prior gives a posterior mean of 0.75: the difference is a modeling choice about uncertainty, not an arithmetic disagreement. The frequentist treats the parameter as fixed; the Bayesian represents uncertainty about it with a prior and updates that distribution with the data. This chapter is optional deepening, useful for posterior inference, latent-variable models and uncertainty analysis.
Definition 8.1 — Prior, posterior \pi(\theta\mid X_1,\dots,X_n) =\frac{L(\theta)\pi(\theta)}{\int L(u)\pi(u)\,du} \qquad(\text{posterior}\propto\text{likelihood}\times\text{prior}), when the evidence (the denominator, independent of \theta) is positive and finite. Sequential updating reuses today’s posterior as tomorrow’s prior.
8.1. Conjugacy: Bernoulli-Beta
Theorem 8.2 If \theta\sim\mathrm{Beta}(a,b) and X_i\mid\theta are iid Bernoulli(\theta), then \theta\mid X_1,\dots,X_n \sim\mathrm{Beta}(a+k,b+n-k), \qquad k=\sum_iX_i.
Proof. Prior \propto\theta^{a-1}(1-\theta)^{b-1} times likelihood \theta^k(1-\theta)^{n-k} gives \pi(\theta\mid x)\propto\theta^{a+k-1}(1-\theta)^{b+n-k-1} — the kernel of a Beta(a+k,b+n-k) density. The family is closed under the update: conjugacy. ∎
Example 8.3 — Sequential updating, with numbers Start from the prior \mathrm{Beta}(1,1) — the uniform, which is a particular choice rather than “knowing nothing”. Observing 8 successes in 10 trials updates it to the posterior \mathrm{Beta}(9,3). Its mean is 9/12=0.75, to be compared with the MLE 0.8, and its 95% equal-tail credible interval, read from the 2.5% and 97.5% quantiles, is approximately [0.482,0.940]. Each new observation updates the two counts — the mechanism behind Bayesian bandits.
from scipy import stats
post = stats.beta(9, 3)
print(post.mean().round(3), post.ppf([0.025, 0.975]).round(3))8.2. Gaussian-Gaussian conjugacy
Theorem 8.4 Model: X_i\mid\mu iid \mathcal{N}(\mu,\sigma^2) with known \sigma>0; prior \mu\sim\mathcal{N}(\mu_0,\tau^2), \tau>0. Then \mu\mid\bar X_n \sim\mathcal{N}\!\left( \frac{\mu_0/\tau^2+n\bar X_n/\sigma^2}{1/\tau^2+n/\sigma^2}, \;\frac1{1/\tau^2+n/\sigma^2} \right).
Proof. Write p=1/\tau^2 and q=n/\sigma^2 for the precisions in this calculation. As a function of \mu, the prior times likelihood is proportional to \exp\Big(-\frac p2(\mu-\mu_0)^2-\frac q2(\mu-\bar X_n)^2\Big). Complete the square: -\frac p2(\mu-\mu_0)^2-\frac q2(\mu-\bar X_n)^2 =-\frac{p+q}{2}\Big(\mu-\frac{p\mu_0+q\bar X_n}{p+q}\Big)^2 +\text{const.}, where the constant does not depend on \mu. This is a Gaussian kernel with precision p+q and a precision-weighted arithmetic mean. ∎
Precisions add up The posterior variance 1/(p+q) is smaller than both 1/p and 1/q; with a fixed proper prior, q=n/\sigma^2 eventually dominates and the posterior concentrates at \bar X_n with variance \sigma^2/n. “The data eventually dominate” holds in this regime — not a universal guarantee for weakly identified or growing-dimensional problems.
8.3. Credible interval vs confidence interval
Definition 8.5 — Credible interval A 1-\alpha credible interval satisfies \mathbb{P}(\theta\in C\mid\text{data})=1-\alpha under the posterior: a probability about \theta given the observed data and model. A confidence interval instead has a repeated-sampling coverage property for fixed \theta.
Example 8.6 — The same experiment, two readings Known \sigma=1, one observation x=0.7. Frequentist: [x-1.96,x+1.96]=[-1.26,2.66] belongs to a procedure covering the fixed mean in 95% of repeated samples — not a probability about this particular interval. Bayesian: the flat prior gives \mu\mid x\sim\mathcal{N}(x,1), and the same interval satisfies \mathbb{P}(\mu\in C\mid x)=0.95. The numbers coincide here; the semantics differ, and with another prior the numbers differ too. Choose the construction for the uncertainty question and report its assumptions.
8.4. MAP vs MLE
Definition 8.7 — MAP estimator The maximum a posteriori estimator maximizes the posterior: \hat\theta_{\mathrm{MAP}} \in\arg\max_\theta\big[\log L(\theta)+\log\pi(\theta)\big]. A flat prior makes this coincide with MLE; density modes depend on parameterization. Example: Beta(2,2) prior and 3 successes in 4 trials give Beta(5,3), with MAP 2/3 versus MLE 3/4.
MAP = regularized MLE, for matching penalties In a negative-log objective, -\log\pi(\theta) is a penalty: Gaussian prior → \ell_2 (ridge), Laplace prior → \ell_1 (lasso). This does not turn every regularization method into posterior inference — data augmentation, early stopping and dropout need their own analysis.
8.5. The Bayesian approach in generation
Bridge toward later reading — preview The VAE is taught in Deep Learning ch. 9; diffusion in its section 9.4 (self-study) and, in depth, in Multimodal Generative AI ch. 3.
- VAE: the latent posterior p_\theta(z\mid x) is approximated by a variational q_\phi(z\mid x) (often Gaussian) via the ELBO — conjugacy gives intuition, but a nonlinear decoder has no exact conjugate posterior.
- Diffusion: the linear-Gaussian forward steps reuse theorem 3.2; learned reverse dynamics and denoising objectives are not repeated conjugate updates.
- Calibration: posterior intervals describe model-based parameter uncertainty; neither Bayesian wording nor a nominal 95% level guarantees empirical calibration under misspecification or shift.
Key takeaways — chapter 8
- The posterior is proportional to the likelihood times the prior; be able to derive the Beta-Bernoulli and Gaussian-Gaussian updates.
- Gaussian precisions add, and the posterior mean is the precision-weighted average.
- A credible probability about a parameter is not the frequentist coverage of a procedure.
- The MAP estimate connects some regularized objectives to priors, but a point estimate is not a full posterior.
9. From statistics to machine learning
Each statistical pillar becomes a learning question: what is estimated, what loss is minimized, what is random, and what evidence supports performance on new units?
9.1. Empirical risk minimization (ERM)
Definition 9.1 — Risk and empirical risk Let D_n=\{(X_i,Y_i)\}_{i=1}^n be drawn iid from P. For a loss \ell(\hat y,y) and a predictor f, the risk and empirical risk are R(f)=\mathbb{E}_{(X,Y)\sim P}\big[\ell(f(X),Y)\big], \qquad \hat R_n(f)=\frac1n\sum_{i=1}^n\ell(f(X_i),Y_i). ERM picks \hat\theta\in\arg\min_\theta\hat R_n(f_\theta) in a parametric family, hoping for low population risk (unsupervised learning drops Y).
Proof. Why averages help. For a fixed predictor f, the LLN gives \hat R_n(f)\to R(f), with CLT fluctuations on the scale \mathrm{sd}(\ell(f(X),Y))/\sqrt n.
Where selection enters. The fitted f_{\hat\theta} was selected after observing the sample: pointwise convergence does not control \sup_\theta|\hat R_n(f_\theta)-R(f_\theta)|.
Uniform convergence and complexity control (or stability) give generalization guarantees — Machine Learning ch. 8; held-out evaluation measures the selected procedure on the target population. Without either, low training loss can be noise fitting. ∎
9.2. Bias-variance in prediction, by computation
Theorem 9.2 — Decomposition of the generalization error At a fixed input x, let Y=f(x)+\varepsilon with noise variance \sigma^2 independent of the training sample, \hat f trained on random data, \bar f(x)=\mathbb{E}[\hat f(x)]. Then \mathbb{E}\big[(Y-\hat f(x))^2\big] =\underbrace{\sigma^2}_{\text{noise}} +\underbrace{\big(f(x)-\bar f(x)\big)^2}_{\text{bias}^2} +\underbrace{\mathrm{Var}(\hat f(x))}_{\text{variance}}.
Proof. With g=\hat f(x)-\bar f(x) and b=\bar f(x)-f(x): Y-\hat f(x)=\varepsilon-b-g, the three terms are independent or constant and centered, so all cross terms vanish — theorem 5.2 plus an irreducible noise term. ∎
Example 9.3 — Seeing the trade-off in simulation
import numpy as np
rng = np.random.default_rng(0)
def f(x): # true function: modulated sine
return np.sin(2 * x) + 0.3 * x
n_train, n_rep = 40, 300 # small samples, many repetitions
x_test = np.linspace(-3, 3, 200)
noise = 0.15**2
for deg in range(1, 13):
preds = np.zeros((n_rep, x_test.size))
for r in range(n_rep):
x = rng.uniform(-3, 3, n_train)
y = f(x) + rng.normal(0, 0.15, n_train)
c = np.polyfit(x, y, deg) # polynomial of degree `deg`
preds[r] = np.polyval(c, x_test)
sq_b = ((f(x_test) - preds.mean(axis=0))**2).mean() # bias²
v = preds.var(axis=0).mean() # variance
print(f"deg={deg:2d} bias^2={sq_b:.4f} var={v:.4f} "
f"err={sq_b + v + noise:.4f}")
# Low degree: large bias. High degree: unstable variance, worst at boundaries.
# Select complexity by validation, not by decreasing training error.The simulation knows f and repeats the training experiment, so it can separate the two error sources — a single real dataset usually cannot. The pattern motivates regularization and validation; it does not promise a universal U-shaped test curve.
9.3. MLE to cross-entropy: the exact bridge
Theorem 9.4 — Maximizing likelihood = minimizing empirical cross-entropy For a conditional model p_\theta(y\mid x), \frac1n\sum_i\log p_\theta(y_i\mid x_i) =-\,\widehat{\mathrm{CE}}(p_{\text{data}},p_\theta), with no extra entropy constant: empirical cross-entropy is the negative average conditional log-likelihood. Specializing the model recovers the usual losses. Bernoulli labels give the binary cross-entropy -\frac1n\ell(\theta) =\frac1n\sum_i\big[-y_i\log\hat p_\theta(x_i) -(1-y_i)\log(1-\hat p_\theta(x_i))\big], categorical labels with logits z_i\in\mathbb{R}^K give the softmax loss -\log p_\theta(y_i\mid x_i) =-\log\frac{e^{z_{i,y_i}}}{\sum_k e^{z_{i,k}}}, and a Gaussian conditional model with fixed variance gives scaled squared error plus a constant. A probabilistic loss therefore makes the observation-model choice explicit; margin or ranking losses need not be likelihoods.
Proof. The optimization equivalence is the definition.
The entropy constant only enters the population identity, for a discrete target with true conditional law p^\star: \mathrm{CE}(p^\star,p_\theta) =H(Y\mid X) +\mathbb{E}_X\!\left[ \mathrm{KL}\big(p^\star(\cdot\mid X)\,\|\,p_\theta(\cdot\mid X)\big) \right], whose first term does not depend on \theta.
The raw empirical point-mass has infinite KL to a continuous density — that is not the finite-sample justification for Gaussian MLE. ∎
A from-scratch affine MNIST classifier is a concrete instance: x\in\mathbb{R}^{784}, logits z=Wx+b, softmax, categorical cross-entropy — the statistical objective without hidden layers.
9.4. Four correspondences to take away
- Empirical risk: LLN/CLT describe a fixed predictor’s loss; selection-aware arguments address learned ones.
- Bias-variance: estimation error becomes a prediction trade-off plus observation noise (simulation 9.3).
- Likelihood → loss: probabilistic models yield squared-error and cross-entropy; VAEs and diffusion optimize variational bounds or denoising objectives (preview: VAEs in Deep Learning ch. 9, diffusion in its section 9.4 and in Multimodal Generative AI ch. 3).
- Conditioning → prediction: \mathbb{E}[Y\mid X] is the squared-loss target; LLMs estimate next-token laws conditioned on context — sequence dependence and evaluation come later.
Key takeaways — chapter 9
- ERM is an empirical average of a loss, and selecting a model requires more than a pointwise LLN.
- The squared prediction error decomposes as noise plus bias² plus variance under the stated independence assumptions.
- The negative conditional log-likelihood equals the empirical cross-entropy, and the entropy-plus-KL identity has its own scope.
- This refresher supplies statistical entry tools, not all of ML and DL: optimization, representation learning and dependence-aware evaluation belong to the next modules.
10. Missing data: mechanisms, baselines and research
Before choosing an imputer, ask what is missing, why, and whether the target is population estimation or prediction from incomplete inputs. This research extension is optional: read it when missingness affects the task.
10.1. Missingness mechanisms: MCAR, MAR, MNAR
Definition 10.1 — Missingness formalism Let M be the missingness indicator matrix, with M_{ij}=1 if X_{ij} is missing; we observe the pair (X_{\text{observed}},M), never the whole matrix X.
- MCAR (Missing Completely At Random): M\perp X. The missingness depends on neither observed nor unobserved values — think of random sample loss or a sensor failure unrelated to the measured process.
- MAR (Missing At Random): \mathbb{P}(M=m\mid X) depends only on the entries observed under that pattern; a common shorthand is M\perp X_{\text{missing}}\mid X_{\text{observed}}. For example, response rates may depend on age while age itself is observed.
- MNAR (Missing Not At Random): the probability of missingness also depends on the missing values themselves — high incomes go unreported, and severely ill patients skip the questionnaire.
MCAR is a special case of MAR. Ignoring the mechanism in likelihood inference requires MAR plus distinctness of the model and missingness parameters, and observed data alone cannot establish MAR rather than MNAR: an MNAR analysis needs additional assumptions, external information or a sensitivity analysis.
10.2. The bias of naive solutions: worked examples
Example 10.2 — Row deletion (listwise deletion) Consider 1,000 clients with standardized, jointly Gaussian variables (X_1,X_2) correlated at \rho=0.6, and suppose 30% of X_2 is missing.
Under MCAR, deleting incomplete rows preserves the population distribution in expectation but keeps only about 700 rows, inflating all estimation variances by approximately 1/0.7=1.43.
Under a MAR threshold (keep X_2 only when X_1<q_{0.7}\approx0.524), Gaussian conditioning gives \mathbb{E}[X_2\mid\text{kept}] =\rho\,\mathbb{E}[X_1\mid X_1<q_{0.7}] =-0.6\,\frac{\varphi(q_{0.7})}{0.7} \approx-0.298: the mean shifts by almost a third of a standard deviation, and the missing region has no overlap — recovering it needs extrapolation assumptions, not MAR alone.
Example 10.3 — Mean imputation Return to the MCAR version and replace each missing X_2 by the observed mean, which is close to zero. Three effects follow. First, the mean is approximately preserved. Second, the variance drops to about 0.7 instead of 1, because 30% of the mass piles up at zero. Third, only the observed pairs contribute to the covariance, which becomes \mathrm{Cov}_{\text{imp}}(X_1,X_2)\approx0.7\times0.6=0.42. The distorted covariance can bias regression coefficients, though not always toward zero — the effect depends on the model and the target. Under MAR these calculations do not even apply, since the observed mean is already biased.
10.3. Doing better: regression imputation and beyond
Proposition 10.4 — Regression imputation under additional conditions Under MAR, adequate overlap and a consistently estimated conditional model, the squared-error target for imputing X_2 is \mathbb{E}[X_2\mid X_{\text{observed}}]: fit on observed rows, predict missing entries. This can recover a marginal mean, but underestimates variation by inserting the conditional center rather than a draw. Refinements: stochastic imputation (center + calibrated residual noise), multiple imputation (several completed datasets, within/between uncertainty combined), EM for latent likelihoods, MICE for chained conditionals. With a deterministic missing region (example 10.2) overlap fails and an extrapolation model is additionally needed. Prediction from incomplete inputs remains a different target from complete-data estimation.
10.4. Selected research on prediction with missing values
Paper 1 — Constant imputation + linear model: non-consistency (AISTATS 2020) “Linear predictor on linearly-generated data with missing values: non consistency and solutions”, PMLR 108. Even with linear complete-data regression, the optimal predictor from incomplete inputs can need different affine functions per mask: with Y=\beta_1X_1+\beta_2X_2+\varepsilon and X_2 missing under MCAR, standardized jointly Gaussian predictors (zero mean, unit variance, correlation \rho, as in example 10.2) give the conditional mean (\beta_1+\rho\beta_2)X_1 on that mask. Without standardization it is affine, with slope \beta_1+\rho\beta_2\sigma_2/\sigma_1. A single linear predictor after constant imputation is not Bayes consistent — mask interactions are needed.
Paper 2 — NeuMiss (NeurIPS 2020) “NeuMiss networks: differentiable programming for supervised learning with missing values”. Gaussian conditional prediction inverts covariance submatrices selected by the mask; the Neumann expansion A^{-1}=\eta\sum_k(I-\eta A)^k (when \rho(I-\eta A)<1) motivates layers that process values and masks jointly. Code: github.com/dirty-cat/NeuMiss.
Paper 3 — Which imputation for prediction? (NeurIPS 2021) “What’s a good imputation to predict with missing values?”. With a sufficiently rich, consistent downstream regressor, broad classes of impute-then-regress procedures are Bayes optimal for prediction from available information (MCAR, MAR, specified MNAR). Practical hypothesis: a simple imputation with the mask explicitly retained may suffice — compare that baseline before elaborate imputation.
Paper 4 — Imputation: diminishing returns (2024) “Imputation for prediction: beware of diminishing returns”. Benchmarks show when sophisticated imputation adds little over simpler choices — an empirical question about data, capacity, missingness and evaluation. Fit preprocessing inside training folds; keep the simpler baseline unless complexity buys a reproducible benefit.
Connection to Graph × LLM Missing metadata in a corpus and unobserved relations in a graph both need an observation model; an unobserved edge is not a negative edge. Transfer the questions — what is observed, what is the target, how selection occurs — not an imputation theorem unchanged. The module catalogue lists the next destinations.
Key takeaways — chapter 10
- MCAR, MAR and MNAR describe an observation mechanism, not just a data-cleaning inconvenience.
- Under MCAR, complete cases remain representative for marginal estimation, while other targets may admit other conditions.
- Mean imputation distorts the variance and the covariance, and conditional-mean imputation still omits the residual variability.
- Estimating complete-data quantities is a different task from predicting with incomplete inputs.
- Use the four papers to formulate and test a baseline, keeping their assumptions and finite-sample limits visible.
Exercises
★ Practical Bayes. A test detecting a virus affecting 1% of the population has sensitivity 99% and specificity 95%. A patient tests positive. What is the probability of infection? What if two tests are positive, assuming their outcomes are independent conditional on infection status?
One positive: \mathbb{P}(M\mid+) =\frac{0.99\times0.01}{0.99\times0.01+0.05\times0.99} \approx0.167. Two positives under the stated conditional independence: \mathbb{P}(M\mid++) =\frac{0.99^2\times0.01}{0.99^2\times0.01+0.05^2\times0.99} =\frac{0.009801}{0.012276} \approx0.798. The probability rises from about 17% to 80%. Repeating the calculation with squared likelihoods is unjustified if the tests share errors beyond their common dependence on infection status.
★ Reverse Simpson. Build a contingency table with 2 groups and 2 treatments in which treatment A is better overall but worse within each group. Explain the mechanism.
Swap the treatment labels in example 1.11:
Group A B Mild 470/500 = 94% 95/100 = 95% Severe 8/50 = 16% 80/200 = 40% Overall 478/550 ≈ 87% 175/300 ≈ 58% A receives many more mild cases, so the aggregate comparison reverses the within-group comparison. Randomization can remove this assignment imbalance in expectation; observational adjustment needs a justified causal model.
★ Normal approximation. A factory produces parts of which 8% are defective. In a batch of 500 independent parts, approximate the probability of more than 55 defects.
N\sim\mathcal{B}(500,0.08) has mean 40 and variance 36.8. Without continuity correction, \mathbb{P}(N>55)\approx1-\Phi\!\left(\frac{55-40}{\sqrt{36.8}}\right)\approx0.007. Since N>55 means N\geq56, a continuity correction uses 55.5 and gives approximately 0.0053. Compare both with
scipy.stats.binom.sf(55, 500, 0.08); a tail approximation can have appreciable relative error.★ Numerical Chebyshev. Request time has mean 200 ms and standard deviation 40 ms. (a) Bound the probability of exceeding 320 ms without specifying a distribution. (b) Compute it under a Gaussian model.
- Without any distributional assumption, the inclusion \{X>320\}\subseteq\{|X-200|\geq120\} lets Chebyshev bound \mathbb{P}(X>320)\leq\frac{40^2}{120^2}=\frac19\approx0.111.
- Under a Gaussian model, \mathbb{P}(X>320)=1-\Phi(3)\approx0.00135: the distribution-free bound is about 82 times larger. Chebyshev is conservative here, and the smaller number is only as credible as the Gaussian tail assumption.
★ Stable sums. Using MGFs, show that the sum of two independent Poissons is Poisson and that two independent gammas with the same scale sum to a gamma. Deduce the sum and mean distributions for iid exponentials.
Poisson: e^{\lambda_1(e^t-1)}e^{\lambda_2(e^t-1)} =e^{(\lambda_1+\lambda_2)(e^t-1)}. Gamma: (1-bt)^{-a_1}(1-bt)^{-a_2}=(1-bt)^{-(a_1+a_2)}. Thus \sum_iX_i\sim\Gamma(n,1/\lambda) for iid \mathcal{E}(\lambda) variables, and \bar X_n\sim\Gamma(n,1/(n\lambda)). Keep scale and rate conventions separate.
★ Full t interval in code. Write
mean_ci(x, alpha=0.05)returning the t confidence interval for a mean. Over 10,000 Gaussian samples of size 20, check the proportion containing the true mean.import numpy as np from scipy import stats def mean_ci(x, alpha=0.05): x = np.asarray(x) n = len(x) m, s = x.mean(), x.std(ddof=1) tq = stats.t.ppf(1 - alpha/2, df=n - 1) return m - tq*s/np.sqrt(n), m + tq*s/np.sqrt(n) rng = np.random.default_rng(0) mu, n_rep = 3.0, 10_000 covered = 0 for _ in range(n_rep): sample = rng.normal(mu, 1.0, 20) lo, hi = mean_ci(sample) # both endpoints from the SAME sample covered += (lo <= mu <= hi) print(covered / n_rep) # close to 0.95 print(np.sqrt(0.95 * 0.05 / n_rep)) # Monte Carlo SE ~0.0022Each repetition builds one interval from one sample; the Monte Carlo fluctuation (±0.002 here) explains deviations from exactly 0.95. Next: try skewed or dependent observations and name the assumption that changed.
★ Sequential Bayesian updating. Start with a Beta(2,2) prior on click probability p. Observe 3 clicks, then 1 failure, then 6 clicks. Give each posterior, the final 90% credible interval and the MAP estimate. Distinguish the MAP from posterior-predictive click probability.
The successive posteriors are Beta(5,2), Beta(5,3) and Beta(11,3). The final MAP is \frac{11-1}{11+3-2}=\frac{10}{12}=\frac56\approx0.833. The posterior-predictive probability of the next click is instead the posterior mean 11/14\approx0.786. The equal-tail 90% credible interval is
scipy.stats.beta(11, 3).ppf([0.05, 0.95]), approximately [0.59,0.93]. Thompson sampling uses a draw from this posterior, not just its mode.★ Sampling distribution and coverage in code. Simulate 10,000 Gaussian samples of size 50, plot their sample means with the theoretical density, and check coverage of \bar X_n\pm1.96s/\sqrt n.
import numpy as np, matplotlib.pyplot as plt from scipy import stats rng = np.random.default_rng(0) samples = rng.normal(5.0, 2.0, size=(10_000, 50)) means = samples.mean(axis=1) plt.hist(means, bins=60, density=True, alpha=.6) grid = np.linspace(4, 6, 300) plt.plot(grid, stats.norm(5.0, 2.0/np.sqrt(50)).pdf(grid), 'r') plt.show(); plt.close() lo, hi = means - 1.96*samples.std(axis=1, ddof=1)/np.sqrt(50), means + 1.96*samples.std(axis=1, ddof=1)/np.sqrt(50) print(((lo <= 5.0) & (5.0 <= hi)).mean()) # close to, but below, 0.95 # Exact Gaussian t procedure, since sigma was estimated tq = stats.t.ppf(0.975, df=49) se = samples.std(axis=1, ddof=1) / np.sqrt(50) lo_t, hi_t = means - tq*se, means + tq*se print(((lo_t <= 5.0) & (5.0 <= hi_t)).mean()) # close to 0.95Gaussian sample means are exactly Gaussian. With estimated s, the z interval covers ≈94.4% here; the exact t critical value is 2.010, not 1.96 —
ddof=1fixes the variance estimator, not the critical value.★ A two-state chain and a random walk. (a) The weather is sunny (state 1) or rainy (state 2), with transition matrix P=\begin{pmatrix}0.8&0.2\\0.4&0.6\end{pmatrix}. Find the stationary law, the probability of rain in two days given sun today, and the factor by which the gap to the stationary law shrinks at each step. (b) On a connected undirected graph with m edges and degrees d_v, show that the random walk P=D^{-1}A satisfies detailed balance with \pi_v=d_v/(2m).
Detailed balance 0.2\,\pi_1=0.4\,\pi_2 with \pi_1+\pi_2=1 gives \pi=(2/3,1/3). In two steps from state 1, (P^2)_{12}=0.8\times0.2+0.2\times0.6=0.28. The second eigenvalue is \operatorname{tr}P-1=0.4: the gap is multiplied by 0.4 at each step, as in example 2.19. Check with
np.linalg.matrix_power(P, 50)[0], which is close to (0.667,0.333).For an edge \{u,v\}, \pi_uP_{uv}=\frac{d_u}{2m}\cdot\frac1{d_u}=\frac1{2m}=\pi_vP_{vu}, and both sides are 0 for a non-edge. Proposition 2.18 then makes \pi stationary: this is Proposition 0.6 of Graph ML, behind random-walk embeddings and PageRank.
★★ MLE of the exponential distribution. For iid X_i\sim\mathcal{E}(\lambda), show that \hat\lambda_{\mathrm{MLE}}=1/\bar X_n and compute its bias.
\ell(\lambda)=n\log\lambda-\lambda\sum_iX_i gives \hat\lambda=n/\sum_iX_i. With the shape-scale convention, \sum_iX_i\sim\Gamma(n,1/\lambda), \qquad \bar X_n\sim\Gamma\big(n,1/(n\lambda)\big). For n>1, \mathbb{E}[1/\bar X_n]=n\lambda/(n-1), so the bias is \lambda/(n-1). For n=1, the estimator has infinite expectation.
★★ Poisson MLE and Fisher. For iid X_i\sim\mathcal{P}(\lambda), \lambda>0: (a) derive the MLE; (b) compute Fisher information using both identities of theorem 5.6; (c) check the Cramér-Rao bound.
- The MLE is \hat\lambda=\bar X_n. (b) For one observation the score is s(\lambda)=X/\lambda-1, so its variance gives I(\lambda)=\mathrm{Var}(X/\lambda)=\frac{\lambda}{\lambda^2}=\frac1\lambda, and the curvature identity gives the same value: -\mathbb{E}[\ell''(\lambda)]=\mathbb{E}[X]/\lambda^2=1/\lambda. Finally, for (c): since \mathrm{Var}(\bar X_n)=\lambda/n=1/(nI(\lambda)), the unbiased estimator attains the bound in finite samples.
★★ Change of variable. If X\sim\mathcal{N}(0,1), determine the densities of Y=X^2 and Z=|X|.
Squaring is not injective: split into positive and negative branches and sum their contributions: f_Y(y)=\frac1{\sqrt{2\pi y}}e^{-y/2},\qquad y>0. This is \chi^2_1, equivalently \Gamma(1/2,2) in shape-scale notation. For the half-normal variable, f_Z(z)=2\varphi(z) for z\geq0, and zero for z<0.
★★ Applied Neyman-Pearson. For iid X_i\sim\mathcal{E}(\lambda), derive the likelihood-ratio test of \lambda=\lambda_0 against \lambda=\lambda_1>\lambda_0.
\frac{L_1}{L_0} =\left(\frac{\lambda_1}{\lambda_0}\right)^n \exp\left(-(\lambda_1-\lambda_0)\sum_iX_i\right). The ratio increases as S=\sum_iX_i decreases, so reject for S\leq c. Under H_0, S\sim\Gamma(n,1/\lambda_0) in shape-scale notation.
Choose c as its lower \alpha quantile, so \mathbb{P}_{\lambda_0}(S\leq c)=\alpha.
★★ Regression by hand. Derive the normal equations and show uniqueness when the columns of X are linearly independent.
Set \nabla_\beta\|y-X\beta\|^2=2X^\top(X\beta-y)=0, giving X^\top X\beta=X^\top y. For nonzero a, a^\top X^\top Xa=\|Xa\|^2>0 iff X has independent columns. Thus X^\top X is positive definite and invertible. Reproduce the same result geometrically using theorem 7.1.
★★ Gauss-Markov in dimension 1. In y_i=\mu+\varepsilon_i, with zero-mean uncorrelated errors of common variance \sigma^2, show that the sample mean has minimum variance among linear unbiased estimators \sum_iw_iy_i.
Unbiasedness requires \sum_iw_i=1. Cauchy-Schwarz gives \mathrm{Var}\Big(\sum_iw_iy_i\Big) =\sigma^2\sum_iw_i^2 \geq\sigma^2\frac{(\sum_iw_i)^2}{n} =\frac{\sigma^2}{n} =\mathrm{Var}(\bar Y). Equality holds iff all weights equal 1/n. This is the one-parameter case of theorem 7.2.
★★★ Missing data. In a MAR setting where X_2 is more often missing for large X_1, explain why consistently estimating and imputing \mathbb{E}[X_2\mid X_1] can recover \mathbb{E}[X_2] but underestimate \mathrm{Var}(X_2). State the required overlap or extrapolation assumption. What addition addresses the missing conditional variance?
MAR plus overlap allows the observed rows to identify the conditional law at relevant X_1 values, subject to adequate estimation. A deterministic cutoff instead needs a justified extrapolation model, such as a correctly specified linear Gaussian conditional mean.
Let m(X_1)=\mathbb{E}[X_2\mid X_1]. Replacing a missing value by m(X_1) preserves its conditional mean and hence the marginal mean by the tower property. But it removes residual variation around that mean. Stochastic imputation adds a draw from the estimated conditional residual law; calibrated conditional variance, not arbitrary noise, is required. Proper multiple imputation also accounts for uncertainty in the fitted imputation model.
Exit checkpoint and connections
Before starting Machine Learning — after the four sessions and the self-study chapters 3, 6, 7 and 9 — produce three pieces of evidence:
- A conditioning calculation with the denominator visible (exercise 1).
- A reproducible coverage experiment, one sample per interval, assumptions stated (exercise 6).
- A loss/model derivation plus an evaluation argument: why training loss is not held-out performance.
Graph × LLM transfer check
Toy evaluation, not a reported benchmark. A text-only baseline and a graph-assisted model answer the same 30 questions in three source groups (10 each). Deployment concerns new groups; questions within a group may be dependent.
| Source group | Text-only correct | Graph-assisted correct | Paired accuracy difference |
|---|---|---|---|
| A | 6 / 10 | 7 / 10 | +0.10 |
| B | 7 / 10 | 8 / 10 | +0.10 |
| C | 5 / 10 | 4 / 10 | -0.10 |
| Total | 18 / 30 | 19 / 30 | +1/30\approx+0.033 |
Checkpoint. Compute the overall gain. Does the table establish a reliable improvement on new groups? Specify the split, baseline and uncertainty unit for a larger experiment, and identify a visible failure case.
Expected evidence
- Accuracy rises from 60% to ≈63.3% — one additional correct answer.
- No reliable population claim: 30 related questions are not 30 independent units (three groups only), and marginal counts hide which questions changed.
- Split by deployment unit (source groups); keep preprocessing, graph construction and model selection from leaking held-out information; evaluate both models on the same questions.
- Keep a text-only baseline and a graph control (shuffled/removed edges); report paired gains with group-level uncertainty — not a row bootstrap.
- Group C already refutes “the graph always helps”: inspect its relations before adding complexity.
Capstone evaluation kit
Self-study, about 1 h with the checkpoint above. The projects below, the Period 2 team projects and the end-of-year capstones all end with a claim of the form “system B beats system A on new units”. This kit turns the transfer check into a protocol for such claims.
- Split by deployment unit, then by time. Name the unit the claim is about — a document, a user, a source, a graph component, a molecular scaffold — and put all its rows on one side of the split. With timestamps, train on the past and test on the future. Fit preprocessing, imputation (chapter 10) and graph construction on the training side only; Graph ML Example 8.1 shows the leak this prevents for edges.
- Seeds. Re-run every configuration with at least 3 seeds in Year 1 and at least 5 in Year 2. Report the mean and the spread across seeds, and never keep only the best seed.
- Paired, cluster-level intervals. Evaluate both systems on the same items, take per-item differences, and bootstrap whole units, not rows — the group-level uncertainty of the transfer check. Report the gain with its 95% interval. McNemar’s test, on the pairs where exactly one system is right, is the matching paired test for accuracies. With fewer than about 20 units, report the per-unit results instead of an interval.
- Multiple testing. Count every variant compared on the evaluation data: prompts, graphs, hyperparameters. Control the family with Bonferroni or Benjamini–Hochberg (section 6.6), or label the analysis exploratory.
- Winner’s curse. The best of K validation scores is biased upward: in example 3.6 the maximum of 9 uniform scores averages 0.9. Select on validation, write down the analysis plan, then open the test set once.
- Structure control. For any claim that a graph helps, rerun the pipeline with shuffled edges (degree-preserving) and with no edges. A gain that survives the shuffle does not come from the graph’s edges.
import numpy as np
def paired_cluster_bootstrap(diff, group, B=10_000, seed=0):
"""Mean per-item difference and a 95% CI that resamples whole groups."""
rng = np.random.default_rng(seed)
labels = np.unique(group)
sums = np.array([diff[group == g].sum() for g in labels])
sizes = np.array([(group == g).sum() for g in labels])
idx = rng.integers(0, len(labels), size=(B, len(labels)))
boot = sums[idx].sum(axis=1) / sizes[idx].sum(axis=1)
return diff.mean(), np.quantile(boot, [0.025, 0.975])
rng = np.random.default_rng(1)
group = np.repeat(np.arange(40), 15) # 40 sources, 15 questions each
gain = rng.normal(0.3, 1.0, 40)[group] # the graph helps some sources only
a = rng.random(600) < 0.6 # text-only correct?
b = rng.random(600) < 1 / (1 + np.exp(-(np.log(1.5) + gain))) # graph-assisted
diff = b.astype(float) - a.astype(float)
print(paired_cluster_bootstrap(diff, group)) # this seed: 0.005, [-0.082, 0.090]
row = rng.integers(0, 600, size=(10_000, 600)) # the wrong, row-level bootstrap
print(np.quantile(diff[row].mean(axis=1), [0.025, 0.975])) # [-0.050, 0.058]: too narrowEach piece is taught in depth elsewhere: the reference pipeline of Machine Learning section 4.6, with its leakage and nested cross-validation sections, and its section 4.9 on comparing two models (paired tests, McNemar); the minimal experimental protocol of Advanced Deep Learning Definition 1.1; the honest-benchmarking rules of Boosting to Foundation Models ch. 9; data and model tests in ML Ops ch. 2.
Where to go next—and what remains
| Destination | What this page supplies | What remains |
|---|---|---|
| Machine Learning | Empirical risk, likelihood losses, bias/variance, regression, uncertainty interpretation. | Validation, regularization, optimization, model selection — a pointwise CLT is not a generalization guarantee. |
| Deep Learning (after ML) | Conditional log-likelihood, cross-entropy, random-vector notation, optional Bayesian foundations. | Batched derivatives, chain rule, representation learning — the NN refresher is entry preparation, not DL equivalence. |
| Graph Machine Learning (mandatory, Period 2) | Independence checks, observation mechanisms, absent ≠ negative evidence, random walks as Markov chains (section 2.7). | Relational baselines, message passing, transductive/inductive protocols. |
| Probability / Monte Carlo — not in the 2026–27 LLGA 1 – S1 list; notes kept for reference | Probability spaces, convergence, elementary simulation, finite Markov chains. | Measure-theoretic depth, MCMC and dependent sampling, as needed. |
| Statistical Learning Theory — not in the 2026–27 LLGA 1 – S1 list; notes kept for reference | LLN/CLT, inequalities, pointwise vs uniform. | Finite-sample concentration and complexity bounds; on the LLGA route, uniform convergence is taught in Machine Learning ch. 8. |
Main route: refreshers as needed → Machine Learning → Deep Learning, then the graph and language branches. Bayesian inference, missing-data research and further probability are selective extensions, not universal prerequisites. Return to the reading route when a module exposes a gap.
Sources and scope
Source layers stay separate: catalog information and this site’s study recommendations are not the same thing. Consult official sources for enrolment and assessment requirements.
The record used is the SynapseS 2026–2027 sheet for APM_51438_EP (captured as supplied; the live catalog was not rechecked):
| Field | Catalog-reported | Boundary for these notes |
|---|---|---|
| Teaching volume | 12 h CTD | A reported volume, not the study-time estimate. |
| Total workload / ECTS | Not displayed | No total or credit value is inferred or asserted. |
| Period / language | X-3A-P1 (autumn semester, period 1), 17 Sep–18 Dec 2026; English | Source labels, not a reading schedule. |
| Responsible | Marine Le Morvan (also listed as responsible of the 2026–2027 occurrence) | Named for identification only; no authorship or endorsement of these notes is claimed. |
| Description / objectives / syllabus / prerequisites | Not displayed (the tabs are empty) | The outline and targets here are this site’s choices; an empty field does not mean no prerequisites — use the positioning checks. |
| Assessment | Grade format: numeric /20 (and US letter grade). The section for the LLGA track is empty: no assessment form, resit rule or pass threshold is displayed for LLGA. | The rules shown for other tracks (resit allowed, higher grade kept, unit acquired at ≥ 10) are not transposed here; the exercises are independent self-assessment. |
Because the sheet displays no description, objectives or syllabus, no “official topic → chapter” correspondence table can be drawn up: the ten-chapter outline is not checked against an official list.
The ≈36 h full-pass budget (the 12 h in class plus ≈ 24 h of self-study, see the session plan) is an optional estimate — neither a conversion of the 12 h CTD nor an ECTS allocation; the session split is likewise our proposal. The chapter sequence, simulations, ML bridge, transfer check and selected papers are editorial study choices, not official prerequisites or equivalences.
Projects and assessment
Official assessment: not displayed. The SynapseS 2026–2027 sheet of APM_51438_EP gives the grade format — numeric /20, with a US letter grade — but its assessment section for the LLGA track is empty: no exam, project or resit rule is shown (sources). Everything below is therefore a proposal sized for a 12 h refresher: solo subjects of 12–15 h, group subjects of 20–25 h per member, a two-hour written exam and a rubric.
The projects exercise two master objectives: O1 (ML and DL foundations: likelihood, estimation, uncertainty) and O7 (hands-on practice: an honest evaluation protocol). The graph-versus-text study adds O5 (Graph × LLM), and the prompt A/B test adds O3 (large language models). Both group subjects apply the capstone evaluation kit that the end-of-year projects reuse.
Solo projects
- [Solo · ≈ 12 h] Coverage under dependence: when iid standard errors lie. How far below 95% do the usual intervals for a mean fall when observations are heavy-tailed or share a source, and which resampling scheme repairs them?
- Implement: a simulator of the coverage of the z, t, percentile-bootstrap and cluster-bootstrap intervals, for iid Gaussian, Student t_3 and clustered data (clusters of size m, intra-cluster correlation \rho from 0 to 0.6), then for node features on a stochastic block model.
- Prove: from the variance formula with covariances (chapter 4), the design effect 1+(m-1)\rho and the coverage 2\Phi\big(1.96/\sqrt{1+(m-1)\rho}\big)-1 that it predicts for the iid interval.
- Data: synthetic, with
networkx.stochastic_block_modelfor the graph case. Link: the leakage-free splits of Graph ML Example 8.1. - Deliverables: code, 4-page report with coverage-versus-\rho curves, 10-minute talk. Chapters: ch. 4, 6; exercises 6 and 8.
- Success criterion: with 2,000 replications, the measured iid coverage matches the prediction within 3 points (about 69% for m=10, \rho=0.3), and the cluster bootstrap reaches at least 92% from 30 clusters on, while its under-coverage with 10 clusters is shown.
- [Solo · ≈ 12 h] From likelihood to loss: count and click models from scratch. Do hand-written maximum-likelihood fits give the same coefficients, standard errors and losses as library code, and when do Fisher, bootstrap and delta-method intervals disagree?
- Implement: logistic and Poisson regression by Newton’s method in NumPy; standard errors from the observed Fisher information; bootstrap intervals; a delta-method interval for an odds ratio or a rate ratio e^{\beta_j}.
- Prove: the fitted objectives are the binary cross-entropy and the Poisson negative log-likelihood (theorem 9.4), and with an intercept the Poisson score equation makes predicted and observed totals equal.
- Data: simulated well-specified data first; then the breast-cancer data bundled with scikit-learn (569 tumours) and the French motor-insurance claim counts
freMTPL2freq(OpenML id 41214), with exposure as sample weight — equivalent to a log-exposure offset — and one reference level dropped per categorical feature. - Trap: the 30 breast-cancer features separate the two classes linearly, so the unpenalized logistic MLE does not exist. Show that the Newton coefficients grow without bound, then fit the 10 standardized “mean” features, where the MLE exists.
- Deliverables: code, 4-page report, 10-minute talk. Chapters: ch. 4 (delta method, bootstrap), 5, 9.
- Success criterion: coefficients agree with scikit-learn (
LogisticRegression(penalty=None)andPoissonRegressor(alpha=0), both withsolver="newton-cholesky"and a tighttol) to 10^{-6}; Fisher and bootstrap standard errors agree within 10% on the simulated data, and the report measures and explains the gap on claim counts (overdispersion).
- [Solo · ≈ 15 h] Paper study: which imputation to predict with missing values? Does a better imputation give a better predictor, and does keeping the missingness mask matter? A paper study of Le Morvan, Josse, Scornet and Varoquaux (NeurIPS 2021), with Le Morvan and Varoquaux (2024) for the “diminishing returns” claim — papers 3 and 4 of section 10.4.
- Implement: mean imputation with and without mask indicators and iterative (MICE-style) imputation with scikit-learn’s
IterativeImputer, each followed by a linear model and by gradient boosting, against the native missing-value support ofHistGradientBoostingRegressor; MCAR, MAR and self-masked MNAR masks at 30%. - Data: Gaussian synthetic data as in example 10.2, then California housing (
sklearn.datasets.fetch_california_housing) with the same masks. - Deliverables: code, 4–6 page report, 10-minute talk. Chapters: ch. 10, 6, and the evaluation kit.
- Success criterion: every imputer is fitted inside the training folds; held-out R^2 differences come with intervals over 5 seeds × 5 folds; the report states whether the 2024 claim holds on these data.
- Implement: mean imputation with and without mask indicators and iterative (MICE-style) imputation with scikit-learn’s
Group projects
- [Group of 3 · ≈ 25 h each] Does the graph really help? A rigorous text-only versus graph-assisted evaluation. On multi-hop questions, does a knowledge-graph view in the prompt of a small LLM raise accuracy on new sources, beyond an equally long graph with shuffled edges? It scales up the transfer check and seeds the evaluation of the Graph × LLM capstones.
- Data: the 2WikiMultiHopQA dev set (Ho, Duong Nguyen, Sugawara and Aizawa, COLING 2020), 600–1,000 questions clustered by their first gold Wikipedia article. The graph view is extracted from the context paragraphs, never from the gold evidence triples, which serve only for error analysis.
- Implement: three prompts for one open model (for example Qwen2.5-1.5B-Instruct on a free GPU tier): text only; text plus a 2-hop triple graph; text plus the same graph with degree-preserving shuffled edges.
- Statistics: paired per-question differences, cluster bootstrap by article (the kit’s code), McNemar’s test, Holm or Benjamini–Hochberg across variants, and a one-page analysis plan written before the test questions are scored.
- Split of work: A builds the retrieval and graph pipeline; B runs the models with fixed seeds and logs per-question outputs; C owns the analysis plan, the bootstrap and the shuffled control.
- Deliverables: repository, analysis plan, 6-page report, 15-minute talk. Chapters: ch. 4, 6, 9 and the exit checkpoint. Links: Graph ML ch. 10 (GraphRAG), Large Language Models ch. 7.
- Success criterion: the gain, or its absence, is reported with a 95% cluster interval, next to the shuffled control and after correction across variants — exactly as the plan said.
- [Group of 2 · ≈ 20 h each] Bayesian versus frequentist prompt A/B testing, and the winner’s curse. Among eight prompts for a labelled task, which is best, how many labelled queries does each design spend to find it, and how optimistic is the winning score?
- Data: SST-2 sentiment (Socher et al., 2013; GLUE validation split, 872 sentences) or BoolQ (Clark et al., 2019; 3,270 dev questions), with one small open instruct model and fixed decoding.
- Implement: (a) a fixed-horizon design — every prompt on the same items, paired comparisons with the baseline prompt, Bonferroni and Benjamini–Hochberg; (b) Beta–Bernoulli Thompson sampling over prompts (chapter 8), stopped when the posterior probability of the leader exceeds 0.95 or a fixed query budget is spent, since near-equal prompts may never reach 0.95.
- Winner’s curse: measure the optimism of the selected prompt — validation accuracy minus accuracy on a held-out set touched once — and compare it with a simulation of eight equally good prompts (example 3.6).
- Split of work: A builds the evaluation harness and design (a); B builds design (b) and the simulation. Link: Large Language Models ch. 9 (benchmarks and contamination).
- Deliverables: code, 4–6 page report, 15-minute joint talk. Chapters: ch. 3, 6, 8.
- Success criterion: both designs report their decision and their query count; the measured optimism comes with an interval and is compared with the simulated null.
Written exam (proposal)
Two hours, one handwritten A4 sheet allowed, a non-programmable calculator; four independent questions. Use z_{0.975}=1.96.
Question (5 points). A colleague writes: “the 95% confidence interval for the accuracy gain is [0.004,0.076], so the gain lies in it with probability 0.95; and p=0.03 means a 3% chance that the gain is zero.” Correct both statements, then describe a setting in which the first reading becomes legitimate.
Expected: coverage is a property of the procedure over repeated samples (definition 6.1); the realized interval contains the fixed gain or not. A p-value is a tail probability computed under H_0; turning it into a probability of H_0 needs a prior, as in the medical test of example 1.8. With a prior, a 95% credible interval satisfies the first reading (definition 8.5, example 8.6).
Question (6 points). Two models answer the same 400 independent questions. Model A is right on 300 and model B on 316; A alone is right on 20 questions and B alone on 36. (a) Give the accuracy gain and a 95% interval from the paired differences. (b) Test equal accuracy with McNemar’s statistic, in its normal approximation. (c) What changes if the 400 questions come from 20 documents of 20 questions?
Expected: (a) the gain is 16/400=0.04; the differences are +1 (36 times), -1 (20 times) or 0, with variance 0.14-0.04^2=0.1384, so \mathrm{SE}=\sqrt{0.1384/400}\approx0.0186, \qquad 0.04\pm1.96\times0.0186=[0.004,\,0.076].
- Under H_0, B’s wins among the 56 discordant pairs follow \mathcal{B}(56,1/2), so z=(36-20)/\sqrt{56}\approx2.14 and p\approx0.03 (exact binomial: 0.044): reject at 5%. (c) The questions are no longer independent: average the differences per document and build the interval from the 20 document means (a t_{19} interval or a cluster bootstrap). With positively correlated questions within a document it is wider, and the conclusion may change.
Question (5 points). (a) Prove that if a probability vector \pi is in detailed balance with a transition matrix P, then \pi^\top P=\pi^\top. (b) For the two-state matrix below, with 0<a,b<1, find \pi and prove that \mu_t(1)-\pi_1=(1-a-b)^t\,(\mu_0(1)-\pi_1). P=\begin{pmatrix}1-a&a\\b&1-b\end{pmatrix}
Expected: (a) sum \pi_iP_{ij}=\pi_jP_{ji} over i and use that row j sums to 1 (proposition 2.18). (b) Detailed balance a\pi_1=b\pi_2 gives \pi=\big(b/(a+b),\,a/(a+b)\big). One step gives \mu_{t+1}(1)=(1-a)\mu_t(1)+b\,(1-\mu_t(1))=b+(1-a-b)\,\mu_t(1); subtract the same identity for the fixed point \pi_1 and iterate. Since |1-a-b|<1, the law converges from any start.
Question (4 points). Let U_1,\dots,U_K be iid uniform on [0,1]. Prove that \mathbb{E}[\max_kU_k]=K/(K+1). Explain why reporting the best of K validation scores overstates performance, and give the protocol that fixes it.
Expected: \mathbb{P}(\max_kU_k\leq t)=t^K (proposition 3.5), so the density is Kt^{K-1} and \mathbb{E}[\max_kU_k]=\int_0^1Kt^K\,dt=\frac{K}{K+1}. When variants are equally good, the selected score is the maximum of noisy estimates and is biased upward — 0.9 for K=9 (example 3.6). Select on validation (or nested cross-validation), then evaluate the selected model once on an untouched test set, and count the K comparisons.
Total: 5 + 6 + 5 + 4 = 20 points.
Grading rubric (proposal)
| Criterion | Weight | What earns the marks |
|---|---|---|
| Question and protocol fixed in advance | 20 % | The claim, the deployment unit, the split, the baseline and the metric are written down before the results; deviations are reported |
| Correctness of derivations and code | 25 % | Derivations are complete; the code is checked on a case with a known answer (a closed form, a simulation, a library fit) |
| Uncertainty and honest comparison | 25 % | Intervals at the right unit, paired comparisons, several seeds, multiple-testing control, and controls such as the shuffled graph |
| Report and talk | 20 % | Clear figures, assumptions stated next to each conclusion, negative results reported, time limit respected |
| Reproducibility and teamwork | 10 % | One command reruns the results from a fixed seed; data provenance is given; for groups, a visible split of the work |
References
Reading recommendations, not a prescribed catalog bibliography. Choose a reference for a specific gap rather than treating the list as additional compulsory reading.
- L. Wasserman, All of Statistics: A Concise Course in Statistical Inference, Springer, 2004 — a compact reference across probability, inference and statistical learning.
- G. Casella, R. Berger, Statistical Inference, 2nd ed., Duxbury, 2001 — deeper derivations and conditions for estimation and testing.
- J. Rice, Mathematical Statistics and Data Analysis, 3rd ed., Duxbury, 2007 — a data-oriented complement to the worked examples.
- C. Robert, The Bayesian Choice, Springer, 2007 — optional depth on Bayesian decision theory and inference.
- A. Gelman, J. Carlin, H. Stern, D. Dunson, A. Vehtari, D. Rubin, Bayesian Data Analysis, 3rd ed., CRC Press, 2013 — modeling and posterior analysis beyond conjugate examples.
- R. Little, D. Rubin, Statistical Analysis with Missing Data, 3rd ed., Wiley, 2019 — missingness mechanisms, likelihood methods and multiple imputation.
- Selected papers for chapter 10:
- Linear predictor on linearly-generated data with missing values: non consistency and solutions, AISTATS 2020.
- NeuMiss networks: differentiable programming for supervised learning with missing values, NeurIPS 2020.
- What’s a good imputation to predict with missing values?, NeurIPS 2021.
- Imputation for prediction: beware of diminishing returns, 2024.
- Public research publication list — further bibliography, not authorship or endorsement of these independent notes.