Skip to content
AI360Xpert
Math

Maximum Likelihood Estimation

Pick the settings that make what you actually observed the least surprising thing that could have happened — which is, precisely, what training a model does.

After seeing seven heads in ten flips, every possible coin bias gets a score for how well it explains that result, and the estimate is simply whichever bias scores highest
After seeing seven heads in ten flips, every possible coin bias gets a score for how well it explains that result, and the estimate is simply whichever bias scores highest

Why Does This Exist?

Training a neural network is maximum likelihood estimation. Not an analogy — the same procedure, with a different function being optimised.

This is the page that turns a pile of separate-looking loss functions into one idea. Cross-entropy for classification, mean squared error for regression, the objective behind language model pretraining: all three are the negative log-likelihood of an assumed distribution, and all three are minimised by the same reasoning. Once you have this, you stop memorising which loss goes with which task and start deriving it.

The practical value is that it tells you what to do when your problem does not fit a standard loss. Predicting counts, or a value that must stay positive, or something with heavy tails? There is no lookup table entry for those — but there is a procedure. Write down the distribution you believe your data came from, take its negative log-likelihood, and you have your loss function. That is the whole method, and it is why L2 regularisation turns out to be a Gaussian prior rather than a trick someone found.

Think of It Like This

Working out which bag the marbles came from

Someone draws ten marbles from one of three bags and shows you the result: seven red and three blue. They will not say which bag.

Bag A is mostly blue, bag B is evenly mixed, bag C is mostly red. You reason about it immediately and without effort: bag A would rarely produce seven reds, bag B might occasionally, and bag C would do it often. So bag C is your answer.

That reasoning is maximum likelihood. You did not compute the probability that it is bag C — you compared how well each bag explains what you saw, and picked the best explanation.

The distinction matters more than it looks. You never asked how likely each bag was to be chosen in the first place. If you knew bag C was locked in a cupboard and rarely used, you might well change your answer, and that shift is what separates maximum likelihood from the Bayesian alternative. Plain maximum likelihood ignores prior plausibility entirely and looks only at fit.

How It Actually Works

Given observed data DD and a model with parameters θ\theta, the likelihood is the probability of the data under those parameters:

L(θ)=P(Dθ)L(\theta) = P(D \mid \theta)

In plain words: how probable is what I actually saw, if these parameter values were the truth? Read the direction carefully, because it is the part people get backwards. The data is fixed and known; θ\theta is what varies. The likelihood is a function of the parameters, not of the data.

For nn independent observations the joint probability is a product:

L(θ)=i=1nP(xiθ)L(\theta) = \prod_{i=1}^{n} P(x_i \mid \theta)

The estimate θ^\hat{\theta} is whichever θ\theta makes that largest.

Take the log, then negate

That product is unusable as written. A thousand probabilities each around 0.1 multiply to 10100010^{-1000}, which underflows to exactly zero in any float type — so the objective becomes flat zero everywhere and there is nothing to optimise.

Taking the logarithm turns the product into a sum:

logL(θ)=i=1nlogP(xiθ)\log L(\theta) = \sum_{i=1}^{n} \log P(x_i \mid \theta)

In plain words: add up the log-probability of every observation instead of multiplying the probabilities. This is safe because log\log is strictly increasing, so it never moves the location of the maximum — only its value. Sums of a thousand numbers around 2.3-2.3 are perfectly well-behaved.

Then negate, because optimisers minimise:

L(θ)=i=1nlogP(xiθ)\mathcal{L}(\theta) = -\sum_{i=1}^{n} \log P(x_i \mid \theta)

That is the negative log-likelihood, and it is your loss function. Every step here was mechanical — none of it involved choosing a loss.

Where the standard losses come from

Now run the procedure on each of the three common assumptions:

  • Categorical (multi-class classification). P(yixi,θ)P(y_i \mid x_i, \theta) is the softmax probability of the true class, so the negative log-likelihood is logy^i,true-\sum \log \hat{y}_{i,\text{true}} — exactly cross-entropy loss.
  • Bernoulli (binary classification). The negative log-likelihood is [ylogy^+(1y)log(1y^)]-\sum [y \log \hat{y} + (1-y)\log(1-\hat{y})] — binary cross-entropy, term for term.
  • Gaussian with fixed variance (regression). The Gaussian density has e(yy^)2/2σ2e^{-(y-\hat{y})^2 / 2\sigma^2} in it, so its log is (yy^)2/2σ2-(y - \hat{y})^2 / 2\sigma^2 plus a constant. Negate and the constants drop out under optimisation, leaving (yy^)2\sum (y - \hat{y})^2mean squared error.

That last one is worth pausing on. MSE squares its errors because the Gaussian has a square in its exponent. Not for convenience, not because it is differentiable — because of the distribution you assumed. Swap in a Laplace distribution and the same procedure gives you mean absolute error, which is more tolerant of outliers precisely because the Laplace has fatter tails.

Adding a prior gives you regularisation

Maximum likelihood asks only which θ\theta best explains the data, which means it will happily choose extreme parameter values if they fit slightly better. That is overfitting, stated in probabilistic terms.

Bayes' theorem offers the fix. Instead of maximising P(Dθ)P(D \mid \theta), maximise P(θD)P(Dθ)P(θ)P(\theta \mid D) \propto P(D \mid \theta) P(\theta), where P(θ)P(\theta) encodes what you believed about the parameters beforehand. This is MAP estimation, and taking logs turns the product into a sum:

L(θ)=logP(Dθ)logP(θ)\mathcal{L}(\theta) = -\log P(D \mid \theta) - \log P(\theta)

In plain words: your usual loss, plus a penalty for parameter values you considered implausible to begin with. Assume a zero-centred Gaussian prior on the weights and logP(θ)-\log P(\theta) works out to λθ22\lambda \lVert \theta \rVert_2^2L2 regularisation is a Gaussian prior. Assume a Laplace prior instead and you get λθ1\lambda \lVert \theta \rVert_1, which is L1, and its sparsity is the Laplace distribution's spike at zero showing through. See norms for the geometry of why that spike produces exact zeros.

Worked example

Flip a coin ten times and get seven heads. What is the coin's probability of heads?

With pp as the unknown, each head contributes a factor of pp and each tail a factor of (1p)(1-p):

L(p)=p7(1p)3L(p) = p^7 (1-p)^3

In plain words: how likely is seven heads and three tails, if the coin's true bias were pp? That is the curve in the diagram above. Take the log:

logL(p)=7logp+3log(1p)\log L(p) = 7 \log p + 3 \log(1-p)

The maximum is where the derivative is zero:

ddplogL=7p31p=0\frac{d}{dp} \log L = \frac{7}{p} - \frac{3}{1-p} = 0

Multiply through by p(1p)p(1-p) to get 7(1p)=3p7(1-p) = 3p, so 7=10p7 = 10p and:

p^=0.7\hat{p} = 0.7

The answer is the observed proportion, which is reassuring — but notice it was derived, not assumed. That same derivation on a Gaussian returns the sample mean, and on a categorical returns the observed class frequencies. Maximum likelihood recovers the obvious estimator when the obvious estimator is right, and tells you what to do when it is not.

Worth seeing the failure case too: ten heads out of ten gives p^=1.0\hat{p} = 1.0, meaning the model declares tails impossible on ten observations. That is maximum likelihood being overconfident with small data, and it is exactly what a prior fixes.

Show Me the Code

import numpy as np

def neg_log_likelihood(p: float, heads: int, tails: int) -> float:    # Sum of log-probabilities, never a product — the product underflows.    return -(heads * np.log(p) + tails * np.log(1 - p))

grid = np.linspace(0.01, 0.99, 99)                       # candidate values of pnll = np.array([neg_log_likelihood(p, 7, 3) for p in grid])print(round(float(grid[nll.argmin()]), 2))               # -> 0.7   matches 7/10
# Why the log is not optional: 1000 observations as a raw product.print(np.prod(np.full(1000, 0.1)))                       # -> 0.0    underflowedprint(np.sum(np.log(np.full(1000, 0.1))))                # -> -2302.58...  fine

The grid search lands on 0.70, matching the calculus. The last two lines are the reason every implementation works in log space.

Watch Out For

Reading the likelihood backwards

P(Dθ)P(D \mid \theta) and P(θD)P(\theta \mid D) are different quantities, and swapping them is the most common conceptual error here.

The likelihood is the probability of the data given the parameters. It is not the probability that the parameters are correct. A maximum likelihood estimate of p^=0.7\hat{p} = 0.7 does not mean there is a 70% chance the coin is fair, or a high probability that 0.7 is the true bias — it means 0.7 explains the observed flips better than any other value does.

The consequence is concrete: a likelihood is not a probability distribution over θ\theta and does not integrate to 1 over θ\theta. You cannot read a confidence interval off it directly, and you cannot compare likelihoods computed on different datasets — only different parameters on the same data. Model comparison metrics like AIC exist precisely because raw likelihoods are not comparable across models with different numbers of parameters.

Turning a likelihood into a genuine belief about θ\theta requires a prior and Bayes' theorem. That is the difference between MLE and MAP, and it is not a formality.

Maximum likelihood assigning probability zero to the unseen

Maximum likelihood fits what it saw and only what it saw, so anything absent from the training data gets a probability of exactly zero — and zero probabilities are catastrophic rather than merely wrong.

The classic case is a naive Bayes text classifier. A word that never appeared with a given class gets P(wordclass)=0P(\text{word} \mid \text{class}) = 0, and because the model multiplies probabilities, that single zero drives the entire document's probability to zero regardless of how much other evidence points that way. One unseen word overrides everything.

In log space the same failure appears as -\infty, which then produces nan on the backward pass. The ten-heads-out-of-ten coin is the minimal example: p^=1\hat{p} = 1 makes the next tail infinitely surprising.

The fix is always the same shape — add a prior. Laplace smoothing (add one to every count) is the direct form, weight decay is the continuous form, and label smoothing is the version applied to targets. All three are MAP estimation with a prior that refuses to let any probability reach exactly zero. If a model produces inf or nan on data that merely looks unusual, this is the first thing to check.

The Quick Version

  • Maximum likelihood picks the parameters under which the observed data is least surprising.
  • The likelihood P(Dθ)P(D \mid \theta) is a function of the parameters; the data is fixed.
  • Products of many probabilities underflow, so always work with the log — it is monotone, so the maximum does not move.
  • Negate the log-likelihood and you have your loss function. That is where losses come from.
  • Categorical assumption gives cross-entropy. Bernoulli gives binary cross-entropy. Gaussian gives MSE.
  • MSE squares errors because the Gaussian squares in its exponent. Laplace instead gives mean absolute error.
  • Multiplying in a prior gives MAP: L2 regularisation is a Gaussian prior, L1 is a Laplace prior.
  • P(Dθ)P(D \mid \theta) is not P(θD)P(\theta \mid D). A likelihood is not a belief about the parameters.
  • MLE assigns probability zero to anything unseen, which becomes -\infty in log space. Smoothing is a prior.

Related concepts