Maximum Likelihood Estimation
Instead of picking a loss function by taste, we can describe how the data was generated, with a probability model, and choose the parameters that make the observed data most probable. This is maximum likelihood estimation (MLE). It explains where common losses come from: squared loss is Gaussian likelihood, cross-entropy is categorical likelihood.
The likelihood
For independent examples with model , the likelihood of the parameters is the probability of the data as a function of :
Products of many small numbers underflow, and products are awkward to differentiate, so we minimize the negative log-likelihood (NLL) instead. The log turns the product into a sum, and its monotonicity keeps the same maximizer:
The NLL is an empirical risk with loss , so MLE is a special case of ERM.
Gaussian noise gives least squares
Model with . Then
The second term does not depend on , so minimizing the NLL is minimizing the sum of squared errors. Maximizing over as well gives , the mean squared residual.
import numpy as np
rng = np.random.default_rng(0)
N = 500
X = np.column_stack([np.ones(N), rng.uniform(0, 10, N)])
y = X @ np.array([3.0, 0.7]) + rng.normal(0, 1.5, N)
def nll(theta, s2):
r = y - X @ theta
return np.sum(r**2) / (2 * s2) + 0.5 * N * np.log(2 * np.pi * s2)
theta_ls = np.linalg.solve(X.T @ X, X.T @ y)
s2_ml = np.mean((y - X @ theta_ls) ** 2)
print("least squares theta:", np.round(theta_ls, 4), " ML sigma:", round(np.sqrt(s2_ml), 4))
# small perturbations of the ML estimate only increase the NLL
base = nll(theta_ls, s2_ml)
deltas = [nll(theta_ls + d, s2_ml) - base for d in rng.normal(scale=0.01, size=(5, 2))]
deltas += [nll(theta_ls, s2_ml * f) - base for f in (0.9, 1.1)]
print("NLL increases for every perturbation:", all(d > 0 for d in deltas))least squares theta: [2.8543 0.7081] ML sigma: 1.4041
NLL increases for every perturbation: True
Bernoulli labels give cross-entropy
For a binary label with (logistic regression),
the binary cross-entropy. For classes with softmax probabilities it is , the categorical cross-entropy used to train every classifier and language model.
import numpy as np
# MLE of a Bernoulli parameter: the sample frequency
data = np.array([1, 0, 1, 1, 0, 1, 1, 1, 0, 1])
mu = np.linspace(0.01, 0.99, 981)
nll = -(data.sum() * np.log(mu) + (len(data) - data.sum()) * np.log(1 - mu))
print("argmin of NLL:", round(mu[np.argmin(nll)], 3), " sample mean:", data.mean())argmin of NLL: 0.7 sample mean: 0.7
Properties and pitfalls
MLE is consistent (it converges to the true parameters as if the model is right) and asymptotically efficient. With little data it overfits: a coin that came up heads 3 times out of 3 gets , declaring tails impossible. Priors fix that (MAP Estimation and Regularization).
In software
nn.CrossEntropyLoss,nn.BCEWithLogitsLossandnn.GaussianNLLLossin PyTorch are negative log-likelihoods.LogisticRegressionin scikit-learn minimizes the Bernoulli NLL plus an penalty by default.- Language-model perplexity is the exponential of the average NLL per token (Perplexity).
Exercises
Exercise 1: MLE of a Poisson rate
Counts are modelled as Poisson() with . Find .
Answer
.
Solution
. Derivative: , so .
Exercise 2: Cross-entropy value
A classifier gives the true class probability for one example and for another. What is the total NLL (natural log)?
Answer
About .
Solution
. Confident mistakes are punished heavily.
Exercise 3: Underflow (code)
Multiply 2,000 likelihood terms of size directly, and sum their logs instead.
Answer
The product underflows to 0; the log-likelihood is about .
Solution
import numpy as np
p = np.full(2000, 0.6)
print(np.prod(p), round(np.sum(np.log(p)), 2))5e-324 -1021.65
Test yourself
Maximizing the likelihood of a linear model with Gaussian noise is equivalent to…
- minimizing absolute errors
- minimizing the sum of squared errors
- maximizing the number of correct predictions
- minimizing the hinge loss
Why do we minimize the negative log-likelihood instead of maximizing the likelihood directly?
- They have different optima
- The log turns products into sums, avoids underflow and simplifies gradients
- The likelihood is always negative
- It is required by NumPy
The MLE of a coin's bias after 3 heads in 3 flips is…
- 0.5
- 0.75
- 1
- undefined