TExcelTAD
Home › Math for Machine Learning › Maximum Likelihood Estimation

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 p(y∣x,θ)p(y \mid \mathbf{x}, \boldsymbol{\theta}), the likelihood of the parameters is the probability of the data as a function of θ\boldsymbol{\theta}:

L(θ)=∏n=1Np(yn∣xn,θ)\mathcal{L}(\boldsymbol{\theta}) = \prod_{n=1}^{N} p(y_n \mid \mathbf{x}_n, \boldsymbol{\theta})

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:

θML=arg⁡min⁡θ(−∑n=1Nlog⁡p(yn∣xn,θ))\boldsymbol{\theta}_{\text{ML}} = \arg\min_{\boldsymbol{\theta}} \left(-\sum_{n=1}^{N}\log p(y_n \mid \mathbf{x}_n, \boldsymbol{\theta})\right)

The NLL is an empirical risk with loss ℓ=−log⁡p(y∣x,θ)\ell = -\log p(y \mid \mathbf{x}, \boldsymbol{\theta}), so MLE is a special case of ERM.

Gaussian noise gives least squares

Model yn=θTxn+ϵny_n = \boldsymbol{\theta}^T\mathbf{x}_n + \epsilon_n with ϵn∼N(0,σ2)\epsilon_n \sim \mathcal{N}(0, \sigma^2). Then

−log⁡p(yn∣xn,θ)=(yn−θTxn)22σ2+12log⁡(2πσ2)-\log p(y_n \mid \mathbf{x}_n, \boldsymbol{\theta}) = \frac{(y_n - \boldsymbol{\theta}^T\mathbf{x}_n)^2}{2\sigma^2} + \frac{1}{2}\log(2\pi\sigma^2)

The second term does not depend on θ\boldsymbol{\theta}, so minimizing the NLL is minimizing the sum of squared errors. Maximizing over σ2\sigma^2 as well gives σML2=1N∑n(yn−θMLTxn)2\sigma^2_{\text{ML}} = \frac{1}{N}\sum_n (y_n - \boldsymbol{\theta}_{\text{ML}}^T\mathbf{x}_n)^2, the mean squared residual.

python · try it yourself
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 y∈{0,1}y \in \{0, 1\} with p(y=1∣x)=μ=σ(θTx)p(y = 1 \mid \mathbf{x}) = \mu = \sigma(\boldsymbol{\theta}^T\mathbf{x}) (logistic regression),

−log⁡p(y∣x,θ)=−(ylog⁡μ+(1−y)log⁡(1−μ))-\log p(y \mid \mathbf{x}, \boldsymbol{\theta}) = -\big(y\log\mu + (1 - y)\log(1 - \mu)\big)

the binary cross-entropy. For KK classes with softmax probabilities it is −log⁡py-\log p_{y}, the categorical cross-entropy used to train every classifier and language model.

python · try it yourself
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 N→∞N \to \infty 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 μML=1\mu_{\text{ML}} = 1, declaring tails impossible. Priors fix that (MAP Estimation and Regularization).

In software

  • nn.CrossEntropyLoss, nn.BCEWithLogitsLoss and nn.GaussianNLLLoss in PyTorch are negative log-likelihoods.
  • LogisticRegression in scikit-learn minimizes the Bernoulli NLL plus an ℓ2\ell_2 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 2,4,3,72, 4, 3, 7 are modelled as Poisson(λ\lambda) with p(k)=λke−λ/k!p(k) = \lambda^ke^{-\lambda}/k!. Find λML\lambda_{\text{ML}}.

Answer

λML=4\lambda_{\text{ML}} = 4.

Solution

−log⁡L=−∑n(knlog⁡λ−λ)+const-\log\mathcal{L} = -\sum_n (k_n\log\lambda - \lambda) + \text{const}. Derivative: −∑knλ+N=0-\frac{\sum k_n}{\lambda} + N = 0, so λ=∑knN=164=4\lambda = \frac{\sum k_n}{N} = \frac{16}{4} = 4.

Exercise 2: Cross-entropy value

A classifier gives the true class probability 0.80.8 for one example and 0.10.1 for another. What is the total NLL (natural log)?

Answer

About 2.5262.526.

Solution

−log⁡0.8−log⁡0.1=0.223+2.303=2.526-\log 0.8 - \log 0.1 = 0.223 + 2.303 = 2.526. Confident mistakes are punished heavily.

Exercise 3: Underflow (code)

Multiply 2,000 likelihood terms of size 0.60.6 directly, and sum their logs instead.

Answer

The product underflows to 0; the log-likelihood is about −1021.65-1021.65.

Solution
python · try it yourself
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…

  1. minimizing absolute errors
  2. minimizing the sum of squared errors
  3. maximizing the number of correct predictions
  4. minimizing the hinge loss

Why do we minimize the negative log-likelihood instead of maximizing the likelihood directly?

  1. They have different optima
  2. The log turns products into sums, avoids underflow and simplifies gradients
  3. The likelihood is always negative
  4. It is required by NumPy

The MLE of a coin's bias after 3 heads in 3 flips is…

  1. 0.5
  2. 0.75
  3. 1
  4. undefined