ML Foundations Lecture 14 of 14
Part V — Probability and Statistics · Lecture 14

Bayes, Distributions, and Maximum Likelihood

The last lecture of Phase A, and the one that ties it together. Maximum likelihood is a single principle from which squared error, cross-entropy, ridge and LASSO all fall out — and Bayes' theorem is the reason a 99%-accurate test can be wrong most of the time.

By the end you can

  • Derive Bayes' theorem and use it to resolve the base-rate fallacy quantitatively
  • Write down a likelihood, take its log, and maximise it
  • Derive the MLE for Bernoulli, Gaussian, linear regression and logistic regression
  • Show that MAP estimation with a Gaussian prior is ridge regression
  • Explain what an estimator's bias is, and why the MLE variance is biased

Assumed

  • Lecture 13: random variables, expectation, variance
  • Lecture 2: logarithms and the argmax theorem
  • Lectures 7, 10, 12: optimisation, least squares, gradients

1Conditional probability

Definition — conditional probability

For events \(A,B\) with \(P(B)>0\),

\[ P(A\mid B) = \frac{P(A\cap B)}{P(B)}. \]

Read: having learned that \(B\) happened, restrict attention to \(B\) and renormalise. The denominator is what makes the conditional probabilities of a partition sum to 1 again.

Independence is the statement that conditioning changes nothing: \(P(A\mid B)=P(A)\), equivalently \(P(A\cap B)=P(A)P(B)\).

Bayes' theorem in three lines0 / 4
\[P(A\mid B)\,P(B) = P(A\cap B) = P(B\mid A)\,P(A)\]
Apply the definition twice. Rearranging the definition gives \(P(A\cap B)=P(A\mid B)P(B)\), and by symmetry of intersection it also equals \(P(B\mid A)P(A)\). Two expressions for the same quantity.
\[\boxed{\;P(A\mid B) = \frac{P(B\mid A)\,P(A)}{P(B)}\;}\]
Divide by \(P(B)\). That is the whole proof. Bayes' theorem is a two-line rearrangement of the definition — its difficulty is entirely in its interpretation, never in its algebra.
\[P(B) = P(B\mid A)P(A) + P(B\mid A^c)P(A^c)\]
Law of total probability, for the denominator. Since \(A\) and \(A^c\) partition the sample space, \(B\) splits into the part inside \(A\) and the part outside, and the two pieces are disjoint so their probabilities add (axiom 3). In general, sum over any partition.
\[\underbrace{P(A\mid B)}_{\text{posterior}} = \frac{\overbrace{P(B\mid A)}^{\text{likelihood}}\ \overbrace{P(A)}^{\text{prior}}}{\underbrace{P(B)}_{\text{evidence}}}\]
The vocabulary. Prior: what you believed about \(A\) before. Likelihood: how well \(A\) explains the observation \(B\). Posterior: your updated belief. Evidence: a normalising constant that makes the posterior sum to 1. Almost every Bayesian computation in machine learning is a fight with that denominator.
The base-rate fallacy: a 99%-accurate test for a rare diseaseInteractive
has the diseasedoes nottests positive
-3.00
0.990
0.9900
Each square is one person in a population of 10 000. Pink squares have the disease; ringed squares tested positive. Count them: with 0.1% prevalence and a 99% test, about 10 sick people test positive and about 100 healthy people ALSO test positive — so a positive result means roughly a 9% chance of being ill, not 99%. The false positives outnumber the true ones because healthy people are so much more numerous. Raise the prevalence slider and watch the posterior climb.
Common trap

The lesson generalises well beyond medicine, and it is the single most useful piece of probability for an ML practitioner to hold on to. A classifier's accuracy on the positive class tells you almost nothing about the reliability of a positive prediction, when the positive class is rare.

Fraud detection, rare-disease screening, anomaly detection, safety filters — all live in this regime. Precision \(P(\text{actually positive}\mid\text{predicted positive})\) depends on the base rate; recall \(P(\text{predicted positive}\mid\text{actually positive})\) does not. That asymmetry is why you should report both, why the precision-recall curve is preferred to the ROC curve for imbalanced problems, and why a model with 99.9% accuracy on a 0.1%-prevalence problem may be worthless — predicting "negative" always would score 99.9%.

2Distributions you will meet constantly

Four, with their means, variances, and what they model.

\[\begin{array}{llll} \textbf{Bernoulli}(p) & P(X{=}1)=p & \E=p & \Var=p(1-p) \\[3pt] \textbf{Categorical}(\boldsymbol\pi) & P(X{=}k)=\pi_k & - & - \\[3pt] \textbf{Gaussian}(\mu,\sigma^2) & f(x)=\frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{(x-\mu)^2}{2\sigma^2}} & \E=\mu & \Var=\sigma^2\\[3pt] \textbf{Multivariate Gaussian} & f(\vx)=\frac{1}{\sqrt{(2\pi)^d|\mS|}}e^{-\frac12(\vx-\vm)^\top\mS^{-1}(\vx-\vm)} & \E=\vm & \Cov=\mS \end{array}\]

Look at the exponent of the multivariate Gaussian: \((\vx-\vm)^\top\mS^{-1}(\vx-\vm)\) is a quadratic form — exactly Lecture 11's object. Its level sets are the ellipsoids we drew there, with axes along the eigenvectors of \(\mS\) and half-lengths proportional to \(\sqrt{\lambda_i}\). The density is constant on those ellipsoids. Everything you learned about quadratic forms is a fact about Gaussians.

3Maximum likelihood

Definition — likelihood and MLE

Given data \(\mathcal{D}=\{x_1,\dots,x_n\}\) modelled as independent draws from \(p(x\mid\vt)\), the likelihood is

\[ L(\vt) = p(\mathcal{D}\mid\vt) = \prod_{i=1}^{n} p(x_i\mid\vt), \]

and the maximum likelihood estimate is \(\hat{\vt}_{\text{MLE}}=\argmax_{\vt}L(\vt)\).

Crucially, \(L\) is a function of \(\vt\), not of the data. The data are fixed and observed; we are asking which parameter setting makes what we saw most probable. This is the single most common conceptual slip with likelihoods, and \(L(\vt)\) is not a probability distribution over \(\vt\) — it does not integrate to 1.

By Lecture 2's argmax theorem we may take logs, converting the product into a sum. The recipe is always the same four steps:

  1. Write the likelihood as a product over the data.
  2. Take the log, turning it into a sum.
  3. Differentiate with respect to the parameters and set to zero (Lecture 7 / Lecture 12).
  4. Check it is a maximum, via the second derivative or convexity.
The likelihood as a function of the parameterInteractive
likelihood L(θ)log-likelihoodyour θthe MLE
0
10
0.300
Blue is the likelihood, purple the log-likelihood (rescaled to fit). Two things to watch. First: they peak at exactly the same θ — that is Lecture 2's argmax theorem, and it is why we may take logs freely. Second: raise n and the peak becomes dramatically sharper. More data means less uncertainty about the parameter, and the curvature at the peak is precisely the Fisher information.
MLE for the Bernoulli: the sample proportion0 / 5
\[L(p) = \prod_{i=1}^{n} p^{x_i}(1-p)^{1-x_i}, \qquad x_i\in\{0,1\}\]
The likelihood. The clever compact form: when \(x_i=1\) the term is \(p\), when \(x_i=0\) it is \(1-p\). One expression covering both cases, which makes the algebra uniform.
\[\ell(p) = \log L = \sum_i \Big[x_i\log p + (1-x_i)\log(1-p)\Big] = k\log p + (n-k)\log(1-p)\]
Take logs, where \(k=\sum_i x_i\) is the number of successes. Note that \(k\) is all the data we need — it is a sufficient statistic. Note also that \(-\ell\) is exactly the binary cross-entropy loss.
\[\ell'(p) = \frac{k}{p} - \frac{n-k}{1-p} \;\stackrel{!}{=}\; 0\]
Differentiate. Using \(\frac{d}{dp}\log(1-p) = -\frac{1}{1-p}\) by the chain rule.
\[k(1-p) = (n-k)p \;\Longrightarrow\; k - kp = np - kp \;\Longrightarrow\; \boxed{\hat p = \frac{k}{n}}\]
Solve. Multiply through by \(p(1-p)>0\) and the \(kp\) terms cancel. The MLE is the sample proportion — reassuringly, exactly what you would have guessed. Getting the obvious answer from the machinery is how you gain confidence in the machinery.
\[\ell''(p) = -\frac{k}{p^2}-\frac{n-k}{(1-p)^2} < 0\]
Confirm it is a maximum. Strictly negative throughout \((0,1)\), so \(\ell\) is strictly concave and this critical point is the unique global maximum (Lecture 7). ∎ Edge case: if \(k=0\) or \(k=n\) the maximum sits at the boundary, giving \(\hat p=0\) or \(1\) — an overconfident estimate from limited data, and exactly what a Bayesian prior fixes.
Derive the Gaussian MLE yourself

Data \(x_1,\dots,x_n\) drawn independently from \(\mathcal{N}(\mu,\sigma^2)\), with both parameters unknown. Find \(\hat\mu\) and \(\hat\sigma^2\).

Hint: write the log-likelihood, then differentiate with respect to each parameter in turn.

Log-likelihood.

\[ \ell(\mu,\sigma^2) = \sum_{i=1}^n \log\!\left[\frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x_i-\mu)^2}{2\sigma^2}}\right] = -\frac{n}{2}\log(2\pi) - \frac{n}{2}\log\sigma^2 - \frac{1}{2\sigma^2}\sum_i (x_i-\mu)^2. \]

For \(\mu\): only the last term involves it.

\[\frac{\partial\ell}{\partial\mu} = \frac{1}{\sigma^2}\sum_i (x_i-\mu) = 0 \;\Longrightarrow\; \sum_i x_i = n\mu \;\Longrightarrow\; \boxed{\hat\mu = \bar x}.\]

The sample mean. Note this is independent of \(\sigma^2\), which is why we can solve for it first. It is also Lecture 13's result that the mean minimises squared deviation — the same computation.

For \(\sigma^2\): treat \(v=\sigma^2\) as the variable (cleaner than \(\sigma\)).

\[\frac{\partial\ell}{\partial v} = -\frac{n}{2v} + \frac{1}{2v^2}\sum_i (x_i-\mu)^2 = 0.\]

Multiply by \(2v^2>0\): \(\;-nv + \sum_i(x_i-\mu)^2 = 0\), so

\[\boxed{\hat\sigma^2 = \frac{1}{n}\sum_{i=1}^n (x_i-\hat\mu)^2}.\]

The catch. Note the \(n\), not \(n-1\). By Lecture 13's exercise, \(\E[\hat\sigma^2_{\text{MLE}}]=\frac{n-1}{n}\sigma^2\) — the maximum likelihood estimate of the variance is biased low, systematically underestimating the spread. It is consistent (the bias vanishes as \(n\to\infty\)) but not unbiased.

This is worth sitting with: maximum likelihood is a principle, not a guarantee. It is asymptotically efficient under regularity conditions, but at finite \(n\) it can be biased, and here it is biased in the dangerous direction — towards overconfidence. The same phenomenon is why a model's training loss underestimates its test loss.

4Every loss function you know, derived

Now the payoff. Two standard losses, both obtained by writing down a noise model and taking the negative log-likelihood.

Linear regression → squared error; logistic regression → cross-entropy0 / 6
\[y_i \mid \vx_i \;\sim\; \mathcal{N}\big(\vw^\top\vx_i,\ \sigma^2\big)\]
Model 1: Gaussian noise around a linear mean. The modelling assumption is entirely contained in this line. Everything below is mechanical.
\[\ell(\vw) = -\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^n\big(y_i-\vw^\top\vx_i\big)^2\]
Log-likelihood. Product of Gaussian densities, logged. The first term does not involve \(\vw\).
\[\argmax_{\vw}\ \ell(\vw) = \argmin_{\vw}\ \sum_i\big(y_i-\vw^\top\vx_i\big)^2 = \argmin_{\vw}\|\vy-\mX\vw\|^2\]
Least squares, recovered. Dropping the constant and the positive factor \(\frac{1}{2\sigma^2}\) leaves exactly Lecture 10's objective. Squared error is not a neutral default — it is a Gaussian noise assumption.
\[y_i \mid \vx_i \;\sim\; \text{Bernoulli}\big(\sigma(\vw^\top\vx_i)\big)\]
Model 2: Bernoulli, with the sigmoid as the link. Recall from Lecture 2 that \(\sigma\) is the inverse of the logit, so this says the log-odds are linear in \(\vx\) — the natural way to make a linear model output a probability.
\[\ell(\vw) = \sum_{i=1}^{n}\Big[y_i\log \hat p_i + (1-y_i)\log(1-\hat p_i)\Big], \qquad \hat p_i = \sigma(\vw^\top\vx_i)\]
Same Bernoulli log-likelihood as before, now with \(p\) depending on \(\vx_i\) through the model rather than being a single number.
\[-\ell(\vw) = -\sum_i\big[y_i\log\hat p_i + (1-y_i)\log(1-\hat p_i)\big] \;=\; \textbf{cross-entropy loss}\]
Cross-entropy, recovered. And Lecture 12's exercise showed its gradient is \(\mX^\top(\hat{\vp}-\vy)\) — the same shape as least squares. Both of the losses you will use most are negative log-likelihoods; the only difference is the assumed noise distribution. ∎

5MAP estimation: where regularisation comes from

MLE treats \(\vt\) as a fixed unknown. The Bayesian alternative treats it as random, with a prior, and maximises the posterior. Bayes' theorem gives

\[p(\vt\mid\mathcal{D}) = \frac{p(\mathcal{D}\mid\vt)\,p(\vt)}{p(\mathcal{D})} \;\propto\; \underbrace{p(\mathcal{D}\mid\vt)}_{\text{likelihood}}\ \underbrace{p(\vt)}_{\text{prior}},\]

where the evidence \(p(\mathcal{D})\) is dropped because it does not depend on \(\vt\) and so cannot move the argmax.

Gaussian prior ⟹ ridge; Laplace prior ⟹ LASSO0 / 5
\[\hat{\vw}_{\text{MAP}} = \argmax_{\vw}\Big[\log p(\mathcal{D}\mid\vw) + \log p(\vw)\Big]\]
Take logs of the posterior. The product becomes a sum: log-likelihood plus log-prior. The whole of regularisation lives in that second term.
\[p(\vw) = \prod_{j=1}^d \frac{1}{\sqrt{2\pi\tau^2}}\exp\!\left(-\frac{w_j^2}{2\tau^2}\right) \;\Longrightarrow\; \log p(\vw) = -\frac{1}{2\tau^2}\|\vw\|_2^2 + \text{const}\]
Choose an isotropic Gaussian prior centred at zero — the formal statement of the belief 'weights are probably small'. Its log is a negative multiple of the squared L2 norm.
\[\hat{\vw}_{\text{MAP}} = \argmin_{\vw}\left[\frac{1}{2\sigma^2}\|\vy-\mX\vw\|^2 + \frac{1}{2\tau^2}\|\vw\|_2^2\right] = \argmin_{\vw}\Big[\|\vy-\mX\vw\|^2 + \lambda\|\vw\|_2^2\Big]\]
Ridge regression, with \(\lambda = \sigma^2/\tau^2\). Multiplying through by \(2\sigma^2\) — a positive constant, so the argmin is unchanged. The regularisation strength has an interpretation: it is the ratio of noise variance to prior variance. A confident prior (small \(\tau\)) means strong regularisation; a lot of noise (large \(\sigma\)) also means strong regularisation, because the data is less trustworthy.
\[p(\vw) \propto \prod_j \exp\!\left(-\frac{|w_j|}{b}\right) \;\Longrightarrow\; \log p(\vw) = -\frac{1}{b}\|\vw\|_1 + \text{const}\]
Now a Laplace prior. Same shape of argument, but the exponent has \(|w_j|\) instead of \(w_j^2\) — the Laplace density is peaked and sharp at zero rather than smooth.
\[\hat{\vw}_{\text{MAP}} = \argmin_{\vw}\Big[\|\vy-\mX\vw\|^2 + \lambda\|\vw\|_1\Big] \qquad\textbf{(LASSO)}\]
L1 regularisation. And now Lecture 8's unit-ball figure explains its behaviour: the L1 ball has corners on the axes, so the constrained optimum tends to land at a corner, where some coordinates are exactly zero. The sharp peak of the Laplace prior and the corners of the L1 ball are the same fact seen from two directions — one probabilistic, one geometric. ∎
Where this shows up in ML

Three consequences worth carrying into Phase B.

Check yourself
A model is trained with mean squared error. What noise model does that implicitly assume, and when would it be a poor choice?
Correct. Correct, and each failure mode maps to a different fix.

Heavy tails: the Gaussian assigns very little probability to large deviations, so a single outlier at distance 10 contributes as much as a hundred at distance 1 and dominates the fit. A Laplace noise model gives \(\sum|r_i|\) — least absolute deviations — and the Huber loss interpolates between the two.

Heteroscedasticity: if \(\sigma_i\) varies by observation, the \(\frac{1}{2\sigma_i^2}\) factors no longer come out of the sum and you get weighted least squares. Ignoring this over-weights the noisiest observations.

Wrong support: a Gaussian puts probability on all of \(\RR\). For counts you want Poisson; for a probability, Beta; for a category, Categorical. Using MSE on a count model will happily predict \(-3.2\) customers.
Not quite. The derivation above shows otherwise, in three lines: assume Gaussian noise, take the negative log-likelihood, and squared error falls out. Every loss encodes assumptions. The dangerous ones are the assumptions you did not know you were making, and "MSE is neutral" is the most common of them.
Not quite. Errors are emphatically not weighted equally under MSE — squaring means an error of 10 is penalised a hundred times as much as an error of 1, not ten times. And a uniform noise model would give a quite different (and strange) likelihood, since a uniform density is constant on its support and zero outside: the MLE would be any parameter making every residual fall inside the support.
Bayes, MLE, and MAP, all verified numericallyPython · NumPy

6What you have built

That is Phase A. It is worth pausing to see the shape of it, because the pieces connect more tightly than they appeared to at the time.

Phase B builds classical machine learning on this. You will find that most of it is already half-derived: linear regression is Lecture 10, logistic regression is Lectures 2, 5 and 14, PCA is Lecture 11, gradient descent is Lectures 4, 6 and 12, and the bias-variance decomposition is Lecture 13. That is the intended effect. Foundations built properly make the material above them feel inevitable rather than arbitrary.

7Exercises

★

A factory has three machines producing 50%, 30% and 20% of output, with defect rates 1%, 2% and 3% respectively.

  1. What fraction of output is defective?
  2. Given a defective item, what is the probability it came from machine 3?
  3. Which machine is the most likely source of a defective item, and is that the same as the machine with the highest defect rate?

1. Law of total probability.

\[P(D) = 0.5(0.01)+0.3(0.02)+0.2(0.03) = 0.005+0.006+0.006 = 0.017 = 1.7\%.\]

2. Bayes.

\[P(M_3\mid D) = \frac{P(D\mid M_3)P(M_3)}{P(D)} = \frac{0.03\times0.20}{0.017} = \frac{0.006}{0.017} \approx 0.3529.\]

About 35.3%.

3. The three posteriors are \(\frac{0.005}{0.017}=29.4\%\), \(\frac{0.006}{0.017}=35.3\%\), \(\frac{0.006}{0.017}=35.3\%\). Machines 2 and 3 are tied as the most likely source, at 35.3% each.

And no, this is not the same as the highest defect rate: machine 3 is three times as defect-prone as machine 1, yet contributes only slightly more defects, because machine 1 produces two and a half times as much. Posterior = likelihood × prior, and the prior here is production volume. This is the base-rate lesson again, in an industrial setting: to reduce total defects you should weigh volume alongside rate.

★★

Derive the MLE for the rate \(\lambda\) of a Poisson distribution, \(P(X=k)=\frac{\lambda^k e^{-\lambda}}{k!}\), from data \(k_1,\dots,k_n\).

Then state the corresponding loss function for a regression model that predicts counts, and say when you would use it in preference to squared error.

Log-likelihood.

\[\ell(\lambda) = \sum_{i=1}^n\Big[k_i\log\lambda - \lambda - \log(k_i!)\Big] = \left(\sum_i k_i\right)\log\lambda - n\lambda - \sum_i\log(k_i!).\]

The last term does not involve \(\lambda\) and can be ignored for optimisation.

\[\ell'(\lambda) = \frac{\sum_i k_i}{\lambda} - n = 0 \;\Longrightarrow\; \boxed{\hat\lambda = \frac1n\sum_i k_i = \bar k}.\]

The sample mean, again. And \(\ell''(\lambda) = -\frac{\sum k_i}{\lambda^2}<0\), so it is the unique maximum. ∎

Poisson regression. Model \(y_i\sim\text{Poisson}(\lambda_i)\) with \(\lambda_i=\exp(\vw^\top\vx_i)\) — the exponential link, which guarantees \(\lambda_i>0\) as a rate must be (a domain constraint, Lecture 1). The negative log-likelihood is

\[ L(\vw) = \sum_i\Big[\exp(\vw^\top\vx_i) - y_i\,\vw^\top\vx_i\Big], \]

dropping the \(\log(y_i!)\) constant. Its gradient is \(\sum_i(\hat\lambda_i - y_i)\vx_i = \mX^\top(\hat{\boldsymbol\lambda}-\vy)\) — the same design-transposed-times-error shape as least squares and logistic regression, for the same exponential-family reason.

When to prefer it. Whenever the target is a non-negative integer count: website visits, defect counts, photon arrivals, word frequencies. Two concrete advantages over squared error:

  • Correct support. The exponential link cannot predict a negative count; a linear-Gaussian model routinely will.
  • Correct variance structure. A Poisson has \(\Var = \E\), so large counts are naturally noisier. Squared error assumes constant variance and therefore over-weights the large counts, distorting the fit. (If the data are over-dispersed — variance well above the mean, which is common — negative binomial is the next step up.)
★★

Show that for the multivariate Gaussian \(\mathcal{N}(\vm,\mS)\), maximising the log-likelihood over \(\vm\) with \(\mS\) known gives \(\hat{\vm}=\bar{\vx}\), the sample mean vector.

Then explain what the level sets of the density look like in terms of the eigenvalues of \(\mS\), and what the quantity \((\vx-\vm)^\top\mS^{-1}(\vx-\vm)\) is called and used for.

Log-likelihood. Dropping terms without \(\vm\):

\[\ell(\vm) = -\frac12\sum_{i=1}^n (\vx_i-\vm)^\top\mS^{-1}(\vx_i-\vm) + \text{const}.\]

Differentiate using Lecture 12's rule \(\grad_{\vz}(\vz^\top\mA\vz)=2\mA\vz\) for symmetric \(\mA\) (and \(\mS^{-1}\) is symmetric because \(\mS\) is), together with the chain rule for the inner \(\vz=\vx_i-\vm\), whose Jacobian with respect to \(\vm\) is \(-\mI\):

\[\grad_{\vm}\ell = \sum_{i=1}^n \mS^{-1}(\vx_i-\vm) = \mS^{-1}\left(\sum_i\vx_i - n\vm\right) = \vzero.\]

Since \(\mS^{-1}\) is invertible we may multiply by \(\mS\): \(\sum_i\vx_i = n\vm\), so \(\hat{\vm}=\bar{\vx}\). ∎

The Hessian is \(-n\mS^{-1}\), which is negative definite because \(\mS\succ0\) implies \(\mS^{-1}\succ0\) (Lecture 11: inverting a positive definite matrix inverts its eigenvalues, keeping them positive). So it is the unique global maximum.

Level sets. The density depends on \(\vx\) only through the quadratic form, so level sets of the density are level sets of that form: ellipsoids centred at \(\vm\). By Lecture 11, if \(\mS=\mQ\Lambda\mQ^\top\) then \(\mS^{-1}=\mQ\Lambda^{-1}\mQ^\top\), so the form is \(\sum_i z_i^2/\lambda_i\) in the eigenbasis. The ellipsoid axes point along the eigenvectors \(\vq_i\), with half-lengths proportional to \(\sqrt{\lambda_i}\) — long in directions of high variance. An isotropic \(\mS=\sigma^2\mI\) gives spheres; strongly correlated variables give long thin cigars.

The quantity. \(d_M(\vx)^2 = (\vx-\vm)^\top\mS^{-1}(\vx-\vm)\) is the squared Mahalanobis distance. It is Euclidean distance measured in units of the local standard deviation, in every direction at once — equivalently, ordinary distance after whitening by \(\mS^{-1/2}\). Uses you will meet: multivariate outlier detection (under a Gaussian, \(d_M^2\sim\chi^2_d\), giving a principled threshold), the discriminant in Gaussian classifiers and LDA, and the natural-gradient and trust-region methods that measure parameter changes in the metric induced by the Fisher information rather than in raw Euclidean distance.

★★★

Coding + analysis, the Phase A capstone. Build a Bayesian linear regression by hand and compare it with MLE and MAP.

  1. Generate \(n=15\) noisy points from a degree-3 polynomial. Fit polynomial features up to degree 12.
  2. Fit by MLE (ordinary least squares). Plot the fit. What happens between the data points?
  3. Fit by MAP with a Gaussian prior at several \(\lambda\). Which \(\lambda\) looks best, and how would you choose it without looking?
  4. Compute the full Gaussian posterior \(p(\vw\mid\mathcal{D}) = \mathcal{N}(\vm_N,\mS_N)\) with \(\mS_N=(\sigma^{-2}\mX^\top\mX+\tau^{-2}\mI)^{-1}\) and \(\vm_N=\sigma^{-2}\mS_N\mX^\top\vy\). Draw 30 samples from it and plot them. What does the spread show that the point estimate does not?
import numpy as np
rng = np.random.default_rng(3)
n, deg, sigma, tau = 15, 12, 0.25, 1.0
xs = np.sort(rng.uniform(-1, 1, n))
f  = lambda x: 1.0 - 2.0*x + 0.5*x**2 + 3.0*x**3
y  = f(xs) + sigma*rng.normal(size=n)
P  = lambda x: np.vander(np.atleast_1d(x), deg+1, increasing=True)
X  = P(xs)

w_mle, *_ = np.linalg.lstsq(X, y, rcond=None)
grid = np.linspace(-1.15, 1.15, 400); G = P(grid)
print("||w_mle|| =", np.linalg.norm(w_mle).round(2))
print("max |fit| on the grid =", np.abs(G @ w_mle).max().round(2),
      " vs max |data| =", np.abs(y).max().round(2))

for lam in [1e-8, 1e-4, 1e-2, 1e0, 1e2]:
    w = np.linalg.solve(X.T@X + lam*np.eye(deg+1), X.T@y)
    train = np.mean((X@w - y)**2)
    true  = np.mean((G@w - f(grid))**2)          # error against the TRUE function
    print(f"lambda={lam:8.0e}  ||w||={np.linalg.norm(w):9.2f}"
          f"  train MSE={train:.5f}  error vs truth={true:.5f}")

S_N = np.linalg.inv(X.T@X/sigma**2 + np.eye(deg+1)/tau**2)
m_N = S_N @ X.T @ y / sigma**2
L = np.linalg.cholesky(S_N + 1e-12*np.eye(deg+1))
samples = m_N + (L @ rng.normal(size=(deg+1, 30))).T
band = samples @ G.T                              # 30 x len(grid)
print("\\nposterior sd of the prediction, inside vs outside the data:")
i0 = np.argmin(np.abs(grid))
print(f"  x= 0.00  sd={band[:, i0].std():.4f}")
print(f"  x= 1.15  sd={band[:, -1].std():.4f}   <- outside the data range")

2. With this seed \(\|\vw_{\text{MLE}}\|\approx 3.5\times10^4\), and the fitted curve reaches a magnitude of about \(9\times10^4\) on the plotting grid — against data whose largest value is \(1.89\). It passes essentially through every data point while oscillating violently between them and exploding outside the data range. Twelve degrees of freedom fitted to fifteen noisy points is near-interpolation: the model has fitted the noise. This is the textbook picture of overfitting, and also the ill-conditioning of Lecture 10 — the Vandermonde matrix here has \(\operatorname{cond}(\mX)\approx 2.8\times10^6\).

3. Error against the truth is U-shaped in \(\lambda\) and spans an enormous range: with this seed it runs \(3.9\times10^{4}\) at \(\lambda=10^{-8}\), down through \(129\) at \(10^{-4}\) and \(1.52\) at \(10^{-2}\), to a minimum of about \(0.87\) at \(\lambda=1\), then back up to \(1.71\) at \(\lambda=100\). Meanwhile training MSE rises monotonically the whole way, from \(0.011\) to \(1.18\) — training error alone would have told you to pick the worst model on the list. Too small and you overfit; too large and you underfit towards the zero function. Choosing it without peeking means cross-validation: hold out folds, fit on the rest, and pick the \(\lambda\) minimising held-out error. Never tune on the test set, and never tune against the true function — you do not have it. (The Bayesian alternative is to maximise the marginal likelihood, or "evidence", which integrates the parameters out rather than holding data out.)

4. The posterior samples agree tightly with each other where there is data and fan out dramatically outside the data range and in any gaps. Concretely: the predictive standard deviation is about \(0.09\) at \(x=0\), in the middle of the data, and about \(9.0\) at \(x=1.15\), just beyond it — a hundredfold increase over a short distance.

That is the thing a point estimate cannot tell you. \(\vw_{\text{MAP}}\) gives one curve with no indication of confidence; the posterior says here is what I know, and here is where I am guessing. This distinction matters enormously in any setting where acting on a confident-but-wrong prediction is costly — medicine, control, active learning, Bayesian optimisation — and it is why calibration and uncertainty quantification are active research areas rather than solved problems.

It is worth appreciating what made this tractable: the posterior is Gaussian in closed form only because a Gaussian prior is conjugate to a Gaussian likelihood. For a neural network no such closed form exists, and everything in approximate Bayesian deep learning — Laplace approximation, variational inference, deep ensembles, MC dropout — is an attempt to recover a usable version of the fan you just plotted.


Phase A complete. Take the index page's advice seriously before moving on: if there are exercises here you could not do, tell me which ones. That is more useful to me than a claim that everything made sense, and it decides whether Phase B starts next or whether we revisit something first.