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\)?

Mean 4, squared deviations 4, 0, 4, sum 8. Divided by \(n - 1 = 2\): \(s^2 = 4\). (Dividing by 3 would give 2.67.) NumPy's 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?

\(1.708 / \sqrt{100} = 0.171\). So the average of 100 rolls almost always lands within about \(3.5 \pm 0.34\) (two standard deviations).

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?

Skewed pieces take longer than a die to get there (a single wait is very lopsided), but the sum of 30 already looks normal. The theorem needs independent pieces with finite variance; it doesn't care about their shape.

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

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?

At \(p = 0.7\). Set the derivative of the log-likelihood to zero (chapter 2: the bottom of a valley, like the top of a hill, is where the slope is zero) and the answer is the fraction of heads.

Set heads to 0 and flips to 3. The MLE says \(p = 0\): this coin can never land heads. What's wrong?

MLE has no notion of "I've barely looked". It's the same trap as P1's spam filter seeing a word only in spam, and the cure is the same: a little prior belief. That's section 6.

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?

Choosing a loss is choosing a noise model. Heavier-tailed noise (a Laplace distribution) gives the absolute error \(|y - \hat y|\), which fits the median and shrugs off outliers; the Huber loss mixes the two. Or take logs of a skewed target first, as Probability 2 suggested.

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?

Posterior Beta(5, 3); its peak is \((5 - 1)/(5 + 3 - 2) = 4/6 \approx 0.667\), a little less extreme than the MLE's 3/4. With a = b = 2 the MAP is \((h + 1)/(n + 2)\): exactly the "add one to each count" smoothing from P1's spam filter. Smoothing was a prior all along.

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?

The NLL is a sum over examples, so it grows with \(n\); the prior's term doesn't. Regularization matters most exactly where overfitting does (chapter 11): few examples, many knobs. A weight decay of 0.01 in a training config is this prior with a fixed width.

8. All of it in code

9. What to carry forward

All lessons: AI from scratch.

Last updated