Loss Functions and Maximum Likelihood: Deriving MSE, BCE and Cross-Entropy and Comparing Them on MNIST

Sunhong··16 min read·0 views·Translated from Korean

Key points of this post

  • A loss function is not an arbitrary formula. You assume the model's output follows some probability distribution, and finding the values that make the observed data most probable (maximum likelihood) is exactly loss minimization. A Gaussian gives MSE, a Bernoulli gives BCE, a categorical gives cross-entropy.
  • The reason to prefer cross-entropy over MSE for classification is the gradient. When the model is confidently wrong, the cross-entropy gradient stays large while the MSE gradient almost vanishes. Measured with an output layer initialized 20x too large, the logit gradient norm on the 4,470 "confidently wrong" samples (out of 10,000) was 1.41 for cross-entropy and 0.0042 for MSE on probabilities (about 340x apart).
  • With sane initialization, though, the choice of loss made little difference on MNIST (95 to 97% after 5 epochs). Where the loss gives the output its meaning shows up in regression that also learns the variance: the error of the predicted noise level was 0.078 with a constant sigma and 0.0053 when trained with the Gaussian NLL.

This is the third post in the AI Note series. In part 1 we introduced the loss as "how far the output is from the answer" and used squared error and cross-entropy, and in part 2 we saw that combining softmax with cross-entropy simplifies the gradient to "probability minus answer". But why squared error for regression and cross-entropy for classification? If we chose them only because the formulas looked reasonable, we would have no way to pick a loss for a new problem. This post gives that choice a foundation. We grasp maximum likelihood with coin tosses, see MSE, BCE and cross-entropy come out of one line of reasoning, and then run experiments to find where the difference actually shows.

1. Read the model output as a probability

A neural network takes an input xx and emits numbers. So far we read those numbers directly as the prediction. We can step back and read them differently: the output is the parameter of the probability distribution that the answer yy follows. For regression it says "the answer is spread around the μ\mu I output", and for classification "the probability of each class is this vector".

Read this way, "is the model good?" becomes a single question: under the distribution the model gives, how probable is the data we actually observed? That probability is called the likelihood. The larger the likelihood, the better the model explains the data. So choosing the parameters that maximize it, maximum likelihood estimation, becomes the principle of learning.

2. Maximum likelihood with coin tosses

The smallest example. We toss a coin with unknown heads probability pp ten times and get 7 heads and 3 tails. If the tosses are independent, the probability of this outcome (the likelihood) is

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

(the order in which they came is only a constant factor, so we ignore it). Let us evaluate it for a few values of pp.

pp 0.3 0.5 0.7 0.9
L(p)L(p) 0.0000750 0.000977 0.002224 0.000478

It is largest at p=0.7p = 0.7. Scanning the whole grid (step 0.01) also puts the maximum at 0.7. That is the common-sense answer, "the fraction of heads". Maximum likelihood generalizes that common sense.

The likelihood is a product, which is awkward. With NN data points we multiply NN probabilities, and for example 400 events of probability 0.1 multiply to 10−40010^{-400}, which is outside the range of 64-bit floating point (about 10−30810^{-308}). So we take the logarithm. The log is increasing, so it does not move the location of the maximum, and it turns products into sums. Minimizing is more familiar than maximizing, so we flip the sign.

loss=−log⁡L=−∑i=1Nlog⁡P(yi∣xi; θ)\text{loss} = -\log L = -\sum_{i=1}^{N} \log P(y_i \mid x_i;\ \theta)

This is the negative log-likelihood (NLL). In words: "for each sample, take the log of the probability the model gave to the correct answer, flip the sign, and add them up". The more probability the model gives the answer, the closer −log⁡-\log is to 0, and the less it gives, the faster the value grows. This one line is the core of this post. From here, the loss is determined by which distribution we let the model output. The figure below is the map.

Once the output distribution is chosen, the negative log-likelihood fixes the loss: Gaussian gives MSE, Laplace gives MAE, Bernoulli gives BCE, categorical gives cross-entropy

3. A Gaussian gives MSE

In regression, suppose the answer is y=μ(x)+noisey = \mu(x) + \text{noise} with Gaussian (normal) noise. If the model outputs the mean μ\mu and the standard deviation σ\sigma is fixed, then

P(y∣x)=12πσ2exp⁡ ⁣(−(y−μ)22σ2),−log⁡P=(y−μ)22σ2+constP(y \mid x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left(-\frac{(y-\mu)^2}{2\sigma^2}\right), \qquad -\log P = \frac{(y-\mu)^2}{2\sigma^2} + \text{const}

In words: the further the answer is from μ\mu, the faster the probability falls off in a bell shape, and the negative log of that is "distance squared". With σ\sigma fixed, the constant and 1/2σ21/2\sigma^2 do not affect the minimization, so what remains is (y−μ)2(y-\mu)^2, the mean squared error (MSE). The squared error we used in part 1 was hiding the assumption "the noise is Gaussian".

Let us check with small numbers. For three samples with answers y=1, 2, 4y = 1,\ 2,\ 4, answering with one constant μ\mu, the sum of squared errors (SSE) and the sum of absolute errors (SAD) are:

μ\mu 1 2 7/3 ≈ 2.33 3
SSE = ∑(y−μ)2\sum (y-\mu)^2 10 5 4.67 6
SAD = ∑∣y−μ∣\sum \lvert y-\mu \rvert 4 3 3.33 4

SSE is smallest at the mean 2.33 and SAD at the median 2. Assuming Gaussian noise, the mean is the answer; assuming a Laplace distribution (heavier tails, −log⁡P∝∣y−μ∣/b-\log P \propto |y-\mu|/b), the median is the answer. A single outlier shows the difference. Change the third value from 4 to 40 and the mean is dragged to 14.3 while the median stays 2. The claim that MAE is robust on data with many outliers comes from this difference. Which loss is good depends on what the noise looks like.

Learning the variance as well

If we do not fix σ\sigma and let the model output it too, the log⁡σ\log \sigma term of the NLL comes alive.

−log⁡P=log⁡σ+(y−μ)22σ2+const-\log P = \log \sigma + \frac{(y-\mu)^2}{2\sigma^2} + \text{const}

Take an error of 1 and vary σ\sigma. For σ=0.5\sigma = 0.5 it is log⁡0.5+1/(2×0.25)=1.307\log 0.5 + 1/(2 \times 0.25) = 1.307, for σ=1\sigma = 1 it is 0+0.5=0.50 + 0.5 = 0.5, and for σ=2\sigma = 2 it is 0.693+0.125=0.8180.693 + 0.125 = 0.818. The minimum is at a σ\sigma equal to the error. If σ\sigma is too small the squared term punishes, and if it is too large the log⁡σ\log \sigma term punishes. So the model learns on its own "at this input, my prediction wobbles about this much". We check it in the experiment below.

4. Bernoulli gives BCE, categorical gives cross-entropy

Binary classification. The answer is 0 or 1, and the model outputs "the probability of 1" as p=σ(z)p = \sigma(z) (sigmoid). The likelihood is pp if the answer is 1 and 1−p1-p if 0, which in one line is py(1−p)1−yp^y (1-p)^{1-y}, so

−log⁡P=−ylog⁡p−(1−y)log⁡(1−p)-\log P = -y \log p - (1-y) \log (1-p)

This is binary cross-entropy (BCE). If the answer is 1 only −log⁡p-\log p remains, and if 0 only −log⁡(1−p)-\log(1-p).

Many classes. From the probability vector softmax outputs, we only look at the probability of the correct class: −log⁡P=−log⁡py-\log P = -\log p_y. In the three-class example of part 1, the scores (logits) (2.0, 1.0, 0.1)(2.0,\ 1.0,\ 0.1) give softmax probabilities (0.659, 0.242, 0.099)(0.659,\ 0.242,\ 0.099).

Correct class Probability given to it Loss −ln⁡py-\ln p_y
class 0 0.659 0.417
class 1 0.242 1.419
class 2 0.099 2.313

The smaller the probability given to the answer, the more steeply the loss grows. With these scores the model always picks class 0, so by accuracy only the first case is right, but cross-entropy turns how much probability it put on the answer into a value. Accuracy only counts right or wrong, so it cannot tell a 0.99 hit from a 0.34 narrow hit.

Let us also explain the name. The cross-entropy of two distributions qq (the answer) and pp (the model) is H(q,p)=−∑kqklog⁡pkH(q, p) = -\sum_k q_k \log p_k. If the answer is one-hot, qy=1q_y = 1 and the rest are 0, so only −log⁡py-\log p_y remains, exactly the formula above. Cross-entropy is the entropy of qq plus the KL divergence (how different two distributions are), and the entropy of a one-hot is 0, so in the end it equals "reducing the KL divergence between the answer distribution and the model distribution". Maximum likelihood, cross-entropy minimization and KL minimization are different names for the same thing.

The gradient ∂L/∂zk=pk−1[k=y]\partial L / \partial z_k = p_k - \mathbb{1}[k=y] derived in part 2 follows the same thread. For binary classification, differentiating BCE with respect to the sigmoid input zz also gives p−yp - y. It is always "prediction minus answer". This neatness is not an accident: differentiating the NLL of an exponential-family distribution with respect to its natural parameter always gives this (the canonical link of GLMs). Even outputting the mean of a Gaussian directly gives the same form, ∂L/∂μ=(μ−y)/σ2\partial L/\partial \mu = (\mu - y)/\sigma^2.

5. Why MSE is a worse fit for classification

Then why not use MSE for classification too? A model using MSE on probabilities also runs fine. The problem is the shape of the gradient. In binary classification, let the answer be y=1y = 1 and the model output the probability p=σ(z)p = \sigma(z) from the logit zz. Differentiating the two losses with respect to zz:

BCE: ∂L∂z=p−1,MSE: L=(p−1)2  ⇒  ∂L∂z=2(p−1)⋅p(1−p)\text{BCE: } \frac{\partial L}{\partial z} = p - 1, \qquad \text{MSE: } L=(p-1)^2 \;\Rightarrow\; \frac{\partial L}{\partial z} = 2(p-1) \cdot p(1-p)

The MSE version is multiplied by the sigmoid derivative p(1−p)p(1-p). When pp sits near 0 or 1, this is almost 0. Take the case where the answer should be 1 but the model is confidently wrong with z=−6z = -6 (p=0.0025p = 0.0025).

Logit zz pp BCE gradient MSE gradient
−6 (confidently wrong) 0.0025 −0.9975 −0.0049
−3 0.047 −0.953 −0.086
0 0.5 −0.5 −0.25
3 (right) 0.953 −0.047 −0.0043

At the most wrong z=−6z = -6, BCE shouts "raise it a lot" at nearly maximum size, while MSE is 0.0049, about 1/200 of that. The loss value does the opposite: the more wrong, the larger the loss, yet there is a region where the gradient shrinks. A picture makes it clearer.

Gradient size versus logit z. With answer 1, BCE approaches size 1 as z gets more negative, while sigmoid+MSE is 0.0049 at z = -6, about 1/200 of BCE

On the confidently wrong side, the BCE gradient saturates at 1 (stays constant) while the MSE gradient vanishes to 0. The log exactly cancels the saturation of the sigmoid. The same happens with multi-class softmax.

6. Running it

Correctness check

First we verified that the gradient p−yp - y is right. With 4 classes and 5 samples, we compared PyTorch's F.cross_entropy (autograd), our formula (p−one-hot)/B(p - \text{one-hot})/B, and a hand-written numerical derivative (central difference, ϵ=10−6\epsilon = 10^{-6}).

Comparison Max difference
Loss: mean of −log⁡py-\log p_y vs F.cross_entropy 0
Gradient: (p−y)/B(p - y)/B vs autograd 2.8×10−172.8 \times 10^{-17}
Gradient: (p−y)/B(p - y)/B vs numerical derivative 2.1×10−102.1 \times 10^{-10}

The formula and the library agree within floating-point error.

Gradients from a confidently wrong start

Take the 784-128-10 network (ReLU, He initialization) we have been using, and multiply the output-layer weights by 20 at the start. The logits are large, so the model is strongly sure of one class from the beginning. Initial accuracy was 10.7% (chance level), and among the first 10,000 training images 4,470 were "over 99% sure of a class that is not the answer". The mean logit-gradient size (vector norm) for these samples was

Loss Logit gradient size for confidently wrong samples
Cross-entropy 1.413
MSE on probabilities (after softmax) 0.0042

about 340x apart. The calculation of section 5 shows up as is in a real network.

Three losses on MNIST

Same network, same data (60,000 MNIST images), same SGD (batch 64); only the loss changes, trained for 5 epochs. We compared (a) cross-entropy, (b) MSE between softmax probabilities and one-hot, (c) MSE between logits and one-hot. Initialization was either normal (He) or output layer x20, with learning rates 0.1 and 1.0, averaged over 3 seeds.

Test accuracy after 5 epochs by loss, initialization and learning rate. With normal init and learning rate 0.1: cross-entropy 96.7%, MSE on probabilities 95.4%, MSE on logits 95.2%. With output layer x20 init and learning rate 1.0: cross-entropy 53.5%, MSE on probabilities 21.7%, MSE on logits 10.3%

To be honest, the result is not "cross-entropy wins by a landslide".

  • With normal initialization the differences are small. At learning rate 0.1 it is cross-entropy 96.7%, MSE on probabilities 95.4%, MSE on logits 95.2%. At learning rate 1.0, MSE on probabilities gets 97.1%, higher than cross-entropy (96.3%). With only 3 seeds we cannot call that difference meaningful.
  • With the output layer x20, cross-entropy leads from the first epoch. At learning rate 0.1, the 1-epoch accuracy is 91.4% for cross-entropy and 86.1% for MSE on probabilities (after 5 epochs, MSE caught up, 94.0% vs 95.0%). At learning rate 1.0, cross-entropy learns, shakily, to 53.5%, while MSE on probabilities stays at 21.7%.
  • MSE on logits is sensitive to the learning rate. At 0.1 it does well at 95.2%, but at 1.0 it collapsed to around 10% in every setting. The output is not squashed into probabilities, so a large learning rate makes it diverge.

In short, the advantage of cross-entropy is not "always more accurate" but the gradient stays alive even with bad initialization or learning rate. The 340x gap seen in section 5 shows up as learning speed, especially in the first epoch. On a problem this small, other losses somehow hold up too.

Regression that learns the variance

Let us look at the variance learning mentioned in section 3. We generated 2,000 points with y=sin⁡(2πx)+εy = \sin(2\pi x) + \varepsilon, with a noise standard deviation that grows with xx (σ(x)=0.05+0.3x\sigma(x) = 0.05 + 0.3x). A neural network (1-64-64-2, tanh) outputs two values, the mean μ(x)\mu(x) and log⁡σ(x)\log \sigma(x), trained with the Gaussian NLL for 4,000 Adam steps. The baseline is the same architecture outputting only the mean, trained with MSE. This model does not know the variance, so we substituted one number, the standard deviation of the residuals (0.217).

The mean and ±2 sigma band from the model trained with Gaussian NLL (blue) overlap the true mean and ±2 sigma band (dashed). The band widens as the points spread out with larger x

Metric NLL (learn μ and σ) MSE (mean only)
Mean error of the predicted mean ∣μ^−μ∣\lvert \hat\mu - \mu \rvert 0.0117 0.0096
Mean error of the predicted noise level ∣σ^−σ∣\lvert \hat\sigma - \sigma \rvert 0.0053 0.078 (constant σ=0.217)

The MSE model predicted the mean slightly better (0.0096 vs 0.0117; with one seed we cannot rank them). But on top of the mean, the NLL model says "the further right, the less reliable" about 15x more accurately. We only changed the loss to NLL in the same network structure. That is what it means for the loss to give meaning to the model output.

The setup is the CPU of a MacBook Pro M1 Max, PyTorch 2.15.0, NumPy 2.5.4, Python 3.12.13. The MNIST part (12 settings x 3 seeds, 36 training runs of 5 epochs each) took 146 seconds, and the whole thing including the two variance-regression models took 163 seconds (measured while the Mac was shared with other jobs). Results can differ for full-size models, so the comparisons here are limited to the small 784-128-10 network and 5 epochs.

7. Summary

  • Choose the distribution the model output follows and use its negative log-likelihood, and the loss is determined. Gaussian gives MSE, Laplace gives MAE, Bernoulli gives BCE, categorical gives cross-entropy. The same recipe builds a loss for a new problem.
  • The mean is the maximum-likelihood answer for a Gaussian and the median for a Laplace. With outliers, this difference becomes large.
  • Cross-entropy equals reducing the KL divergence between the answer distribution and the model distribution, and combined with softmax or sigmoid its gradient is "prediction minus answer". The gradient does not saturate even when confidently wrong.
  • Measured, the logit gradient on confidently wrong samples was 1.41 for cross-entropy and 0.0042 for MSE on probabilities. But on MNIST with normal initialization the accuracy gap was small (95 to 97%).
  • If the model also outputs the variance, the same architecture can say how reliable it is (σ error 0.078 vs 0.0053).

Next post: Now that the loss is set, the question left is how to reduce it. In part 4 we compare how SGD, momentum and Adam reduce the same loss at different speeds with hand calculation and experiments, and look at why learning rate schedules, warmup and gradient clipping are needed.

References

Similar posts