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

The big idea

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.

In this chapter you will learn to
  1. Distinguish a parameter, an estimator and an estimate.
  2. Judge estimators by bias, variance and mean squared error.
  3. Explain why the sample variance divides by .
  4. Write a likelihood and log-likelihood, and maximize them.
  5. Derive least squares and cross-entropy as maximum likelihood.
  6. Recognize overfitting and explain regularization.
Before you start

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

TermMeaningExample
parameter a fixed but unknown number describing the populationthe coin’s true heads probability
estimator a rule that turns data into a guess”count heads, divide by “
estimatethe 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

Definition: 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

Bias-variance decomposition

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 variancehigh variance
low biastight cluster on target: idealscattered around the target
high biastight cluster, off targetscattered 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.

Definition: likelihood

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.
Likelihood is not “the probability of ”

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

Maximum likelihood estimation (MLE)

Choose the parameter value that makes the observed data most probable:

Use the log-likelihood

In practice, maximize the log-likelihood:

Three reasons:

  1. Products become sums, which are far easier to differentiate.
  2. 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.
  3. Same answer. is increasing, so the that maximizes also maximizes .

The recipe

  1. Write the likelihood as a product.
  2. Take logs to get .
  3. Differentiate with respect to and set to zero.
  4. 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.


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

Gaussian noise ⟹ least squares

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 modelMaximum likelihood lossBehaviour
Gaussiansquared 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:

Classification loss = negative log-likelihood

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 classLoss
0.990.010
0.90.105
0.50.693
0.12.303
0.014.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:

  1. More data. Variance shrinks.
  2. A simpler model. Fewer parameters to fit noise with.
  3. 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).
  4. Validation. Hold out data the fit never saw, and measure error there. Training error always looks better than real performance.
Never report training error as 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

IdeaFormula or fact
bias
MSEbias² + variance
sample variancedivide by to be unbiased
likelihood
MLE,
Bernoulli, Poisson, Gaussian meanobserved fraction, ,
Gaussian noiseMLE = least squares
categoriesMLE = cross-entropy
overfittinglow bias, high variance; fix with data, simplicity, regularization

Three facts to remember:

  1. MLE picks the parameters that make the observed data most probable.
  2. Your loss function is a hidden assumption about the noise.
  3. 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).

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?

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?

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.


Where this is used

Next: PS 10 Confidence Intervals and Hypothesis Tests: how sure are you, and is the effect real?