Mathematics and Statistics for AI Advanced 13 minutes

Maximum Likelihood Estimation and Loss Functions

Where do the mean squared error and cross-entropy losses come from? The answer: from maximum likelihood.

Your progress in the track0%

Idea

For independent data \(x_1, \dots, x_n\) and a model \(p(x \mid \theta)\):

$$\hat{\theta}_{MLE} = \arg\max_\theta \prod_{i=1}^n p(x_i \mid \theta) = \arg\min_\theta \; -\sum_{i=1}^n \log p(x_i \mid \theta)$$

From the assumption to the loss function

Assumption on the outputNegative log-likelihood
Gaussian around the predictionMean squared error (MSE)
Bernoulli with a sigmoid probabilityBinary cross-entropy
Categorical with softmax probabilitiesCategorical cross-entropy
Laplace around the predictionMean absolute error (MAE)

Binary cross-entropy

$$L = -\frac{1}{n}\sum_{i=1}^n \big[y_i \log \hat{p}_i + (1-y_i)\log(1-\hat{p}_i)\big]$$

From MLE to MAP

$$\hat{\theta}_{MAP} = \arg\max_\theta \; p(D \mid \theta)\, p(\theta)$$

  • A Gaussian prior \(\Rightarrow\) L2 regularization.
  • A Laplace prior \(\Rightarrow\) L1 regularization, which encourages zero parameters.
import numpy as np
y = np.array([1, 0, 1, 1])
p = np.array([0.9, 0.2, 0.6, 0.99])
bce = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
print(round(bce, 4))

In practice, cross-entropy is computed directly from the raw values (logits), as in torch.nn.CrossEntropyLoss, to avoid numerical precision errors with probabilities close to 0 or 1.

Lesson terms

Cross-entropy
A classification loss equal to the negative logarithm of the probability the model gave to the correct class.
MAP estimation
Maximizing the posterior probability of the parameters, that is, the likelihood multiplied by a prior distribution.
Maximum likelihood estimation
Choosing the parameter values that maximize the probability of the observed data under the model.

Abstract

Maximum likelihood estimation (MLE) chooses the parameters that make the observed data most probable. Maximizing the likelihood is equivalent to minimizing the negative log-likelihood. Assuming Gaussian noise we get the mean squared error, and assuming a Bernoulli or categorical distribution we get cross-entropy. Adding a prior distribution on the parameters gives the MAP estimate, which corresponds to regularization.

Review questions

  1. Why do we work with the log-likelihood instead of the likelihood itself?

    Because the logarithm turns a product into a sum, which makes differentiation easier and avoids the problem of very small numbers.

  2. Which prior distribution corresponds to L2 regularization?

    A Gaussian distribution centred at zero on the parameters.

Sources and references

  1. Deisenroth, Faisal & Ong — Mathematics for Machine Learning (Ch. 8)
  2. Goodfellow, Bengio & Courville — Deep Learning (Ch. 5.5)

Complete the lesson