Maximum Likelihood and MAP Estimation
Suppose you observe the lifetimes of a hundred light bulbs. You want to predict how long the next one will last. You must pick a distribution family. Worse, you must pick specific numbers for its parameters. This all must come from finite noisy data alone. Maximum likelihood estimation (MLE) answers this by asking a deceptively simple question: which parameter values make the data you actually saw as probable as possible? This single principle underlies logistic regression, neural network training via cross-entropy loss, Gaussian mixture models, hidden Markov models, and much of classical statistics. MLE is the quiet engine behind almost every loss function in the formal learning problem, once you decide on a probabilistic model of your data. Minimizing squared error is MLE under Gaussian noise. Minimizing cross-entropy is MLE under a categorical model. Minimizing hinge-like surrogate losses often traces back to a likelihood argument in disguise. Understanding MLE means understanding why these losses look the way they do, not just how to code them. But MLE has a well-known failure mode. With little data or many parameters, it happily overfits. It assigns zero probability to anything unseen, and wild confidence to noise. Maximum a posteriori (MAP) estimation fixes this by folding in a prior belief over parameters. It then maximizes the resulting posterior instead. This turns out to be exactly regularization wearing a probabilistic disguise. A Gaussian prior gives ridge regression. A Laplace prior gives the lasso. This article builds MLE and MAP from first principles. It works through the algebra for concrete models. It gives pseudocode for the general optimization loop. It also traces the connection from priors to penalty terms. This way, "regularization strength" and "prior variance" become two names for the same knob.
- MLE picks parameters that maximize the probability (or density) of the observed data under the model.
- The log-likelihood turns products into sums, making optimization tractable via calculus or gradient methods.
- MAP maximizes the posterior , adding a prior term to the objective.
- A Gaussian prior on weights yields exactly the ridge (L2) penalty; a Laplace prior yields the lasso (L1) penalty.
- MLE is consistent and asymptotically efficient under regularity conditions, but can overfit badly in small-sample or high-dimensional regimes.
- MAP with a fixed prior is a point estimate, not full Bayesian inference — it ignores posterior uncertainty.
Maximum likelihood chooses parameters that best explain the data alone; MAP chooses parameters that best explain the data while respecting a prior belief, and that prior is mathematically identical to a regularizer.
The idea
Let data be drawn i.i.d. from a distribution with density or mass function , where is an unknown parameter vector. The likelihood function is the joint probability of the data viewed as a function of with the data held fixed:
The maximum likelihood estimator is
Because products of many small probabilities underflow numerically and are awkward to differentiate, one almost always works with the log-likelihood:
Since is strictly increasing, maximizing gives the same maximizer as maximizing . In practice one minimizes the negative log-likelihood (NLL), , turning estimation into a standard minimization problem compatible with gradient descent and other optimization machinery.
MAP estimation treats itself as random, with a prior density encoding belief before seeing data. Bayes' rule gives the posterior
since does not depend on . The MAP estimator maximizes this posterior:
Comparing the two objectives is the key insight: MAP is MLE plus an extra additive term . When is a zero-mean Gaussian, is (up to a constant) — the ridge penalty. When is a Laplace distribution, becomes — the lasso penalty. MAP is thus exactly regularized maximum likelihood, with the regularization strength determined by how concentrated the prior is around its mode.
How it works
Step 1 — choose a model family. Decide what distribution plausibly generated each data point: Bernoulli for binary labels, Gaussian for continuous noise, categorical/softmax for multi-class labels, Poisson for counts, and so on. This choice encodes assumptions and determines the eventual loss function.
Step 2 — write the log-likelihood. Expand using the chosen density.
Step 3 — optimize. For simple exponential-family models this can be done in closed form by setting and solving. For most realistic models (logistic regression, neural networks, mixture models) there is no closed form, and one uses iterative numerical optimization: gradient ascent on (equivalently, gradient descent on the NLL), Newton's method, or specialized algorithms like Expectation-Maximization for latent-variable models.
Step 4 (for MAP) — add the prior term. Augment the objective with before differentiating or before running gradient descent; this simply adds a penalty gradient to every update.
Step 5 — check second-order conditions. Verify (via the Hessian, or via convexity of the model class) that the stationary point found is indeed a maximum of the likelihood/posterior, not a saddle point or minimum — important for non-convex models like neural networks, where only local optima are guaranteed. ``` function FIT_MLE(data D = {x_1, ..., x_n}, model family p(x | theta), init theta_0): theta <- theta_0 repeat until convergence:
# negative log-likelihood and its gradient over the whole dataset g <- 0 # gradient accumulator, same shape as theta loss <- 0 for each x_i in D: loss <- loss - log p(x_i | theta) g <- g - grad_theta( log p(x_i | theta) ) theta <- theta - learning_rate g # gradient descent step on NLL return theta function FIT_MAP(data D, model family p(x | theta), prior p(theta), init theta_0): theta <- theta_0 repeat until convergence: g <- - grad_theta( log p(theta) ) # prior contributes a penalty gradient loss <- - log p(theta) for each x_i in D: loss <- loss - log p(x_i | theta) g <- g - grad_theta( log p(x_i | theta) ) theta <- theta - learning_rate g return theta ``` The two routines differ by exactly one term: the prior's negative log-density and its gradient. Everything else — the per-example likelihood gradient, the update rule, the convergence check — is identical. This is the precise sense in which "MAP equals regularized MLE."
Complexity & correctness
Time complexity. For a dataset of points and a parameter vector of dimension , evaluating the log-likelihood and its gradient once costs for most standard models (linear/logistic regression, Gaussians with diagonal covariance), since each of the terms contributes an gradient computation. If the model requires a full covariance matrix (multivariate Gaussian MLE), computing and inverting the covariance costs in addition to the needed to form it. Iterative optimization (gradient descent, Newton's method) multiplies the per-step cost by the number of iterations needed for convergence: total cost for gradient methods, or for Newton-type methods that use curvature. Closed-form MLEs (e.g., Gaussian mean and variance, or ordinary least squares via the normal equations) avoid the iteration factor entirely but may still pay for a matrix inversion or decomposition. Stochastic gradient variants reduce the per-step cost to per example at the price of noisier updates and more steps to convergence — a classical statistical-computational tradeoff.
Space complexity. Storing the data is ; storing the parameter vector and its gradient is ; methods that use second-order information (the Hessian) require space, which becomes prohibitive for large (e.g., deep networks), motivating first-order or quasi-Newton methods with limited memory.
Correctness of MLE — consistency. Under standard regularity conditions (identifiability of , the true parameter lying in the interior of , smoothness of ), the law of large numbers gives
The right-hand side, as a function of , is maximized uniquely at . This follows from Gibbs' inequality: for any two densities and ,
with equality iff almost everywhere — precisely the statement that the Kullback–Leibler divergence . So maximizing the empirical log-likelihood is, in the population limit, equivalent to minimizing over , whose unique minimizer is . Hence in probability: MLE is consistent. Under further regularity, is also asymptotically normal and efficient, achieving the Cramér–Rao lower bound on variance among (asymptotically) unbiased estimators as .
Correctness of MAP — Bayesian justification. MAP is exactly correct as the mode of the true posterior by construction of Bayes' rule; no approximation is introduced beyond dropping the normalizing constant , which does not affect the arg max. As , the likelihood term dominates a fixed prior (its curvature grows as while the prior's stays fixed), so — the prior's influence vanishes asymptotically, a fact sometimes called the Bernstein–von Mises phenomenon.
Honest tradeoffs.
- MLE can severely overfit when is small relative to : e.g., MLE variance estimates are biased low, and MLE for logistic regression with linearly separable data diverges to infinity.
- MAP requires choosing a prior family and a strength; a badly mismatched prior introduces bias that does not vanish for finite , and choosing it via the data itself risks circularity (partially addressed by hierarchical/empirical Bayes methods, outside this scope).
- MAP gives a single point estimate and, unlike full Bayesian posterior inference, does not quantify uncertainty about — it reports the mode, not the shape, of the posterior.
- For non-convex models (neural nets), neither MLE nor MAP is guaranteed to find the global optimum; gradient methods only guarantee convergence to a stationary point.
Worked example
Setup. You flip a possibly biased coin times and observe heads. Model each flip as Bernoulli(), being the probability of heads.
MLE derivation.
Differentiate and set to zero:
The second derivative confirms a maximum.
MAP derivation with a Beta prior. Suppose you believe the coin is probably close to fair and encode this as a prior on , with density . Take (a fairly strong "near 0.5" belief, equivalent to having pre-observed 4 heads and 4 tails). The posterior is
i.e. another Beta distribution (the Beta prior is conjugate to the Bernoulli likelihood). Its mode is
Interpretation table:
| Quantity | Value | Reading |
|---|---|---|
| Raw data estimate () | 0.800 | "80% heads, no prior belief" |
| Prior mode () | 0.500 | "I believed the coin was fair" |
| MAP estimate | 0.667 | Pulled from 0.8 toward 0.5 |
| MAP with weak prior (, uniform) | 0.800 | Uniform prior ⇒ MAP = MLE |
| MAP as (same ratio) | Prior's pull vanishes with more data |
This trace shows exactly how MAP behaves as advertised: with a flat (uniform) prior it collapses to MLE; with an informative prior it shrinks the estimate toward the prior mode, and that shrinkage weakens as the sample size grows — the hallmark of regularization. Note the pseudo-counts interpretation of the Beta prior: acts like extra observed heads and like extra observed tails, giving direct intuition for why pulls a small, unbalanced sample ( heads out of ) noticeably toward .
Connection to regularized linear regression (second case). For linear regression with , the Gaussian log-likelihood is
so MLE for is exactly ordinary least squares: minimizing . Now place a Gaussian prior . Then
and the MAP objective becomes
which is precisely ridge regression with regularization strength . A tighter prior (small , strong belief that weights are near zero) yields a larger — heavier shrinkage — exactly matching intuition.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting the constant / normalizer when comparing likelihoods across models with different parameter counts | Raw likelihood always increases (weakly) with more parameters | Use AIC/BIC or held-out validation, not raw likelihood, for model comparison |
| Treating MAP as "the" Bayesian answer | MAP is a single point (the mode), ignoring posterior spread/skew | Report the full posterior or credible intervals when uncertainty matters |
| Using an improper or accidentally informative "flat" prior | A prior that looks uninformative in one parameterization can be very informative in another (e.g., flat on vs. flat on ) | Choose priors thoughtfully in the parameterization that matches your actual belief |
| MLE diverging on separable data (logistic regression) | The likelihood keeps increasing as when classes are linearly separable | Add a prior/regularizer (MAP) or use early stopping |
| Confusing likelihood with probability of the parameter | is a function of for fixed data, not a probability distribution over — it need not integrate to 1 over | Remember Bayes' rule is what turns into a probability over , via the prior and normalization |
| Non-concave log-likelihoods (mixture models, neural nets) trapping gradient ascent in local maxima | The objective is genuinely non-convex | Use multiple restarts, better initialization, or EM-style algorithms suited to the structure |
Pioneers & history
Origins · 1 minRonald Aylmer Fisher and how this was discovered
Fisher formalized maximum likelihood estimation as a general principle in the 1920s, proving its consistency and asymptotic efficiency, and introduced the concept of Fisher information that underlies the Cramér–Rao bound. He worked simultaneously as a statistician and geneticist, developing the mathematical foundations of experimental design and analysis of variance while at Rothamsted Experimental Station, work that would later become indispensable to statistical machine learning.
Where this matters
Nearly every standard training loss in modern machine learning is a negative log-likelihood in disguise. Training a neural network classifier with cross-entropy loss is exactly MLE under a categorical/softmax output model. Training a regression network with mean squared error is MLE under a Gaussian noise assumption. Weight decay, ubiquitous in deep learning frameworks, is MAP estimation with a Gaussian prior on the weights — an L2 penalty added to the loss. Speech recognition systems historically relied on MLE-trained hidden Markov models; modern language models are trained by maximizing the likelihood of the next token given context. Spam filters, medical diagnosis models, and recommendation systems built on logistic regression or naive Bayes are direct applications of MLE/MAP to Bernoulli and categorical likelihoods. In computational biology, MLE fits population-genetic models to sequence data; in finance, MLE estimates volatility parameters in stochastic models. Bayesian deep learning and probabilistic programming languages (Stan, PyMC, Pyro) build directly on the MAP-as-regularized-MLE view before extending to full posterior approximation via variational inference or MCMC — topics that assume this article's ideas as their starting point.
Ask the tutor: How does maximum likelihood estimation extend to models with latent variables, like Gaussian mixtures, via the Expectation-Maximization algorithm?
Is MLE just a special case of MAP?
Yes — MLE is MAP with a uniform (flat) prior over the parameter space, so that is constant and contributes nothing to the arg max. More precisely, MLE is the limiting case of MAP as the prior's concentration around any particular value vanishes (infinite prior variance for a Gaussian prior, for instance). This is why the same optimization code can implement both: MAP training is MLE training with one extra penalty term added to the loss and its gradient. When people say "regularized maximum likelihood," they mean MAP.
Why does a Laplace prior give the L1 penalty and produce sparse solutions, while a Gaussian gives L2 and does not?
The Laplace density is , so , giving the L1 penalty directly in the MAP objective. The Laplace density has a sharp peak (non-differentiable point) at zero, which makes zero a genuinely attractive optimum for coordinates with weak signal, driving them to exactly zero — sparsity. The Gaussian density is smooth everywhere, including at zero, so its penalty has zero gradient at zero and merely shrinks weights toward zero without setting them there exactly.
Can MLE ever be a bad idea even with plenty of data?
With enough i.i.d. data and a well-specified, identifiable model, MLE is consistent and asymptotically efficient, so it is rarely "bad" asymptotically. Problems arise from model misspecification (the true data-generating process isn't in your model family, biasing the estimate no matter how much data you collect), from non-identifiability (multiple parameter values give the same likelihood, as in mixture model label-switching), and from computational issues in high dimensions (non-convex optimization landscapes in deep networks). In these cases more data doesn't fix the estimator; you need a better model, tighter identifiability constraints, or a different optimization strategy.
How is MAP different from full Bayesian inference?
MAP returns a single point — the mode (peak) of the posterior distribution — obtained by optimization. Full Bayesian inference characterizes the entire posterior distribution, capturing its spread, skewness, and any multimodality, typically via Markov Chain Monte Carlo sampling or variational approximation. MAP is much cheaper computationally (it's an optimization problem, not an integration problem) but throws away uncertainty information: two posteriors with the same mode but very different spreads give identical MAP estimates yet imply very different confidence in that estimate.
Why does MLE for logistic regression fail on linearly separable data?
If the training classes can be perfectly separated by a hyperplane, the logistic likelihood can be made arbitrarily close to 1 for every training point by scaling the weight vector toward infinity in the separating direction — the sigmoid outputs saturate toward 0 or 1 exactly where needed. The log-likelihood is monotonically increasing as with no finite maximizer, so gradient ascent on the unregularized likelihood diverges. Adding any strictly informative prior (equivalently, any regularization term like L2) makes the objective concave with a bounded maximizer, fixing the issue — a direct practical case where MAP is not just "nicer" but necessary.
Does the choice of prior in MAP estimation ever get overridden by enough data?
Yes, under the same regularity conditions that make MLE consistent. As grows, the log-likelihood's curvature around its maximum grows proportionally to (each data point contributes independent curvature), while the log-prior's curvature stays fixed. The posterior mode is therefore pulled increasingly toward the MLE, and the influence of the prior's exact shape asymptotically vanishes — a fact related to the Bernstein–von Mises theorem, which further shows the posterior itself becomes approximately Gaussian centered near the MLE for large .
What's a quick way to remember which prior gives which penalty?
Match the prior's negative log-density shape to the familiar penalty formula. Gaussian: , a smooth bowl, giving the L2/ridge penalty and pure shrinkage. Laplace: , a sharp V-shape, giving the L1/lasso penalty and sparsity-inducing shrinkage. Uniform/flat prior: is constant, contributing nothing, recovering plain MLE. In general, whenever you see a penalty term added to a loss function, ask "what prior, if any, has this as its negative log-density?" — that's the MAP interpretation of the penalty.