Loss Functions for Deep Networks
Imagine training a network to read handwritten digits. After Forward Propagation it outputs a vector of scores for classes 0–9. How do you tell the network it was wrong, and by how much? It must be done in a way that produces a useful learning signal. This is the job of a loss function: a single number that measures the distance between a prediction and the truth. It is small when the network is right and large when it is badly wrong. Without a loss function, there is nothing to differentiate. There is nothing to minimize, and no notion of "better" or "worse" weights. Loss functions matter because they are the mathematical bridge between raw predictions and the optimization machinery. That machinery includes gradient descent and The Chain Rule and Backpropagation, which update the network's parameters. The choice of loss is not cosmetic. It changes what "good performance" means. It affects how gradients behave near correct and incorrect predictions. It also affects whether training is numerically stable. A network trained with the wrong loss for its task can converge to garbage. This happens even if every other design choice is correct. This article builds the two workhorse losses of deep learning from first principles. These are mean squared error (MSE), the natural choice for regression, and cross-entropy, the natural choice for classification. We derive both from a probabilistic view (maximum likelihood). We show exactly how they behave on concrete numbers. We also explain why cross-entropy's gradient is so well-behaved. This is why it became the default for classifiers, including the deep networks behind image recognition, speech systems, and language models. By the end you will be able to write the loss computation step of a training loop by hand. You will be able to explain why cross-entropy pairs naturally with softmax. You will also see precisely how the loss's gradient becomes the starting signal for Backpropagation.
- A loss function turns a prediction and a target into one scalar that measures error — the quantity training minimizes.
- MSE, , is the maximum-likelihood loss under Gaussian noise; ideal for regression.
- Cross-entropy, , is the maximum-likelihood loss under a categorical/Bernoulli model; ideal for classification.
- Cross-entropy's gradient with softmax simplifies to , avoiding the vanishing-gradient problem that plagues MSE with saturating outputs.
- Both losses are convex in the model's output but not necessarily in the network's weights, so optimization is still nontrivial.
- The loss's gradient is exactly the signal that backpropagation propagates backward through the network.
A loss function converts "how wrong is this prediction" into a differentiable scalar, and the choice of loss — MSE for continuous targets, cross-entropy for class probabilities — determines both what the network learns and how cleanly gradients flow during training.
The idea
A loss function maps a prediction (the network's output after Forward Propagation) and a ground-truth target to a nonnegative real number, with only when the prediction is perfect. Averaged over a dataset of examples, this gives the cost function (sometimes the terms are used interchangeably)
where collects all weights and biases. Training a network is exactly the problem of choosing to minimize , typically via gradient-based optimization. The loss function is therefore the objective the entire learning machinery serves — every architectural choice from The Perceptron onward exists to produce a that this objective can score. Two losses dominate deep learning because they arise naturally from maximum likelihood estimation. If we assume that targets are generated as with Gaussian noise , maximizing the likelihood of the data under this model is equivalent to minimizing the sum of squared errors — this gives mean squared error (MSE), the standard loss for regression. If instead we assume targets are drawn from a categorical distribution over classes with the network producing estimated probabilities , maximizing likelihood is equivalent to minimizing the negative log-likelihood of the true class, which is exactly cross-entropy. Both losses, then, are not arbitrary engineering choices — they are the loss that makes gradient descent equivalent to maximum likelihood estimation under a natural noise model for the task.
How it works
Mean Squared Error. For a regression network producing scalar (or vector) output against target :
Its gradient with respect to the output is simple and linear:
which is exactly proportional to the error — large errors produce large gradients, small errors produce small gradients. This is a desirable, well-behaved signal as long as the output layer itself has a well-behaved gradient (e.g., a linear output unit).
Cross-entropy. For a -way classifier, the network typically outputs raw scores ("logits") , passed through a softmax:
Given a one-hot target vector (with for the true class , else 0), cross-entropy is
For binary classification with a sigmoid output and target , this specializes to
The key mechanical fact, derived below, is that when softmax (or sigmoid) is paired with cross-entropy, the gradient with respect to the logits collapses to the remarkably clean form
This is the gradient that The Chain Rule and Backpropagation receives as its starting point and propagates backward through every earlier layer.
Step-by-step algorithm (one training step)
```text function COMPUTE_LOSS_AND_GRAD(x, y_true, network, task):
# ---- forward pass (see Forward Propagation) ---- z = network.forward_to_logits(x) # raw scores, shape (K,) or scalar if task == "regression": y_hat = z # linear output unit loss = mean((y_hat - y_true)^2) dL_dyhat = (2 / len(y_true)) (y_hat - y_true) return loss, dL_dyhat # feed into backprop at output layer if task == "binary_classification": p_hat = sigmoid(z) eps = 1e-12 # numerical floor, avoids log(0) loss = -( y_truelog(p_hat+eps) + (1-y_true)*log(1-p_hat+eps) ) dL_dz = p_hat - y_true # combined sigmoid+BCE gradient return loss, dL_dz if task == "multiclass_classification": p_hat = softmax(z) # shift-stabilized, see below c = index_of_true_class(y_true) loss = -log(p_hat[c] + eps) dL_dz = p_hat.copy() dL_dz[c] -= 1 # p_hat - one_hot(y_true) return loss, dL_dz ``` The averaged cost over a mini-batch of size is simply , and the gradients above are likewise averaged before being handed to the optimizer.
Numerical stability note. Computing softmax naively, , can overflow for large logits. The standard fix subtracts the max logit first: ```text function SOFTMAX_STABLE(z): m = max(z) exps = [exp(zk - m) for zk in z] s = sum(exps) return [e / s for e in exps] ``` This is mathematically identical (the max cancels in numerator and denominator) but keeps exponents , avoiding overflow.
Complexity & correctness
Time complexity. For a -class output, computing softmax is (one exponential and one sum per class), and computing cross-entropy given softmax output is additional work (a single logarithm lookup for the true class, or if using the full one-hot dot product). MSE over a -dimensional output is . Over a mini-batch of size , both losses cost or — linear in batch size and output dimension, which is negligible compared to the cost of the forward and backward passes through the network itself. Loss computation is never the bottleneck of training; it is a thin, cheap layer sitting on top of an otherwise expensive computation graph.
Space complexity. Both losses require only or auxiliary storage per example (the softmax vector, or the elementwise squared differences), which is dominated by the memory needed to store activations for the backward pass.
Correctness: why MSE is the right loss for Gaussian regression. Assume with i.i.d. The likelihood of the dataset is
Taking the negative log-likelihood and dropping constants independent of :
Minimizing this over is identical to minimizing — i.e., MSE. So MSE is not an ad hoc choice; it is exactly the maximum-likelihood objective under a Gaussian-noise assumption. This also explains a well-known limitation: MSE is sensitive to outliers, because squared error grows quadratically, mirroring the thin tails of the Gaussian it assumes.
Correctness: why cross-entropy is the right loss for classification. With targets drawn categorically ( is one-hot over classes with true probability 1 on the correct class) and model , the likelihood of one example is (only the true-class term survives). The negative log-likelihood over the dataset is
which is exactly the sum of cross-entropy losses. So cross-entropy minimization is maximum likelihood estimation for a categorical output model — the same logic that justifies MSE for Gaussian regression.
Correctness: the softmax + cross-entropy gradient simplification. This is the crucial computational fact that makes cross-entropy so practical. Let be logits, , . Using (the softmax Jacobian) and the chain rule:
using since is one-hot. So despite softmax and log both being nonlinear, their combined gradient is the trivially simple residual . This matters enormously in practice: it means the error signal handed to backpropagation is large when the prediction is confidently wrong and vanishes gracefully as , with no extra multiplicative shrinkage from a saturating log or exponential derivative. Contrast this with using MSE on softmax outputs for classification: the chain rule there multiplies by the softmax Jacobian and the derivative of squared error, and because softmax saturates (derivatives near 0 or 1 flatten out), the resulting gradient can become vanishingly small even when the prediction is badly wrong — a classic cause of stalled training. This is the mathematical reason cross-entropy, not MSE, is the standard loss for classifiers.
Convexity caveat. Both losses are convex functions of the model's output ( or ) — a genuine, checkable mathematical property. But composed with a deep, nonlinear network , the loss as a function of the weights is generally non-convex, so gradient descent finds only a local optimum (or saddle), not a certified global minimum. Nothing about choosing the "right" loss removes this fundamental difficulty of deep learning optimization.
Worked example
Consider a 3-class classifier (cat / dog / bird) that has just produced logits for an image whose true label is dog (class index 1).
Step 1 — stabilized softmax. Subtract : shifted logits .
| class | |||
|---|---|---|---|
| cat | 2.0 | 0.0 | 1.0000 |
| dog | 1.0 | −1.0 | 0.3679 |
| bird | 0.1 | −1.9 | 0.1496 |
Sum . Normalizing:
| class | |
|---|---|
| cat | |
| dog | |
| bird |
(check: ✓)
Step 2 — cross-entropy loss. True class is dog, so (natural log). Notice the loss is fairly large: the model put most of its probability mass (0.659) on the wrong class (cat).
Step 3 — gradient with respect to logits, using with one-hot :
| class | |||
|---|---|---|---|
| cat | 0.6590 | 0 | +0.6590 |
| dog | 0.2424 | 1 | −0.7576 |
| bird | 0.0986 | 0 | +0.0986 |
Interpretation: the gradient pushes the "cat" logit down (positive gradient on a loss we minimize means decrease it) and pushes the "dog" logit up (large negative gradient means increase it strongly), exactly the correction we want. This 3-vector is exactly what gets handed to Backpropagation to update every earlier weight in the network.
Contrast with MSE. If instead we trained by applying MSE directly to against : . Computing , then multiplying by the softmax Jacobian entry gives a logit gradient of only about — nearly eight times smaller than the that cross-entropy delivers directly, for an equally wrong prediction. This numerically confirms the vanishing-gradient argument made above.
Common pitfalls & traps
| Pitfall | Why it hurts | Fix |
|---|---|---|
| Using MSE for a softmax classifier | Gradient shrinks due to softmax saturation, slowing learning | Use cross-entropy, which cancels the saturating derivative analytically |
| Computing | NaN/−∞ loss when a predicted probability is exactly 0 | Add a small epsilon or use numerically fused log-softmax |
| Naive softmax without max-subtraction | Overflow for large logits () | Subtract before exponentiating |
| Forgetting to average over batch | Loss (and gradient magnitude) scales with batch size, destabilizing learning rate tuning | Always divide summed loss by batch size |
| Wrong target encoding (index vs one-hot mismatch) | Silent shape bugs; loss computed against the wrong class | Match the loss function's expected label format exactly |
| Using cross-entropy with unnormalized (non-probability) outputs | Log of a number outside , or wrong likelihood interpretation | Always pass logits through softmax/sigmoid, or use a fused "logits" loss variant |
Pioneers & history
The probabilistic view of loss functions traces back to the foundations of statistics and information theory, later fused with neural network training in the 1980s–1990s as researchers connected likelihood-based objectives to gradient descent.
Origins · 1 minClaude Shannon and how this was discovered
Shannon's 1948 work on communication defined entropy as the expected information content of a message. Cross-entropy — the expected number of bits (or nats) needed to encode data from a true distribution using a model's estimated distribution — is a direct descendant, later adopted wholesale as a training objective for classifiers.
Where this matters
MSE and cross-entropy are the default loss functions built into every major deep learning framework, and nearly every production classifier or regressor uses one of them (or a close variant) as its training objective. Image classifiers underlying photo search and medical imaging diagnosis train with cross-entropy over thousands of classes. Speech recognition and machine translation systems use cross-entropy over vocabulary distributions at each decoding step, essentially treating "predict the next token" as a giant classification problem. Regression-style tasks — predicting a house price, a sensor reading, or a continuous control signal in robotics — use MSE or its robust cousins (Huber loss, mean absolute error) directly. Even large language models, at their core, are trained by minimizing cross-entropy between predicted next-token distributions and observed text, making the ideas in this article the literal training signal behind systems used by billions of people daily. Understanding these losses is also the necessary bridge to understanding The Chain Rule and Backpropagation, since the loss's gradient is precisely the starting point that backpropagation pushes through the network.
Ask the tutor: Can you derive, step by step, why the gradient of binary cross-entropy with a sigmoid output also simplifies to ?
Why can't we just use accuracy as the loss function directly?
Accuracy (fraction of correctly classified examples) is a step function of the model's parameters — it is flat almost everywhere and jumps discontinuously at decision boundaries. Such a function has zero gradient almost everywhere, so gradient descent gets no useful direction to move in. Losses like cross-entropy are smooth, differentiable proxies that closely track classification quality (they penalize low-confidence correct predictions and heavily penalize confident mistakes) while still providing a nonzero, informative gradient everywhere. This is a general pattern in machine learning: the metric you ultimately care about (accuracy, BLEU score, IoU) is often not directly optimizable, so you optimize a differentiable surrogate instead.
Is cross-entropy the same thing as KL divergence?
They are closely related but not identical. KL divergence between the true label distribution and prediction is , where is the cross-entropy and is the entropy of the true distribution. For one-hot hard labels, (no uncertainty), so minimizing KL divergence and minimizing cross-entropy become exactly equivalent. With soft labels (e.g., label smoothing or teacher-student distillation), is a nonzero constant with respect to the model parameters, so the two objectives still have identical gradients even though their absolute values differ.
When should I use mean absolute error (MAE) instead of MSE?
MAE, , is the maximum-likelihood loss under Laplace-distributed noise instead of Gaussian, and it grows linearly rather than quadratically with error size. This makes MAE far more robust to outliers: one wildly wrong prediction contributes proportionally to the loss rather than dominating it via squaring. The tradeoff is that MAE's gradient has constant magnitude (just the sign of the error) everywhere except at zero, where it is non-differentiable, which can make fine-grained convergence near the optimum less smooth. The Huber loss is a common compromise, behaving like MSE for small errors and like MAE for large ones.
Does the choice of loss function affect which optimizer I should use?
Indirectly, yes. The loss determines the shape of the optimization landscape — its curvature, the scale of its gradients, and whether saturating regions exist — all of which affect how well a given optimizer and learning rate perform. For instance, cross-entropy's well-scaled gradients (, bounded in per class) make it more forgiving of a fixed learning rate than a poorly chosen loss with wildly varying gradient magnitudes. However, modern optimizers like Adam adapt per-parameter learning rates partly to compensate for such scale differences, so the interaction is real but not usually the dominant factor in optimizer choice.
Can I design a custom loss function for a specialized task?
Yes, and this is common in practice — examples include IoU-based losses for object detection, perceptual losses for image generation, and contrastive losses for representation learning. The requirements are that the loss be differentiable (or subdifferentiable) almost everywhere with respect to the model's outputs, that it be minimized exactly (or nearly so) when predictions match targets, and ideally that it have a probabilistic or task-relevant justification like MSE and cross-entropy do. Custom losses without careful gradient analysis are a common source of the vanishing- or exploding-gradient bugs described in the pitfalls section, so deriving the gradient by hand before implementing is strongly recommended.
Why does cross-entropy use natural log rather than log base 2 or base 10?
The base of the logarithm only rescales the loss by a constant factor (), so it does not change where the minimum is or the direction of the gradient — it only rescales the gradient's magnitude uniformly. Natural log () is used by convention in deep learning because it simplifies the calculus (derivative of is , with no extra constant factor), matches the exponential in softmax exactly (so terms cancel cleanly, as shown in the gradient derivation), and connects directly to the "nats" unit used in information theory, as opposed to base-2 "bits" preferred in some information-theoretic contexts.
What happens to training if the loss function is not convex in the network's weights?
Almost all deep networks have non-convex loss surfaces in weight space, regardless of which loss (MSE or cross-entropy) is used, because composing linear layers with nonlinear activations destroys convexity. This means gradient descent is only guaranteed to reach a local minimum or saddle point, not the global optimum, and different initializations can lead to different final solutions. In practice, deep networks tend to train well despite this because high-dimensional loss landscapes have been empirically observed to have many nearly-equally-good local minima and relatively few problematic local minima, though this remains an active area of theoretical research rather than a settled proof.