Maximum Likelihood Estimation
§8.2 never wrote down a probability. This section does, and the book is explicit about the mapping:
In Section 8.3.1, we introduce the likelihood, which is analogous to the concept of loss functions (Section 8.2.2) in empirical risk minimization. The concept of priors (Section 8.3.2) is analogous to the concept of regularization (Section 8.2.3).
This page does the first correspondence and page 805 does the second. And “analogous” turns out to be an understatement — measured, the two objectives are affine transforms of each other, so they rank every parameter identically.
What you’ll learn
Section titled “What you’ll learn”- Equation 8.14, the negative log-likelihood, and why the negative sign is there at all.
- The interpretive point the book makes twice: read two ways is two different objects.
- Measured: the likelihood does not integrate to 1 over — it integrates to in the worked case. It is not a distribution over parameters.
- Equations 8.15–8.17: the supervised setting, and where the independence assumption turns a product into a sum.
- Example 8.5, Equation 8.18: Gaussian maximum likelihood is least squares. Measured, the minimisers agree to and the objectives differ by .
- The three asymptotic properties of the MLE, and the warning attached to them: measured, error is roughly constant, confirming decay.
Intuition: which knob best explains what you saw?
Section titled “Intuition: which knob best explains what you saw?”You have a machine with a dial on it. Turn the dial to and the machine spits out numbers according to . You did not see the dial, but you saw the numbers.
Maximum likelihood asks: which dial setting makes the numbers I saw least surprising? Not “which is most probable” — the dial has no probability attached, that would need a prior — but which setting assigns the highest density to the observations.
The whole trick is that can be read in two directions. Read it with nailed down and free, it is a distribution over data. Read it with nailed down — because you observed it — and free, it is the likelihood. Same formula. Different function, different variable, different meaning.
flowchart TD M["a probabilistic model
p(y | x, theta)"] M -->|"fix theta, vary y"| D["a DISTRIBUTION over data
integrates to 1"] M -->|"fix y, vary theta"| L["the LIKELIHOOD
does NOT integrate to 1"] L --> NLL["Eq 8.14: negative log-likelihood
minimise instead of maximise"] NLL -->|"independence, Eq 8.17"| SUM["a SUM over examples
instead of a product"] SUM -->|"Gaussian, Eq 8.18"| LS["exactly least squares
Section 8.2's Example 8.2"] L -.->|"multiply by a prior"| POST["the POSTERIOR
Section 8.3.2"] style POST stroke-dasharray: 4 3
Equation 8.14: the negative log-likelihood
Section titled “Equation 8.14: the negative log-likelihood”For data represented by a random variable and a family of densities :
The subscript emphasises that is varying and is fixed, and the book notes it is usually dropped, leaving — “as it is really a function of ”.
Three transformations happened in that one line, and each has a reason:
- The logarithm. Independence makes the joint density a product over examples, and a product of small numbers underflows. §0.3 measured the failure: a product of probabilities of reaches exactly
0.0in float64. The logarithm turns it into a sum, which does not. - The negative sign. The book calls it “a historical artifact that is due to the convention that we want to maximize likelihood, but numerical optimization literature tends to study minimization of functions.” That is all it is.
- Nothing else. is strictly increasing and negation reverses order exactly once, so with no approximation.
The two readings
Section titled “The two readings”The book states this carefully, so it is worth quoting both halves.
Fix , vary : “It is a distribution that models the uncertainty of the data. In other words, once we have chosen the type of function we want as a predictor, the likelihood provides the probability of observing data .”
Fix , vary : “It tells us how likely a particular setting of is for the observations . Based on this second view, the maximum likelihood estimator gives us the most likely parameter for the set of data.”
Equations 8.15–8.17: the supervised setting
Section titled “Equations 8.15–8.17: the supervised setting”Given pairs with and , we specify the conditional distribution of the labels given the examples:
Read the model this asserts: the label is the linear prediction plus Gaussian noise of known variance. Note what §8.2 did not have to say — page 803’s §8.2.5 quote, that empirical risk minimization never has to “specify the noise distribution for the labels”. Here you do.
Then, using independence:
Example 8.5: the derivation that collapses two frameworks into one
Section titled “Example 8.5: the derivation that collapses two frameworks into one”Substituting the Gaussian and expanding, step by step:
The logarithm splits the product inside into a sum:
and cancels:
The book’s conclusion: “As is given, the second term in (8.18d) is constant, and minimizing corresponds to solving the least-squares problem.”
What that means precisely
Section titled “What that means precisely”Compare the first term with Equation 8.8’s . They differ by the factor . So
A positive multiple plus a constant. Neither operation can move an . Measured with and : the slope is , the constant is , and the two minimisers agree to .
So §8.2 and §8.3 are not two methods that happen to agree on this example. For a Gaussian likelihood with known variance they are the same objective in different notation, and the choice between them is a choice of vocabulary — until §8.3.2 adds a prior, where the vocabularies start to buy different things.
§8.3.2’s remark: what maximum likelihood guarantees
Section titled “§8.3.2’s remark: what maximum likelihood guarantees”The book lists three properties (Lehmann and Casella, 1998; Efron and Hastie, 2016):
- Asymptotic consistency. The MLE converges to the true value in the limit of infinitely many observations, plus a random error that is approximately normal.
- The error’s variance decays as .
- And the caveat: “the size of the samples necessary to achieve these properties can be quite large.”
Then the warning that motivates the next page: “Especially, in the ‘small’ data regime, maximum likelihood estimation can lead to overfitting.”
Measured on a three-parameter model with known truth:
| mean squared error | error | |
|---|---|---|
The right column is roughly constant from onward, which is the claim. At it is — noticeably above the asymptote, which is the “samples necessary can be quite large” caveat showing up at the small end.
Worked example by hand
Section titled “Worked example by hand”Derive the MLE for the mean of a Gaussian, the smallest complete case.
Model: with known, and observations .
Step 1: the negative log-likelihood.
Step 2: differentiate and set to zero.
The maximum likelihood estimate of a Gaussian mean is the sample mean. With these numbers:
Measured by a grid search over the likelihood: , differing only by the grid spacing.
Step 3: check it is a minimum. . Positive for every , so it is a minimum of and hence a maximum of the likelihood.
Step 4: notice what did. It appears in , it appears in the second derivative, and it cancels completely from the answer. That is the same cancellation as Equation 8.18’s: with known and constant, it scales the objective without moving its minimiser. The MLE for the mean is the sample mean whatever the noise level is.
See it move
Section titled “See it move”The two readings are much easier to feel than to read about:
From scratch
Section titled “From scratch”import numpy as np
SIGMA = 0.35
def make(n, seed, noise=SIGMA):
rng = np.random.default_rng(seed)
x = np.sort(rng.uniform(-3, 3, n))
return x, np.sin(1.4 * x) + 0.3 * x + noise * rng.standard_normal(n)
def design(x, deg):
return np.vander(x / 3.0, deg + 1, increasing=True)
x, y = make(25, seed=3)
Phi = design(x, 3)
N = len(y)
def empirical_risk(th):
"""Equation 8.7."""
return float(np.mean((y - Phi @ th) ** 2))
def nll(th):
"""Equation 8.18d, written exactly as the book leaves it."""
r = y - Phi @ th
return float(r @ r / (2 * SIGMA ** 2)
- N * np.log(1.0 / np.sqrt(2 * np.pi * SIGMA ** 2)))
# --- the two objectives have the same minimiser ---------------------------
th_ls = np.linalg.lstsq(Phi, y, rcond=None)[0]
# minimise the NLL from a different start by Newton's method
th = np.zeros(Phi.shape[1])
H = Phi.T @ Phi / SIGMA ** 2
for _ in range(50):
g = -Phi.T @ (y - Phi @ th) / SIGMA ** 2
th = th - np.linalg.solve(H, g)
print("least-squares theta :", np.round(th_ls, 6).tolist())
print("NLL-minimising theta:", np.round(th, 6).tolist())
print(f"max |difference| : {np.abs(th - th_ls).max():.3e}")
# --- and they differ by an affine transformation --------------------------
const = -N * np.log(1.0 / np.sqrt(2 * np.pi * SIGMA ** 2))
slope = N / (2 * SIGMA ** 2)
print(f"\nEquation 8.18d says L = (1/(2 sigma^2)) sum r^2 + const")
print(f" in terms of R_emp that is L = {slope:.6f} * R_emp + "
f"({const:.6f})")
print(f"\n{'theta tried':>36} {'R_emp':>12} {'L':>14} {'predicted L':>14}")
for scale in (0.0, 0.5, 1.0, 1.5):
t = scale * th_ls
pred = slope * empirical_risk(t) + const
print(f"{str(np.round(t, 3).tolist()):>36} {empirical_risk(t):>12.6f} "
f"{nll(t):>14.6f} {pred:>14.6f}")
print("the last two columns agree, so the NLL is an affine function of R_emp")
print("and a positive multiple plus a constant cannot move an argmin.")
# --- the likelihood is not a distribution over theta ---------------------
print("\nThe likelihood is NOT a distribution over theta:")
obs = np.array([1.2, 2.1, 1.7])
sig = 0.8
ths = np.linspace(-10, 12, 400001)
lik = np.ones_like(ths)
for o in obs:
lik *= np.exp(-0.5 * ((o - ths) / sig) ** 2) / (sig * np.sqrt(2 * np.pi))
print(f" three observations {obs.tolist()}, sigma = {sig}")
print(f" area under the likelihood in theta: {np.trapezoid(lik, ths):.6f}")
print(f" argmax at theta = {ths[int(np.argmax(lik))]:.6f}, "
f"sample mean = {obs.mean():.6f}")
ys = np.linspace(-12, 14, 400001)
dens = np.exp(-0.5 * ((ys - 2.0) / sig) ** 2) / (sig * np.sqrt(2 * np.pi))
print(f" area under p(y | theta=2) in y: {np.trapezoid(dens, ys):.6f}")
print(" one integrates to 1, the other does not. Only one is a density.")
# --- Section 8.3.2's remark: the error variance decays as 1/N -----------
print("\nThe MLE error variance decays as 1/N:")
true_theta = np.array([0.4, 1.2, -0.7])
rng = np.random.default_rng(0)
print(f"{'N':>8} {'mean sq error':>16} {'N x error':>12}")
for n in (10, 40, 160, 640, 2560, 10240):
trials = 2000
errs = np.empty(trials)
for t in range(trials):
xs = rng.uniform(-2, 2, n)
A = np.vander(xs, 3, increasing=True)
ys_ = A @ true_theta + 0.5 * rng.standard_normal(n)
thn = np.linalg.lstsq(A, ys_, rcond=None)[0]
errs[t] = np.sum((thn - true_theta) ** 2)
m = errs.mean()
print(f"{n:>8} {m:>16.8f} {n * m:>12.6f}")
print("N times the error is roughly constant, which is the 1/N claim.")least-squares theta : [-0.116506, 3.633144, 0.492278, -4.086057]
NLL-minimising theta: [-0.116506, 3.633144, 0.492278, -4.086057]
max |difference| : 1.776e-15
Equation 8.18d says L = (1/(2 sigma^2)) sum r^2 + const
in terms of R_emp that is L = 102.040816 * R_emp + (-3.272090)
theta tried R_emp L predicted L
[-0.0, 0.0, 0.0, -0.0] 0.998583 98.624110 98.624110
[-0.058, 1.817, 0.246, -2.043] 0.359425 33.403965 33.403965
[-0.117, 3.633, 0.492, -4.086] 0.146373 11.663917 11.663917
[-0.175, 5.45, 0.738, -6.129] 0.359425 33.403965 33.403965
the last two columns agree, so the NLL is an affine function of R_emp
and a positive multiple plus a constant cannot move an argmin.
The likelihood is NOT a distribution over theta:
three observations [1.2, 2.1, 1.7], sigma = 0.8
area under the likelihood in theta: 0.104496
argmax at theta = 1.666655, sample mean = 1.666667
area under p(y | theta=2) in y: 1.000000
one integrates to 1, the other does not. Only one is a density.
The MLE error variance decays as 1/N:
N mean sq error N x error
10 0.15053755 1.505375
40 0.02453147 0.981259
160 0.00586250 0.938000
640 0.00145983 0.934290
2560 0.00037095 0.949635
10240 0.00009030 0.924683
N times the error is roughly constant, which is the 1/N claim.On real data
Section titled “On real data”Reading the plot
Section titled “Reading the plot”The first figure is the distinction the whole section turns on. Both panels are built from the same formula and the same three observations. On the left, is fixed at three different values and runs along the axis: three bell curves, each integrating to , each a legitimate probability density over data. The green lines are the observations, and you can see each curve assigning them different densities.
On the right, the observations are fixed and runs along the axis. The three coloured squares are the same three settings — the product of the three green dots’ heights, for each curve. Sweeping traces out the likelihood.
Now the part that matters: the annotation says the area under the right-hand curve is . It is not , it was never going to be , and nothing in the construction normalises it. The likelihood is a function of , not a distribution over . Phrases like “the most likely parameter” are convenient and slightly wrong; the object that is a distribution over is the posterior, and getting it requires the prior of §8.3.2.
The second figure turns “analogous” into “identical”. The left panel slices both objectives along one coordinate. The blue curve () and the green curve () are on different axes with different scales — but their minima are at the same place, to six decimals.
The right panel is why. Plot directly against and you get a straight line: slope , intercept , with a maximum deviation at the level. An affine map with positive slope is monotone, so it preserves ordering exactly — every that one objective prefers, the other prefers too.
This is stronger than an analogy and it is worth being clear about the scope. It holds for a Gaussian likelihood with known, constant variance. Change the noise model and the correspondence breaks: a Laplace likelihood gives absolute loss, not squared. Let depend on and the sum becomes weighted least squares. The general statement is that choosing a noise distribution is choosing a loss function — and §8.2’s freedom not to specify one is exactly the freedom §8.3 gives up.
The third figure checks the three claims and the caveat. The left panel plots the mean squared error against on log-log axes with a pure reference. The measured products run , , , , , — settled by and constant thereafter. The one visible outlier is , sitting above the asymptote, which is the book’s “the size of the samples necessary to achieve these properties can be quite large” made visible at the small end.
The middle panel checks “approximately normal”: standardised errors against a standard normal, with measured skew and excess kurtosis both near zero. For a linear-Gaussian model this is exact rather than asymptotic, which is why the agreement is so clean — a nonlinear model would show visible departure at small .
The right panel is the warning, and it is the bridge to page 805. With the same estimator, with no bug and no misconfiguration, produces an expected risk that climbs steeply with model complexity. The MLE has no mechanism to prevent this: it maximises fit to the data it has, full stop. §8.2.3 added a penalty to fix that; §8.3.2 adds a prior, and page 805 measures that they are the same repair.
Pitfalls
Section titled “Pitfalls”Compare
Section titled “Compare”| empirical risk minimization, §8.2 | maximum likelihood, §8.3.1 | |
|---|---|---|
| the object minimised | , Eq 8.6 | , Eq 8.14 |
| what you must specify | a loss function | a noise distribution |
| the Gaussian case | squared loss | the same objective, scaled |
| measured relation | — | |
| minimisers agree to | — | |
| regularisation appears as | a penalty term, §8.2.3 | a prior, §8.3.2 |
| output | a point estimate | a point estimate |
| can express predictive uncertainty | no | yes, via the noise model |
| noise model | the loss it implies |
|---|---|
| Gaussian, constant | squared loss |
| Gaussian, | weighted squared loss |
| Laplace | absolute loss |
| Bernoulli | cross-entropy / logistic loss |
-
Why does the likelihood in the worked example integrate to 0.104496 rather than 1?
The density p(y | theta) integrates to exactly 1.000000 over y, because that is what a density does. The likelihood is the same formula read along the other axis, and nothing normalises it there. Turning it into a distribution over theta requires a prior, which is Section 8.3.2.
pch.quizShowAnswer
B — Because it is a function of theta and was never normalised in theta — it is not a density over parameters — The density p(y | theta) integrates to exactly 1.000000 over y, because that is what a density does. The likelihood is the same formula read along the other axis, and nothing normalises it there. Turning it into a distribution over theta requires a prior, which is Section 8.3.2.
-
Equation 8.18 shows the Gaussian negative log-likelihood equals (N / 2 sigma squared) times the empirical risk, plus a constant. What follows?
An affine map with positive slope is strictly monotone, so it preserves ordering exactly: every theta one objective prefers, the other prefers too. Section 8.2 and Section 8.3 are the same objective in different vocabulary — for this noise model.
pch.quizShowAnswer
B — They have identical minimisers, because a positive multiple plus a constant cannot move an argmin — measured agreement 1.8e-15 — An affine map with positive slope is strictly monotone, so it preserves ordering exactly: every theta one objective prefers, the other prefers too. Section 8.2 and Section 8.3 are the same objective in different vocabulary — for this noise model.
-
Does maximum likelihood always reduce to least squares?
The cancellation in Equation 8.18 depends on the specific form of the Gaussian and on sigma being constant. The general statement is that choosing a noise distribution IS choosing a loss function — which is exactly the specification Section 8.2 was free to skip.
pch.quizShowAnswer
B — No — only for a Gaussian likelihood with known constant variance. A Laplace likelihood gives absolute loss, and an input-dependent sigma gives weighted least squares — The cancellation in Equation 8.18 depends on the specific form of the Gaussian and on sigma being constant. The general statement is that choosing a noise distribution IS choosing a loss function — which is exactly the specification Section 8.2 was free to skip.
-
Why is the negative sign in Equation 8.14 there?
The book says exactly this. Negation reverses the ordering once, so argmax of p equals argmin of L with no approximation. The logarithm, by contrast, IS doing work — it turns a product that underflows into a sum that does not.
pch.quizShowAnswer
B — It is a historical artifact: we want to maximise likelihood, but optimisation literature studies minimisation — The book says exactly this. Negation reverses the ordering once, so argmax of p equals argmin of L with no approximation. The logarithm, by contrast, IS doing work — it turns a product that underflows into a sum that does not.
-
N times the MLE's mean squared error measured 1.505 at N = 10 and settled near 0.93 from N = 40 onward. What does that show?
A constant product means error proportional to one over N, which is the book's claim. The N = 10 value sitting 60 percent above the asymptote is the book's own caveat — that the sample sizes needed can be quite large — showing up at the small end, and it is why Section 8.3.2 exists.
pch.quizShowAnswer
B — The 1 over N decay is confirmed asymptotically, and N = 10 is visibly outside the regime where the asymptotic properties hold — A constant product means error proportional to one over N, which is the book's claim. The N = 10 value sitting 60 percent above the asymptote is the book's own caveat — that the sample sizes needed can be quite large — showing up at the small end, and it is why Section 8.3.2 exists.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – The MLE of a Gaussian mean
Section titled “Exercise 1 – The MLE of a Gaussian mean”Exercise 2 – The likelihood is not a density over theta
Section titled “Exercise 2 – The likelihood is not a density over theta”Exercise 3 – Equation 8.18, the affine relation
Section titled “Exercise 3 – Equation 8.18, the affine relation”Exercise 4 – Both routes reach the same theta
Section titled “Exercise 4 – Both routes reach the same theta”Exercise 5 – The 1/N decay, and where it fails
Section titled “Exercise 5 – The 1/N decay, and where it fails”Recall card
Section titled “Recall card”- Section 8.3’s own mapping: the likelihood is analogous to a loss function, and a prior is analogous to regularisation. Measured, “analogous” understates it — for a Gaussian the two are affine transforms of each other.
- Equation 8.14 is minus the log of the likelihood. The log turns an underflowing product into a sum; the negative sign is a historical artifact of the minimisation convention. Neither moves the argmin.
- p(x given theta) is one formula and two objects. Fix theta and vary x: a distribution over data, integrating to one. Fix x and vary theta: the likelihood, which does not.
- Measured: the likelihood integrated to 0.104496 over theta while the density integrated to 1.000000 over y. “The most likely theta” is a figure of speech; the object that IS a distribution over theta is the posterior.
- Theta on the right of the conditioning bar is still the variable. The book warns about this explicitly — the bar means “for this setting of”, not “having observed”.
- Equations 8.15 to 8.17: a Gaussian conditional on the linear prediction, then independence turns the product into a sum of logs.
- Example 8.5’s punchline: the Gaussian NLL is (N over 2 sigma squared) times the empirical risk plus a constant. Measured with N = 25 and sigma = 0.35, that is 102.040816 times R_emp minus 3.272090, and the two minimisers agree to 1.8e-15.
- A positive multiple plus a constant cannot move an argmin, so Section 8.2 and Section 8.3 are the same objective in different vocabulary.
- But only for THIS noise model. Laplace gives absolute loss; an input-dependent sigma gives weighted least squares. Choosing a noise distribution IS choosing a loss function — the specification Section 8.2 was free to skip.
- Sigma cancels from the answer. In the worked example it appears in the NLL and in its second derivative and vanishes from the estimate: the MLE of a Gaussian mean is the sample mean at any noise level.
- Three asymptotic properties: consistency, approximately normal error, and error variance decaying as one over N. Measured, N times the error settles near 0.93 from N = 40 onward.
- And one caveat that bites. At N = 10 the product was 1.505, 60 percent above the asymptote, and with N = 12 the MLE overfits badly. The book’s closing line is that in the small-data regime maximum likelihood can lead to overfitting — which is what the next page fixes.
Next: add a prior, and discover it was the penalty term all along. MAP Estimation and Model Fitting
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading