Maximum Likelihood & MAP
Choosing parameters that make the data most probable.
Every time you train a classifier with cross-entropy or fit a line by least squares, you are maximizing a likelihood. This lesson derives maximum likelihood estimates from scratch, shows that they match the model to the data's distribution, and adds a prior to get MAP estimation, which turns out to be ridge and the lasso in disguise.
What you’ll learn
- Write the likelihood and log-likelihood of i.i.d. data, and derive the maximum likelihood estimates for Bernoulli and Gaussian models.
- Prove that the Gaussian variance MLE is biased by the factor , and explain why that bias is not a flaw in itself.
- Show that maximizing the likelihood minimizes the cross-entropy and the KL divergence from the empirical distribution, and read common losses as negative log-likelihoods.
- Derive MAP estimation as the MLE plus a log-prior, and recover ridge from a Gaussian prior and the lasso from a Laplace prior.
- Explain how zero counts break the MLE on small samples, and repair them with additive smoothing.
The likelihood function
A parametric model is a family of distributions . Given data drawn i.i.d. from one member of the family, the likelihood is the probability (or density) of the observed data, read as a function of the parameters, and the log-likelihood is its logarithm:
The maximum likelihood estimate is . Logs change nothing about where the maximum is, since is increasing, but they turn products into sums that are easy to differentiate, and they prevent underflow: 1,000 flips of a fair coin have probability , on the edge of what double precision can represent.
A coin with gives for . With heads among flips:
Set the derivative to zero:
The second derivative is negative everywhere, so is concave and this stationary point is the global maximum when . If or , is monotone and the maximum sits on the boundary, or .
From 100 flips you find . What is the maximum likelihood estimate of the odds ?
- It must be derived again from scratch; there is no shortcut
- , because the odds and the probability are the same parameter
Show the answer
C.
The MLE is invariant: if maximizes the likelihood, then for any one-to-one reparameterization , the MLE of is . Relabeling the parameter does not change which distribution makes the data most probable.
Gaussian MLE, and a biased variance
For i.i.d., the log-likelihood is
Setting gives the sample mean, whatever is. Then gives the average squared deviation:
To find , expand around the true mean. The cross term collapses because :
Each has mean and , so the deviations from fall short by exactly one : is fitted to the same data, so the points sit closer to it than to the truth.
You estimate a Gaussian's variance by maximum likelihood from observations. On average, the estimate is what percentage of the true variance?
Show the answer
80 %
: a 20% underestimate on average. Dividing by instead (Bessel's correction) removes the bias. Yet for Gaussian data the MLE has the smaller mean squared error, against at , and dividing by does better still (). Unbiasedness is one virtue among several, not a requirement.
The same steps in dimensions give and . Conditional models work the same way. In linear regression with Gaussian noise, , the log-likelihood is . For any it is maximized by minimizing the squared error: the MLE of is least squares, and , biased low again (the unbiased version divides by ).
Maximum likelihood matches distributions
Why is maximum likelihood a sensible goal at all? Rewrite the average log-likelihood as an expectation under the empirical distribution , which puts mass on each data point.
The average log-likelihood is an average of over the data:
For discrete data its negative is the cross-entropy from to the model, which splits into the data's own entropy plus the KL divergence:
does not depend on . So maximizing the likelihood is the same as making the model's distribution as close as possible, in KL, to the data's:
As the law of large numbers turns the average into an expectation under the true distribution (for densities, is the differential entropy). The MLE therefore aims at the parameter whose distribution is closest to the truth in KL: the true parameter if the model is right, the best approximation if it is not.
| Loss you minimize | Noise model it assumes | Where you meet it |
|---|---|---|
| squared error | least squares, most regression | |
| absolute error | Laplace noise around | median regression, robust to outliers |
| log loss | logistic regression, binary classifiers | |
| softmax cross-entropy | categorical with probabilities | multiclass networks |
| Poisson deviance, up to constants | count regression |
MAP: a prior becomes a penalty
Put a prior on the parameters. The posterior is proportional to likelihood × prior, and its mode is the MAP estimate. The evidence does not depend on , so it drops out:
MAP is maximum likelihood with a penalty, and the penalty is the negative log-prior. For a coin with a Beta prior , the same calculus as before gives : the prior adds imaginary heads and imaginary tails.
Linear regression with and a Gaussian prior . The negative log-posterior, up to constants, is
Multiply by , which does not move the minimizer: this is ridge regression, with the penalty set by the ratio of noise to prior variance.
With independent Laplace priors instead, , and the same rescaling gives the lasso (Tibshirani, 1996, noted this reading):
Small samples: zero counts and smoothing
For a categorical variable with outcomes and counts , maximizing subject to (one Lagrange multiplier) gives . Every outcome that has not been seen gets probability exactly zero.
That is fatal in naive Bayes. A spam filter multiplies one probability per word; if "refund" never occurred in the legitimate emails of the training set, any new email containing it gets likelihood zero under "legitimate", whatever its other thousand words say. The standard repair is additive smoothing:
With it is Laplace's add-one rule. It is the posterior mean under a symmetric Dirichlet prior with parameter , or the MAP estimate under a Dirichlet with parameter , as Conjugate Priors & Exact Posteriors shows.
A six-sided die is rolled 20 times and never shows a six. With add-one smoothing (, ), what probability do you assign to a six?
Show the answer
3.8 %
. The MLE says 0%, which no one believes about a die. The smoothed estimate is still well below the fair , because twenty rolls with no six are some evidence against it, but it leaves room for the next roll to be a six.
How much should you trust an MLE once it is defined? As , under regularity conditions, it is consistent (it converges to the true parameter; Wald, 1949) and asymptotically normal, with variance , where is the Fisher information carried by one observation. For a coin , so the standard error is about : with 70 heads in 100 flips, about . The Convergence lesson Asymptotics of Maximum Likelihood proves these results, and shows where they fail.
Computing MLEs, and the road ahead
Closed forms are the exception. For exponential families the likelihood equations reduce to matching averages of a few statistics; otherwise the negative log-likelihood is simply a loss to minimize numerically, by gradient methods, by Newton's method (iteratively reweighted least squares for generalized linear models), or by EM when some variables are unobserved (Latent Variables & EM). Optimizing over unconstrained transformed parameters, such as a log-scale, keeps positive quantities positive, and invariance means nothing is lost.
import numpy as np
from scipy import optimize, stats
x = np.random.default_rng(0).gamma(shape=2.0, scale=1.5, size=500) # positive data
def nll(params):
# optimize log(shape) and log(scale): both stay positive
shape, scale = np.exp(params)
return -stats.gamma.logpdf(x, a=shape, scale=scale).sum()
res = optimize.minimize(nll, x0=[0.0, np.log(x.mean())], method="L-BFGS-B")
shape_hat, scale_hat = np.exp(res.x) # invariance: transform back
# At the MLE the likelihood equation for the scale reads shape * scale = mean(x)
print(shape_hat * scale_hat, x.mean())A Gamma fit by numerical maximum likelihood. The two printed numbers agree up to the optimizer's tolerance: setting for the scale gives exactly, a first glimpse of moment matching in exponential families.
Key takeaways
- The likelihood is the probability of the data as a function of the parameters, not a distribution over them. The MLE maximizes it, usually through the log-likelihood, and is invariant to reparameterization.
- For a coin ; for a Gaussian and , biased by the factor ; for linear regression with Gaussian noise the MLE is least squares.
- Maximum likelihood minimizes the cross-entropy and the KL divergence ; squared error, absolute error and cross-entropy are negative log-likelihoods under matching noise models.
- MAP estimation adds the log-prior to the log-likelihood: a Gaussian prior gives ridge with , a Laplace prior the lasso with . Unlike the MLE, the MAP estimate depends on the parameterization.
- On small samples the MLE gives unseen outcomes probability zero; additive smoothing fixes it. As grows the MLE becomes consistent and approximately normal with variance .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
is computed from i.i.d. draws of . What is ?
- : the MLE is unbiased
- It depends on
Show the answer
B.
has expectation . Fitting to the same data uses up one observation's worth of variation.
Maximizing the likelihood of discrete data is equivalent to minimizing which quantity over ?
- , the KL from the empirical distribution to the model
- , the KL from the model to the data
- The entropy of the model,
- The squared distance between and the true parameter
Show the answer
A. , the KL from the empirical distribution to the model
, and the first term is constant. The expectation is taken under the data, which is why every observed point must get positive model probability.
Linear regression has Gaussian noise of variance and a prior . The MAP estimate minimizes with which ?
- It is the lasso, not ridge
Show the answer
C.
The negative log-posterior is ; multiplying by gives . Noisier data or a tighter prior both mean more shrinkage.
A naive Bayes spam filter is trained by maximum likelihood. The word "refund" never appeared in any legitimate training email. What happens to a new legitimate email that contains "refund"?
- Nothing unusual: one word has little effect on the total
- Its likelihood under "legitimate" is exactly zero, so the filter can never label it legitimate, whatever else it says
- The filter ignores words it has not seen with a class
- Its likelihood under "spam" becomes zero instead
Show the answer
B. Its likelihood under "legitimate" is exactly zero, so the filter can never label it legitimate, whatever else it says
Naive Bayes multiplies one estimated probability per word, and the MLE for "refund" given "legitimate" is . One zero factor wipes out all other evidence. Additive smoothing, , gives every word a small positive probability.
You change parameterization from to the log-odds , keeping the same data and the same prior beliefs (transformed correctly). Which estimates are guaranteed to describe the same distribution before and after?
- Both the MLE and the MAP estimate
- Neither: every estimate depends on the parameterization
- Only the MAP estimate
- Only the MLE
Show the answer
D. Only the MLE
The likelihood is a function of the distribution, so its maximizer just gets relabeled: . A prior density picks up a Jacobian factor when you change variables, so its peak, and the posterior's, can move to a different distribution. With a flat prior on and 3 heads in 3 flips, the MAP is in one parameterization and in the other.
Go deeper
- Asymptotics of Maximum Likelihood · Consistency, Fisher information and the Cramér–Rao bound.
- Exponential Families · Sufficient statistics, conjugacy and moment matching.
- When the Model Is Wrong · Misspecified likelihoods, KL projections and sandwich errors.
Further reading
- R. A. Fisher, "On the mathematical foundations of theoretical statistics," Philosophical Transactions of the Royal Society A 222, 309–368 (1922).
- G. Casella & R. L. Berger, Statistical Inference, 2nd ed. (Duxbury, 2002), chapter 7.
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), sections 1.2 and 2.3.
- R. Tibshirani, "Regression shrinkage and selection via the lasso," Journal of the Royal Statistical Society B 58(1), 267–288 (1996).