Chapter 9: Estimation and maximum likelihood
Previous: PS 08 Law of Large Numbers and Central Limit Theorem | PS 00 Course Map | Next: PS 10 Confidence Intervals and Hypothesis Tests
To fit a model to data, choose the parameters under which the data you actually observed would have been most probable. That is maximum likelihood. It reproduces common-sense answers (the sample mean, the observed fraction) and also explains the loss functions of machine learning: with Gaussian noise it is least squares, and with categories it is cross-entropy.
- Distinguish a parameter, an estimator and an estimate.
- Judge estimators by bias, variance and mean squared error.
- Explain why the sample variance divides by .
- Write a likelihood and log-likelihood, and maximize them.
- Derive least squares and cross-entropy as maximum likelihood.
- Recognize overfitting and explain regularization.
You need the named distributions (PS 03 Discrete Random Variables, PS 05 Continuous Random Variables), standard error (PS 08 Law of Large Numbers and Central Limit Theorem), and finding a maximum with calculus: set the derivative to zero. Two log rules: and .
9.1 From probability to statistics
Probability runs forward: given the parameter, what data will we see? “If the coin is fair, how likely are 7 heads in 10 flips?”
Statistics runs backward: given the data, what was the parameter? “I saw 7 heads in 10 flips. How biased is this coin?”
Vocabulary
| Term | Meaning | Example |
|---|---|---|
| parameter | a fixed but unknown number describing the population | the coin’s true heads probability |
| estimator | a rule that turns data into a guess | ”count heads, divide by “ |
| estimate | the number the rule gives on your data |
Because data is random, an estimator is a random variable: different datasets would give different estimates. So it has a mean, a variance and a sampling distribution, and we can ask whether it is a good rule.
9.2 What makes an estimator good?
Bias
If the bias is zero, the estimator is unbiased: on average it hits the right value.
Variance
How much does the estimate jump around from one dataset to another? , or its square root, the standard error.
Mean squared error
Proof sketch: write , square, and take expectations; the cross term vanishes because .
The darts picture. Bias is how far the centre of your cluster of darts is from the bullseye. Variance is how spread out the cluster is. MSE measures the typical distance of a dart from the bullseye, combining both.
| low variance | high variance | |
|---|---|---|
| low bias | tight cluster on target: ideal | scattered around the target |
| high bias | tight cluster, off target | scattered and off target |
The bias-variance tradeoff
An estimator with a little bias but much less variance can have lower MSE than an unbiased one. Accepting some bias to cut variance is a deliberate and very common strategy: it is what regularization does (section 9.8).
Consistency
An estimator is consistent if as . With enough data it gets there. The sample mean is consistent by the law of large numbers.
9.3 Sample mean and sample variance
- is an unbiased estimator of ().
- is an unbiased estimator of , but only because it divides by .
Why ?
The deviations are measured from , which was itself computed from the same data. is the number that minimizes over all (it is the least squares fit of a constant, LA 06 Orthogonality and Least Squares). So the sum of squared deviations from is always smaller than the sum from the true . Dividing by would therefore underestimate on average.
Exactly how much smaller? On average by one : . Dividing by corrects it.
Degrees of freedom. The deviations must sum to zero, so only of them are free. One degree of freedom was “used up” estimating the mean.
Worked example 9.1. Data . . Squared deviations , sum 8. , . (Dividing by would give .)
9.4 Likelihood
The definition
Suppose the data come from a model with density or mass function , and the observations are independent.
This is the probability (or density) of the observed data, viewed as a function of with the data held fixed.
It is the same formula as the probability of the data, but read differently:
- As a function of the data (with fixed): a probability distribution.
- As a function of (with data fixed): the likelihood. It scores how well each candidate explains what was actually seen.
need not sum or integrate to 1 over . It answers “how probable is this data if were true?”, which is , not . Getting the second requires a prior and Bayes’ rule (PS 11 Bayesian Inference).
Maximum likelihood estimation
Choose the parameter value that makes the observed data most probable:
Use the log-likelihood
In practice, maximize the log-likelihood:
Three reasons:
- Products become sums, which are far easier to differentiate.
- Numerical safety. A product of 10,000 probabilities each around 0.1 is , which underflows to zero on a computer. The sum of logs is about , perfectly representable.
- Same answer. is increasing, so the that maximizes also maximizes .
The recipe
- Write the likelihood as a product.
- Take logs to get .
- Differentiate with respect to and set to zero.
- Solve for . (Check it is a maximum.)
9.5 Worked examples of MLE
Worked example 9.2: a coin (Bernoulli)
flips give heads. Each flip has probability of heads.
Step 1. (one particular sequence; the binomial coefficient is a constant and does not affect the maximizer).
Step 2. .
Step 3.
Step 4. Multiply out: , so and
The observed fraction. With 7 heads in 10 flips, .
This is reassuring: the principle reproduces common sense in the simple case, which is evidence that it can be trusted in complicated cases where common sense gives no answer.
Worked example 9.3: Poisson counts
Counts per hour from Poisson():
The sample mean. For counts : .
Worked example 9.4: Gaussian mean and variance
Data from :
The mean. Only the last term depends on , and it is maximized by minimizing . That gives .
The variance. Differentiate with respect to and set to zero:
Note it divides by , so it is slightly biased downward (section 9.3). MLE is not guaranteed to be unbiased. It is guaranteed (under mild conditions) to be consistent, and for large samples to have the smallest possible variance among well-behaved estimators. The bias here vanishes as grows.
Worked example 9.5: exponential lifetimes
Lifetimes from Exponential(): . Setting gives . If five parts lasted hours, and per hour.
A policy succeeds 18 times in 24 trials. What is the MLE of its success rate?
Answer. .
9.6 Least squares is maximum likelihood
The model
Suppose each output is a deterministic function of the input plus Gaussian noise:
Then , and the log-likelihood is
Maximizing this likelihood is exactly minimizing the sum of squared errors.
So mean squared error is not an arbitrary choice. It is the correct loss if the noise is Gaussian. The linear regression of LA 06 Orthogonality and Least Squares is maximum likelihood under that assumption.
Other noise, other losses
If the noise has heavier tails, a different loss is correct:
| Noise model | Maximum likelihood loss | Behaviour |
|---|---|---|
| Gaussian | squared error | sensitive to outliers |
| Laplace (double exponential) | absolute error | robust to outliers; fits the median |
This is why L1 (absolute) loss is used when data contains outliers.
9.7 Cross-entropy is maximum likelihood
The model
A classifier (or a discrete-action policy) outputs a probability for each class: . Training data are pairs of inputs and true labels.
The likelihood of the observed labels is . Take logs, negate, and average:
This is the cross-entropy loss (also called the negative log-likelihood, NLL). Minimizing it is maximizing the likelihood of the training labels.
What the loss rewards
| Probability given to the correct class | Loss |
|---|---|
| 0.99 | 0.010 |
| 0.9 | 0.105 |
| 0.5 | 0.693 |
| 0.1 | 2.303 |
| 0.01 | 4.605 |
Being right confidently costs almost nothing. Being confidently wrong is punished severely. The connection to information theory is explained in PS 12 Markov Chains and Information.
Behaviour cloning with discrete actions is exactly this: the expert’s actions are the labels, and the policy is trained to maximize their likelihood (06 Imitation and Distribution Shift).
9.8 Overfitting and regularization
The problem
Maximum likelihood uses only the training data. With a flexible model and little data, it fits the noise as well as the signal.
Extreme example. A coin shows 3 heads in 3 flips. MLE says : the coin never shows tails. That is a confident and almost certainly wrong conclusion from tiny data. (High variance.)
A polynomial with as many parameters as data points passes through every point exactly, including the noise, and predicts wildly between them.
Remedies
All of these accept a little bias in exchange for much lower variance:
- More data. Variance shrinks.
- A simpler model. Fewer parameters to fit noise with.
- Regularization. Add a penalty for complexity to the loss: This pulls parameters toward zero. It has a Bayesian reading as a prior belief that parameters are small (PS 11 Bayesian Inference).
- Validation. Hold out data the fit never saw, and measure error there. Training error always looks better than real performance.
The model was chosen to fit the training data, so it looks better there than it is. Performance must be measured on data that played no part in fitting or in choosing the model.
Summary
| Idea | Formula or fact |
|---|---|
| bias | |
| MSE | bias² + variance |
| sample variance | divide by to be unbiased |
| likelihood | |
| MLE | , |
| Bernoulli, Poisson, Gaussian mean | observed fraction, , |
| Gaussian noise | MLE = least squares |
| categories | MLE = cross-entropy |
| overfitting | low bias, high variance; fix with data, simplicity, regularization |
Three facts to remember:
- MLE picks the parameters that make the observed data most probable.
- Your loss function is a hidden assumption about the noise.
- Lower error on training data is not better performance; check on held-out data.
Exercises
Part A: warm-up
A1. Data . Compute , the MLE of the variance, and .
A2. In 40 grasp attempts, 34 succeed. What is the MLE of the success probability?
A3. An estimator has bias 0.1 and variance 0.04. Another has bias 0 and variance 0.09. Which has lower MSE?
A4. A classifier gives the true class probability 0.8 on one example and 0.3 on another. Compute the average cross-entropy loss (natural log).
A1. . Squared deviations , sum 46. MLE . .
A2. .
A3. versus . The biased one.
A4. .
Part B: core
B1. Derive the MLE of for the geometric distribution, given observed waiting times .
B2. Lifetimes (hours) of five components: . Assuming an exponential model, find the MLE of the failure rate and of the mean lifetime.
B3. You fit (a line through the origin) with Gaussian noise. Derive the MLE of for data . Apply it to , , .
B4. Explain why fitting a degree-9 polynomial to 10 noisy points typically has lower training error but higher test error than a degree-2 polynomial. Use the words bias and variance.
B5. Show that the MLE for the mean of is the same whatever the value of . Why does that matter?
B1. . Derivative gives .
B2. . per hour; mean lifetime 120 hours.
B3. Minimize : derivative , so .
B4. The degree-9 polynomial has enough freedom to pass through all 10 points (low bias, near-zero training error) but it fits the noise, so it changes wildly with the particular sample (high variance) and predicts badly between points. The degree-2 polynomial cannot fit the noise (some bias) but is stable (low variance), so it generalizes better.
B5. appears only in , and any positive constant factor does not move the minimizer. So you can estimate the mean without knowing the noise level, which is why least squares works without knowing .
Part C: explain and prove
C1. Prove that minimizes over all numbers .
C2. Prove the bias-variance decomposition .
C3. Explain why maximizing likelihood and maximizing log-likelihood give the same answer, and why the second is preferred in code.
C4. A colleague trains with squared error on data containing a few large sensor glitches. What do you suggest, and why, in terms of noise models?
C1. Derivative gives ; the second derivative confirms a minimum.
C2. Section 9.2’s proof sketch, written out: , and the middle term is 0.
C3. is strictly increasing, so it preserves the location of the maximum. Logs turn products into sums (easier derivatives) and avoid numerical underflow.
C4. Squared error assumes Gaussian noise, which makes large errors extremely unlikely, so the fit bends to explain the glitches. Use absolute error or Huber loss (Laplace-like heavy-tailed noise), or detect and remove the glitches.
Part D: practise with code
D1. For a coin with 7 heads in 10 flips, plot and for . Mark the maximum.
D2. Draw 5 samples from , compute the variance with ddof=0 and ddof=1. Repeat 10,000 times and average each. Which one averages to 1?
D3. Fit polynomials of degree 1 to 9 to 12 noisy points from . Plot training error and error on 200 fresh points against degree. Find where test error is lowest.
D4. Fit a line by least squares to data with one huge outlier, then fit it by minimizing absolute error (scipy.optimize.minimize). Compare the two lines.
D2. ddof=1 (dividing by ) averages to about 1; ddof=0 averages to about .
D3. Training error keeps falling with degree; test error falls, then rises sharply: the classic U-shape of overfitting.
Where this is used
- Every supervised loss in 05 Training Neural Policies is a negative log-likelihood under some noise model.
- Behaviour cloning is maximum likelihood on expert actions (06 Imitation and Distribution Shift).
- The diffusion training objective is derived from a likelihood bound (08 Diffusion and Flow Matching).
- System identification: fitting a robot’s mass, friction and delay parameters from logged data.
Next: PS 10 Confidence Intervals and Hypothesis Tests: how sure are you, and is the effect real?