AI from scratch · Probability 3 · Stage 2: how a network learns
From data to parameters: MLE and MAP
Training a model means picking its knobs from data. But why the mean squared error? Why cross-entropy? Why does adding \(\lambda \lVert w \rVert^2\) help? They aren't arbitrary choices: they all come out of one principle, pick the knobs that make the data you actually saw most likely, plus one honest addition, what you believed before seeing it. This lesson builds both from coin flips up, and on the way shows why averages work at all.
1. A sample is not the population
The thing you want to know about (every outage there will ever be, every email ever sent) is the population. What you have is a sample: some of it. Numbers computed from the sample, like its mean \(\bar x\), are estimates of the population's true values, like its mean \(\mu\), and they'd come out a bit different with a different sample.
One estimate has a famous twist. Measure spread around the sample's own mean, and you come up short, because the sample mean sits in the middle of these points, closer to them than the true mean usually is. Dividing by \(n - 1\) instead of \(n\) corrects for that exactly. Below, the computer draws 4000 samples of size \(n\) from a bell curve whose true variance is 1, and averages both versions:
\[ s^2 = \frac{1}{n - 1} \sum_{i=1}^{n} (x_i - \bar{x})^2 \]
Why exactly \(n - 1\)?
The deviations \(x_i - \bar x\) always add up to zero, so once you know \(n - 1\) of them, the last is forced: only \(n - 1\) of them are free (degrees of freedom). Worked out, the expected value of \(\sum (x_i - \bar x)^2\) is \((n - 1)\sigma^2\), not \(n\sigma^2\): you lose exactly one \(\sigma^2\), the variance of \(\bar x\) itself times \(n\). Dividing by \(n - 1\) gives back \(\sigma^2\) on average: an unbiased estimate.
Sample: 2, 4, 6. What's \(s^2\), dividing by \(n - 1\)?
np.var divides by \(n\) unless you pass ddof=1; pandas' .var() divides by \(n - 1\). Yes, really.2. Why averages work: the law of large numbers
Roll a die again and again and keep the running average. Early on it jumps around; with more rolls it settles on 3.5, the die's true mean. That's the law of large numbers: the sample mean of independent draws converges to the population mean. It's why a training set's average loss is a fair stand-in for the loss on the whole world, and why more data helps.
How fast? Calculus 4 showed it: the spread of an average of \(n\) draws is \(\sigma / \sqrt n\). Four times the data halves the error, which is why the last few points of accuracy are so expensive.
A die has standard deviation about 1.708. What's the standard deviation of the average of 100 rolls?
3. Why bell curves are everywhere: the central limit theorem
Add up several random numbers. Whatever shape each one has (flat like a die, lopsided like a train wait), the sum heads toward the same bell curve. That's the central limit theorem, and it's why measurement errors, heights and averages are so often normal: they're sums of many small independent effects. The bars are 5000 sums; the yellow curve is the bell with the same mean and spread.
Pick train waits with "how many" at 1, then raise it. What happens to the lopsided shape?
- It stays lopsided, since each wait is lopsided
- It gets more symmetric and bell-shaped as more waits are added
Add up many small independent effects and the total is close to a bell curve, whatever each effect looks like on its own.
Where it breaks: sums that never become bells
- Tails too heavy. The theorem needs each piece to have a finite variance. Some don't: for the Cauchy distribution (the ratio of two bell-curve numbers), the average of 1,000 samples is exactly as spread out as a single sample. Averaging doesn't help at all. Real data with a few gigantic values (outage hours, city sizes, file sizes) lives part of the way toward this.
- Pieces that move together. If the effects aren't independent (a storm delays every train at once, a crash moves every stock), their sum keeps big swings a bell curve would call impossible.
- One piece that dominates. A sum of one huge effect and many tiny ones keeps the huge one's shape.
- The tails last. The middle of the curve turns normal quickly; its far tails much more slowly. A bell curve fit to 30 train waits gets the typical day right and the one-in-a-thousand day wrong, which is the day risk estimates are about.
4. Maximum likelihood: which knob makes the data least surprising?
You flip a coin 10 times and get 7 heads. What's your best guess for its chance of heads, \(p\)? For any \(p\), the probability of exactly that sequence is \(p^7 (1 - p)^3\), called the likelihood of \(p\). It's a function of the knob, with the data held fixed. Drag \(p\) and find the top:
The maximum likelihood estimate (MLE) is the \(p\) at the top, and here it's exactly what common sense says: \(7/10\). In practice you maximize the log-likelihood instead (green): same top, but products become sums (the math warm-up), and its derivative is easy:
\[ \ell(p) = h \ln p + (n - h) \ln(1 - p), \qquad \ell'(p) = \frac{h}{p} - \frac{n - h}{1 - p} = 0 \;\Rightarrow\; p = \frac{h}{n} \]
Maximum likelihood picks the knob settings under which the data you actually saw would have been least surprising.
With 7 heads in 10 flips, where is the likelihood highest?
Set heads to 0 and flips to 3. The MLE says \(p = 0\): this coin can never land heads. What's wrong?
- Three flips is too little data to rule anything out, but MLE trusts the data completely
- The calculation has a bug
5. Where the loss functions come from
Now the payoff. Apply "maximize the log-likelihood" to the models on this path, and the standard losses fall out. Maximizing a log-likelihood is the same as minimizing the negative log-likelihood (NLL), so a loss is just an NLL in disguise.
The math, step by step
A bell curve. Data \(x_1 \dots x_n\) from a normal with mean \(\mu\) and spread \(\sigma\). Each point's density is \(\frac{1}{\sqrt{2\pi}\sigma} e^{-(x_i - \mu)^2 / 2\sigma^2}\), so
\[ -\ell(\mu, \sigma) = \sum_i \frac{(x_i - \mu)^2}{2\sigma^2} + n \ln \sigma + \text{const} \]
Setting the derivatives to zero gives \(\mu = \bar x\) and \(\sigma^2 = \frac1n \sum (x_i - \bar x)^2\): the sample mean, and the variance dividing by \(n\), the slightly-too-small one from section 1. MLE isn't always unbiased.
Linear regression. Suppose each target is the line plus bell-curve noise: \(y_i = w x_i + b + \epsilon_i\), \(\epsilon_i \sim \mathcal N(0, \sigma^2)\): each noise term drawn from a normal (\(\mathcal N\)) bell curve with mean 0 and variance \(\sigma^2\). Then \(-\ell = \frac{1}{2\sigma^2} \sum_i (y_i - w x_i - b)^2 + \text{const}\). With \(\sigma\) fixed, the only part that depends on the knobs is the sum of squared errors. Minimizing MSE is maximum likelihood under Gaussian noise.
Classification. If the model says "class \(k\) with probability \(\hat p_k\)" and the truth is class \(y\), the likelihood of that example is \(\hat p_y\), so \(-\ell = -\sum_i \ln \hat p_{y_i}\). That's cross-entropy, chapter 5's loss. For two classes with a sigmoid, it's the coin's log-likelihood above with \(p\) coming from the model.
Every standard loss is a negative log-likelihood: choosing a loss is choosing what you believe about the noise.
Your regression targets have rare, huge outliers (like Probability 2's outage hours). Squared error lets them dominate. In likelihood terms, why?
- Squared error has a bug with big numbers
- The model is too small
- MSE assumes bell-curve noise, where a 10σ error is essentially impossible, so the fit bends over backwards to avoid it
6. Bayesian updating: start with a belief, let data move it
Bayes' rule (Probability 1) works on knobs too. Put a prior on \(p\), a probability for every possible value, and multiply by the likelihood to get the posterior: what you believe after the data. For a coin, the natural prior is a Beta(\(a\), \(b\)) distribution, which acts like \(a - 1\) heads and \(b - 1\) tails you'd already seen. After \(h\) heads and \(t\) tails, the posterior is Beta(\(a + h\), \(b + t\)).
The blue curve is the prior, green the likelihood of the flips so far (scaled to fit), yellow the posterior. With few flips, the prior holds the posterior back from extreme answers; with many, the data takes over and the prior hardly matters. The mystery coin's true \(p\) is hidden. Flip until you're sure.
The top of the posterior is the MAP (maximum a posteriori) estimate:
\[ \hat p_{\text{MAP}} = \frac{h + a - 1}{n + a + b - 2} \qquad \text{with } a = b = 2: \quad \frac{h + 1}{n + 2} \]
A prior is what you believed before; the posterior is prior times likelihood, and the data outweighs the prior as it piles up.
Prior Beta(2, 2), then 3 heads and 1 tail. What's the MAP estimate?
7. L2 regularization is a prior
Do the same with a model's weights. Put a bell-curve prior on each weight, centered on 0 with spread \(\tau\): "I expect weights to be small". The log of that prior is \(-w^2 / 2\tau^2\), so maximizing the posterior means minimizing
\[ \underbrace{\frac{1}{2\sigma^2} \sum_i (y_i - \hat y_i)^2}_{\text{NLL: the MSE}} \; + \; \underbrace{\frac{1}{2\tau^2} \lVert w \rVert^2}_{-\log \text{prior}} \]
That's chapter 11's L2 regularization (ridge regression), with \(\lambda = \sigma^2/\tau^2\): a strong belief in small weights (small \(\tau\)) is a big \(\lambda\). Below, five noisy points from the line \(y = 0.5x\); the green line is the MLE (least squares through the origin), the yellow one the MAP. Tighten the prior and watch it pull the slope toward 0:
L2 regularization is a bell-curve prior on the weights that says "probably small"; its strength is how sure you are of that.
When does the prior matter most?
- With lots of data
- With little or noisy data, or many weights per example
8. All of it in code
9. What to carry forward
- Sample statistics estimate population values. Sample variance divides by \(n - 1\) to be unbiased.
- Law of large numbers: averages converge, with error shrinking like \(\sigma/\sqrt n\). Central limit theorem: sums of many independent pieces become bell-shaped.
- MLE: pick the knobs that make the observed data most likely; in practice minimize the negative log-likelihood.
- Gaussian noise → MSE. Categorical outputs → cross-entropy. Heavy-tailed noise → absolute error. A loss is a noise model.
- Bayesian updating: posterior ∝ likelihood × prior. A Beta prior on a coin acts like pretend flips; add-one smoothing is one.
- MAP = MLE plus a prior. A Gaussian prior on weights is L2 regularization, with \(\lambda = \sigma^2/\tau^2\).
All lessons: AI from scratch.
Last updated