TExcelTAD
Home › Math for Deep Learning & LLMs › Maximum Likelihood and Cross-Entropy

Maximum Likelihood and Cross-Entropy Loss

Why mean squared error for regression and cross-entropy for classification? Because both are the same principle, maximum likelihood, applied to different output distributions. Seeing a loss as a negative log-likelihood tells you which loss to use for a new kind of output and what the network's outputs mean. The general theory is in Maximum Likelihood Estimation.

The principle

A network with parameters θ\boldsymbol{\theta} defines a conditional distribution p(y∣x;θ)p(y \mid \mathbf{x}; \boldsymbol{\theta}). Maximum likelihood picks the parameters that make the observed labels most probable, which, after taking logs and averaging, means minimizing the negative log-likelihood:

L(θ)=−1n∑i=1nlog⁡p(yi∣xi;θ)\mathcal{L}(\boldsymbol{\theta}) = -\frac{1}{n}\sum_{i=1}^{n}\log p(y_i \mid \mathbf{x}_i; \boldsymbol{\theta})

This is the cross-entropy between the empirical data distribution and the model (Entropy and KL).

Three outputs, three losses

Gaussian output, MSE. If p(y∣x)=N(y;f(x),σ2)p(y \mid \mathbf{x}) = \mathcal{N}(y; f(\mathbf{x}), \sigma^2) with fixed σ\sigma, then −log⁡p=(y−f(x))22σ2+const-\log p = \frac{(y - f(\mathbf{x}))^2}{2\sigma^2} + \text{const}: minimizing the NLL is minimizing the squared error.

Bernoulli output, binary cross-entropy. With μ=σ(z)\mu = \sigma(z), −log⁡p(y)=−ylog⁡μ−(1−y)log⁡(1−μ)-\log p(y) = -y\log\mu - (1 - y)\log(1 - \mu).

Categorical output, cross-entropy. With p=softmax⁡(z)\mathbf{p} = \operatorname{softmax}(\mathbf{z}), −log⁡p(y)=−log⁡py=LSE⁡(z)−zy-\log p(y) = -\log p_y = \operatorname{LSE}(\mathbf{z}) - z_y.

python · try it yourself
import numpy as np

y, f, sigma = 2.5, 2.0, 1.0
nll = 0.5 * np.log(2 * np.pi * sigma**2) + (y - f)**2 / (2 * sigma**2)
print(f"Gaussian NLL {nll:.4f} = squared error/2 {(y - f)**2 / 2:.4f} + const {0.5 * np.log(2 * np.pi):.4f}")
z, label = 1.2, 1
mu = 1 / (1 + np.exp(-z))
print(f"binary CE: {-(label * np.log(mu) + (1 - label) * np.log(1 - mu)):.4f}")
logits, k = np.array([2.0, 0.5, -1.0]), 0
lse = logits.max() + np.log(np.sum(np.exp(logits - logits.max())))
print(f"categorical CE: {lse - logits[k]:.4f}")
Gaussian NLL 1.0439 = squared error/2 0.1250 + const 0.9189
binary CE: 0.2633
categorical CE: 0.2413

Why not MSE for classification?

With a sigmoid output and MSE loss, the gradient with respect to the logit is (μ−y) μ(1−μ)(\mu - y)\,\mu(1 - \mu). When the network is confidently wrong (μ≈0\mu \approx 0, y=1y = 1), the factor μ(1−μ)\mu(1 - \mu) is nearly 0 and learning stalls. The cross-entropy gradient is simply μ−y\mu - y: the log cancels the saturation of the sigmoid exactly.

python · try it yourself
import numpy as np

y = 1.0
for z in (-8.0, -2.0, 0.0, 2.0):
    mu = 1 / (1 + np.exp(-z))
    g_mse = (mu - y) * mu * (1 - mu)
    g_ce = mu - y
    print(f"logit {z:+.0f}: mu {mu:.4f}  dMSE/dz {g_mse:+.5f}  dCE/dz {g_ce:+.4f}")
logit -8: mu 0.0003  dMSE/dz -0.00034  dCE/dz -0.9997
logit -2: mu 0.1192  dMSE/dz -0.09248  dCE/dz -0.8808
logit +0: mu 0.5000  dMSE/dz -0.12500  dCE/dz -0.5000
logit +2: mu 0.8808  dMSE/dz -0.01252  dCE/dz -0.1192

At logit −8-8 the model is badly wrong, yet the MSE gradient is about −0.0003-0.0003; the cross-entropy gradient is about −1-1.

Learning the variance too

A regression network can output both μ(x)\mu(\mathbf{x}) and s(x)=log⁡σ2(x)s(\mathbf{x}) = \log\sigma^2(\mathbf{x}) and minimize the full Gaussian NLL 12(s+(y−μ)2es)\frac{1}{2}\left(s + \frac{(y - \mu)^2}{e^s}\right). It then learns where its predictions are uncertain (heteroscedastic regression). Predicting the log-variance keeps σ2>0\sigma^2 > 0 automatically.

In software

  • nn.MSELoss, nn.BCEWithLogitsLoss, nn.CrossEntropyLoss and nn.GaussianNLLLoss are the four negative log-likelihoods above.
  • Label smoothing replaces the one-hot target by (1−ε)(1 - \varepsilon) on the true class and ε/K\varepsilon/K elsewhere, discouraging overconfident logits.
  • LLM pre-training minimizes exactly the categorical NLL of the next token (Language Modeling).

Exercises

Exercise 1: Laplace noise

If p(y∣x)p(y \mid \mathbf{x}) is a Laplace distribution 12be−∣y−f(x)∣/b\frac{1}{2b}e^{-\lvert y - f(\mathbf{x}) \rvert/b}, which loss does maximum likelihood give?

Answer

The mean absolute error ∣y−f(x)∣\lvert y - f(\mathbf{x}) \rvert.

Solution

−log⁡p=∣y−f(x)∣b+log⁡2b-\log p = \frac{\lvert y - f(\mathbf{x}) \rvert}{b} + \log 2b; with bb fixed, minimizing the NLL minimizes the absolute error.

Exercise 2: Cross-entropy gradient

Show that ∂∂z[−ylog⁡σ(z)−(1−y)log⁡(1−σ(z))]=σ(z)−y\frac{\partial}{\partial z}\left[-y\log\sigma(z) - (1 - y)\log(1 - \sigma(z))\right] = \sigma(z) - y.

Answer

Use σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)).

Solution
−yσ(1−σ)σ+(1−y)σ(1−σ)1−σ=−y(1−σ)+(1−y)σ=σ−y-y\frac{\sigma(1 - \sigma)}{\sigma} + (1 - y)\frac{\sigma(1 - \sigma)}{1 - \sigma} = -y(1 - \sigma) + (1 - y)\sigma = \sigma - y

Exercise 3: Uniform guessing (code)

What is the cross-entropy of a classifier that outputs the uniform distribution over 10 classes? Check with code.

Answer

ln⁡10≈2.3026\ln 10 \approx 2.3026.

Solution

Every class gets 0.10.1, so the loss is −ln⁡0.1-\ln 0.1 for every example. An untrained network should start near this value; a much larger initial loss signals badly scaled logits.

python · try it yourself
import numpy as np
logits = np.zeros(10)
print(round(np.log(np.sum(np.exp(logits))) - logits[3], 4))
2.3026

Test yourself

Minimizing mean squared error is maximum likelihood under which noise model?

  1. Laplace
  2. Gaussian with fixed variance
  3. Bernoulli
  4. Uniform

For a sigmoid output, why is cross-entropy preferred over MSE?

  1. It is cheaper
  2. Its gradient σ(z)−y\sigma(z) - y does not vanish when the model is confidently wrong
  3. MSE cannot be differentiated
  4. Cross-entropy is always smaller

The expected initial loss of a well-initialized 1000-class classifier is about…

  1. 0
  2. 1
  3. ln⁡1000≈6.9\ln 1000 \approx 6.9
  4. 1000