Topic 2 of 5 · 4 min read
Choosing a loss function for the task
Goal: Match a task to mean squared error, cross-entropy or binary cross-entropy and explain the gap between training loss and the business metric.
The loss is the single number gradient descent lowers, so choose one that punishes the mistakes you care about and has a usable gradient. The model learns whatever the loss rewards, which is not always what the business measures.
Check yourself · 1 of 3
Which loss fits a model that predicts tomorrow's delivery time in minutes?
Why it matters
A wrong loss gives a model that trains smoothly and optimises the wrong thing. A classifier trained with squared error on class labels, or a demand model trained with an average that hides rare huge misses, are real examples. Gradient descent needs a smooth loss to follow, so many metrics you report cannot be trained on directly.
The three common choices
- Mean squared error (MSE) for predicting a number: price, temperature, delivery time. It averages
(prediction - truth)^2. Squaring punishes large misses hard: an error of 10 costs 100, ten times more than ten errors of 1 cost together (10). One outlier can dominate. Mean absolute error treats errors linearly and resists outliers. - Cross-entropy for choosing one of several classes. The model outputs a probability per class, and the loss is
-log(probability of the true class). Predict 0.9 for the right class and the loss is 0.105. Predict 0.01 and it is 4.61. Confident wrong answers cost the most, which is what you want. - Binary cross-entropy for yes/no or several independent yes/no labels (a photo can show both a dog and a car). The same idea per label.
Language models use cross-entropy too: at each position the model assigns probabilities to the next token, and the loss is the negative log of the probability of the real token.
Loss is not the metric
Accuracy, F1, revenue and user satisfaction are not smooth, so you cannot follow their gradient. You train on a loss that moves in the same direction and report the metric separately. They can disagree. A fraud model can lower cross-entropy while recall on the rare fraud class stays poor, because 99.8% of rows are legitimate and the average loss is dominated by them. Always track the real metric on validation data next to the loss.
Before and after
Weak: a team predicts customer churn (yes or no) with a linear output and MSE on 0/1 labels. Outputs drift outside 0 to 1 and gradients get weak for confident mistakes. Fixed: a sigmoid output with binary cross-entropy, which gives probabilities and a strong gradient when the model is confidently wrong.
import torch.nn as nn
loss_fn = nn.BCEWithLogitsLoss() # yes/no, takes raw scores
# nn.CrossEntropyLoss() # one of N classes, takes raw scores
# nn.MSELoss() # a number
What goes wrong
- Applying softmax before
CrossEntropyLoss. The loss applies it itself, so the probabilities get squashed twice and training stalls. - Optimising a loss, shipping a metric. Nobody checks the metric, and the model looks fine on loss only.
- Ignoring class imbalance. The majority class wins the average.
Examples
Matching tasks to losses
| Task | Output | Loss |
|---|---|---|
| Predict house price | one number | MSE or absolute error |
| Sort emails into 5 folders | 5 probabilities | cross-entropy |
| Tag a photo with any of 10 labels | 10 independent probabilities | binary cross-entropy |
| Next token of a text | probability per vocabulary token | cross-entropy |
Loss and metric disagree
A fraud model sees 1 fraud per 500 transactions. Validation loss falls for 20 epochs, yet recall on fraud stays at 12%. The average loss is dominated by the 499 easy rows. The fix is to weight the rare class or sample it more, and to select checkpoints by recall, not by loss.
Key points
- The loss is what gradient descent lowers, so the model learns whatever the loss rewards.
- Use MSE for numbers, cross-entropy for one of several classes, binary cross-entropy for yes/no labels.
- Cross-entropy charges -log(probability of the true class), so confident wrong answers cost the most.
- Squaring in MSE lets one outlier dominate; absolute error is more robust.
- Report the real metric on validation data next to the loss, because they can disagree.
Common mistakes
- Applying softmax or sigmoid and then a loss that already applies it.
- Using MSE on class labels.
- Judging a model by training loss alone without the business metric.
- Forgetting class imbalance when the average loss hides the rare class.
Check yourself · 2 of 3
A classifier gives the true class a probability of 0.01. Which loss value does cross-entropy, -ln(p), give for that example?
Check yourself · 3 of 3
Training loss keeps falling, but recall on the rare fraud class stays flat. What is the most useful reading?
Practice items, not counted towards your mastery.
Start here
- Google ML Crash Course: gradient descent (opens in a new tab)CourseFree
Gradient descent on a linear model with the update rule and learning rate shown step by step.
- CS231n: Optimization (opens in a new tab)CourseFree
Stanford notes on loss functions, gradients and numeric checks, with clear intuition.
- PyTorch docs: torch.optim (opens in a new tab)DocsFree
The optimizer API and learning rate schedulers you call in a training loop.