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 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 follows. For regression it says "the answer is spread around the 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 ten times and get 7 heads and 3 tails. If the tosses are independent, the probability of this outcome (the likelihood) is
(the order in which they came is only a constant factor, so we ignore it). Let us evaluate it for a few values of .
| 0.3 | 0.5 | 0.7 | 0.9 | |
|---|---|---|---|---|
| 0.0000750 | 0.000977 | 0.002224 | 0.000478 |
It is largest at . 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 data points we multiply probabilities, and for example 400 events of probability 0.1 multiply to , which is outside the range of 64-bit floating point (about ). 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.
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 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.

3. A Gaussian gives MSE
In regression, suppose the answer is with Gaussian (normal) noise. If the model outputs the mean and the standard deviation is fixed, then
In words: the further the answer is from , the faster the probability falls off in a bell shape, and the negative log of that is "distance squared". With fixed, the constant and do not affect the minimization, so what remains is , 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 , answering with one constant , the sum of squared errors (SSE) and the sum of absolute errors (SAD) are:
| 1 | 2 | 7/3 ≈ 2.33 | 3 | |
|---|---|---|---|---|
| SSE = | 10 | 5 | 4.67 | 6 |
| SAD = | 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, ), 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 and let the model output it too, the term of the NLL comes alive.
Take an error of 1 and vary . For it is , for it is , and for it is . The minimum is at a equal to the error. If is too small the squared term punishes, and if it is too large the 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 (sigmoid). The likelihood is if the answer is 1 and if 0, which in one line is , so
This is binary cross-entropy (BCE). If the answer is 1 only remains, and if 0 only .
Many classes. From the probability vector softmax outputs, we only look at the probability of the correct class: . In the three-class example of part 1, the scores (logits) give softmax probabilities .
| Correct class | Probability given to it | Loss |
|---|---|---|
| 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 (the answer) and (the model) is . If the answer is one-hot, and the rest are 0, so only remains, exactly the formula above. Cross-entropy is the entropy of 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 derived in part 2 follows the same thread. For binary classification, differentiating BCE with respect to the sigmoid input also gives . 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, .
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 and the model output the probability from the logit . Differentiating the two losses with respect to :
The MSE version is multiplied by the sigmoid derivative . When 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 ().
| Logit | 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 , 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.

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 is right. With 4 classes and 5 samples, we compared PyTorch's F.cross_entropy (autograd), our formula , and a hand-written numerical derivative (central difference, ).
| Comparison | Max difference |
|---|---|
Loss: mean of vs F.cross_entropy |
0 |
| Gradient: vs autograd | |
| Gradient: vs numerical derivative |
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.

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 , with a noise standard deviation that grows with (). A neural network (1-64-64-2, tanh) outputs two values, the mean and , 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).

| Metric | NLL (learn μ and σ) | MSE (mean only) |
|---|---|---|
| Mean error of the predicted mean | 0.0117 | 0.0096 |
| Mean error of the predicted noise level | 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
- S. J. D. Prince, Understanding Deep Learning, chapter 5 "Loss functions", MIT Press, 2023.
- C. M. Bishop, H. Bishop, Deep Learning: Foundations and Concepts, chapters 4 and 5, Springer, 2024.
- Stanford CS231n, "Linear Classification: Softmax and cross-entropy".
- NLL regression that also predicts the variance: D. A. Nix, A. S. Weigend, "Estimating the mean and variance of the target probability distribution", IEEE ICNN, 1994.
- Y. LeCun, C. Cortes, C. J. C. Burges, the MNIST handwritten digit dataset.

