Loss functions catalog
Every loss is a negative log-likelihood in disguise — pick the right disguise
The loss is the only thing a network ever sees of your goals. Choosing it well is choosing the probabilistic model you believe in: MSE says "Gaussian noise", cross-entropy says "categorical outcomes", InfoNCE says "find the matching pair". The same catalog reappears unchanged in vision (5.5 Object detection, 5.6 Segmentation), language modeling (7.6 Decoder-only: GPT and autoregressive generation), embeddings (9.2 Embeddings deep dive) and alignment (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI), and the log-sum-exp trick you learn here is why your training never produces NaN.
You'll be able to
- Derive MSE, MAE and cross-entropy as negative log-likelihoods under Gaussian, Laplace and Bernoulli/categorical models
- Implement cross-entropy from logits stably with the log-sum-exp trick and explain BCE-with-logits
- Choose a loss from the type of output and the data's quirks (outliers, imbalance, label noise)
- Explain label smoothing, focal loss, class weighting, KL divergence and contrastive losses and when each applies
- Compute cross-entropy and its gradient with respect to the logits for a small example
Key ideas
- Loss = negative log-likelihood under an assumed output distribution: Gaussian → MSE, Laplace → MAE, Bernoulli → BCE, categorical → cross-entropy.
- Cross-entropy from logits: CE = −z_y + LSE(z) with LSE(z) = m + log Σ e^{z_j − m}; never compute log(softmax) by hand.
- The gradient of softmax + cross-entropy with respect to the logits is p − y.
Show 4 more key ideas
- Huber is quadratic near zero and linear far away — the robust default for regression and value functions.
- Label smoothing (ε ≈ 0.1) and focal loss (γ ≈ 2) fight over-confidence and class imbalance respectively; class weights rebalance skewed datasets.
- KL divergence matches distributions (distillation, VAEs, RLHF); InfoNCE is cross-entropy over a batch of candidates and trains all embedding models.
- Optimize a differentiable surrogate, report the real metric, and check they agree on validation data.
Suggested path through this lesson
Losses are negative log-likelihoods
Almost every loss in deep learning comes from one recipe (1.7 Probability II: Bayes, independence, MLE and MAP): assume a probabilistic model for the output, and minimize the negative log-likelihood of the data,
The network outputs the parameters of that distribution (a mean, a probability, a vector of class probabilities), and the choice of distribution is the choice of loss. Seeing losses this way tells you which loss belongs to which problem and why some losses are robust and others are not.
Regression losses
- Mean squared error. Assume with . Then , so maximizing likelihood is minimizing (3.2 Linear regression). Its gradient grows with the error, so a single outlier can dominate a batch.
- Mean absolute error. Assume Laplace noise, , and you get : constant-magnitude gradient, robust to outliers, but non-smooth at zero and it estimates the median rather than the mean.
- Huber loss interpolates: for and beyond, where . Quadratic near the target (smooth, fast convergence), linear far away (robust). Default in many regression and RL value-function heads (4.11 Reinforcement learning essentials).
Classification losses
Binary cross-entropy. Model as Bernoulli with where is the logit. The NLL is
Categorical cross-entropy. For classes with one-hot target and softmax probabilities ,
the negative log-probability assigned to the correct class. This is also the cross-entropy of 1.9 Information theory: entropy, cross-entropy and KL divergence between the empirical distribution and the model, and for language models it is the per-token loss whose exponential is the perplexity (6.2 Classical NLP and n-gram language models, 7.6 Decoder-only: GPT and autoregressive generation). Its gradient with respect to the logits is startlingly simple — derived in 4.4 Backpropagation, fully derived:
Predicted minus actual: the network is pushed to raise the correct logit and lower the others in proportion to how much probability it wrongly assigned them.
Numerical stability: never exponentiate without the trick
Softmax involves , and already overflows float32. Because softmax is shift-invariant (4.2 Activation functions), subtract the maximum logit first. The log-sum-exp trick:
where every exponent is now . Then and with no explicit probabilities. For the binary case the stable form is
This is exactly what nn.CrossEntropyLoss and nn.BCEWithLogitsLoss compute. Rule: the model outputs logits; the loss owns the softmax/sigmoid. Computing log(softmax(z)) yourself gives as soon as one class underflows.
Worked example. Three classes, logits , correct class 0. Exponentials: ; sum ; probabilities . Loss . Gradient : the correct logit is pushed up, the others down. With the stable route: , , and . ✓
Modifiers for real data
- Class weights. Multiply each example's loss by a weight (often inverse class frequency) to stop a 99:1 dataset from being solved by predicting the majority (3.13 Feature engineering, data quality and data-centric ML).
- Label smoothing. Replace the one-hot target by . The optimum is no longer a logit of for the correct class, so the model stays calibrated and less over-confident; is standard in vision and machine translation. In the example above, gives smoothed targets and a loss of instead of : the model is charged for the probability it refused to spread.
- Focal loss down-weights examples the model already gets right ( near 1), focusing on hard ones; fixed the extreme foreground/background imbalance in one-stage detectors (5.5 Object detection).
- Hinge loss with wants a margin, not a probability — the SVM loss of 3.10 Support vector machines and kernels; rarely used in deep nets today.
Distribution-matching and metric losses
- KL divergence (1.9 Information theory: entropy, cross-entropy and KL divergence) matches one distribution to another: a student to a teacher in knowledge distillation (soft targets at temperature ), the approximate posterior to the prior in a VAE (8.8 Generative models I: VAEs and GANs), and the fine-tuned policy to its reference model in RLHF (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI). Minimizing is minimizing cross-entropy, because the data entropy is constant.
- Contrastive losses learn embeddings rather than labels. The InfoNCE loss for a batch of matched pairs with similarities and temperature ,
is just cross-entropy where the "classes" are the other items in the batch and the correct class is the true partner. It trains SimCLR (5.8 Self-supervised and contrastive learning), CLIP (8.10 Multimodal models) and every sentence-embedding model behind RAG (9.2 Embeddings deep dive). Triplet loss is the older margin-based cousin.
- Dice / IoU losses optimize overlap directly for segmentation masks where cross-entropy is swamped by background pixels (5.6 Segmentation).
The catalog in one table
| output type | model's output | activation (in the loss) | loss | implied distribution |
|---|---|---|---|---|
| real value | 1 number | identity | MSE / Huber / MAE | Gaussian / mixed / Laplace |
| yes/no | 1 logit | sigmoid | BCE with logits | Bernoulli |
| one of | logits | softmax | cross-entropy (+ label smoothing) | categorical |
| several of | logits | sigmoid each | BCE per label | independent Bernoullis |
| count | 1 number | exp | Poisson NLL | Poisson |
| match pairs | embeddings | softmax over batch | InfoNCE | categorical over candidates |
| match a distribution | logits | softmax | KL divergence | — |
Losses vs metrics
The loss must be differentiable and well-behaved; the metric you care about (accuracy, F1, BLEU, pass@1) usually is not. Cross-entropy is a smooth surrogate for accuracy; it keeps improving the margin after accuracy saturates, which is why validation loss can rise while accuracy is flat (over-confidence on a few errors). Report metrics, optimize losses, and check that the two agree on your validation set (3.5 Evaluating models: metrics, validation and the bias–variance trade-off).
Where this shows up later
- The gradient is the first step of the backprop derivation — 4.4 Backpropagation, fully derived; loss-curve pathologies and NaNs from unstable losses — 4.8 Training dynamics and debugging.
- Focal and Dice losses in detection and segmentation — 5.5 Object detection, 5.6 Segmentation; InfoNCE in self-supervised vision and CLIP — 5.8 Self-supervised and contrastive learning, 8.10 Multimodal models.
- Per-token cross-entropy as the language-modeling objective and perplexity — 6.2 Classical NLP and n-gram language models, 7.6 Decoder-only: GPT and autoregressive generation; KL penalties and preference losses in alignment — 8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI; the ELBO's KL term — 8.8 Generative models I: VAEs and GANs.
Common pitfalls (4)
- Computing log(softmax(z)) or log(sigmoid(z)) manually and getting −inf / NaN; use the with-logits losses.
- Using MSE for classification: it works poorly because its gradient vanishes exactly when the model is confidently wrong after a saturating activation.
- Applying class weights and oversampling at the same time, double-correcting the imbalance.
- Reading rising validation loss with flat accuracy as 'the model is getting worse' — it is usually over-confidence on a few mistakes; consider label smoothing or early stopping on the metric you care about.
Recap: all 7 key points
- Loss = negative log-likelihood under an assumed output distribution: Gaussian → MSE, Laplace → MAE, Bernoulli → BCE, categorical → cross-entropy.
- Cross-entropy from logits: CE = −z_y + LSE(z) with LSE(z) = m + log Σ e^{z_j − m}; never compute log(softmax) by hand.
- The gradient of softmax + cross-entropy with respect to the logits is p − y.
- Huber is quadratic near zero and linear far away — the robust default for regression and value functions.
- Label smoothing (ε ≈ 0.1) and focal loss (γ ≈ 2) fight over-confidence and class imbalance respectively; class weights rebalance skewed datasets.
- KL divergence matches distributions (distillation, VAEs, RLHF); InfoNCE is cross-entropy over a batch of candidates and trains all embedding models.
- Optimize a differentiable surrogate, report the real metric, and check they agree on validation data.
Watch
Why cross-entropy, not squared error, pairs with softmax outputs.
Read
Try it live
Interactive demo
runs in your browserExercises
- By hand: cross-entropy and its gradient
For logits and correct class 1, compute the softmax, the loss and by hand, then repeat with label smoothing . Expected: loss ≈ 0.16 unsmoothed; the smoothed loss is larger and the gradient on the wrong classes is reduced.
- NumPy: stable cross-entropy from logits
Implement
cross_entropy(logits, targets)using the log-sum-exp trick, with logits of shape (B, K). Test it on logits containing values like 1000 and −1000 where the naivenp.log(softmax)returns NaN or −inf. Expected: your version returns finite values and matchestorch.nn.functional.cross_entropyto 1e-6 on normal inputs. - Experiment: MSE vs cross-entropy for classification
Train the same MLP on MNIST twice: once with cross-entropy on logits, once with MSE on softmax outputs against one-hot targets. Compare training curves and final accuracy after 3 epochs. Expected: cross-entropy converges much faster; MSE stalls because its gradient shrinks when the softmax saturates.
- Experiment: imbalance fixes
Subsample a binary dataset to a 95:5 class ratio. Train logistic regression with (a) plain BCE, (b) class-weighted BCE, (c) focal loss with . Compare precision, recall and PR-AUC (3.5 Evaluating models: metrics, validation and the bias–variance trade-off). Expected: (a) nearly ignores the minority class; (b) and (c) trade precision for recall in different ways.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →