Loss Functions: Teaching the Network What 'Wrong' Means
A neural network learns by minimizing a single number: the loss. Pick the wrong loss and your model will optimize the wrong thing perfectly — high accuracy on something nobody asked for. MSE for regression, cross-entropy for classification, contrastive for similarity. Choosing the right scalar is half the engineering.
After this lesson, you will be able to:
Understand why different tasks need different loss functions, and what breaks when you pick the wrong one
See where the cross-entropy formula comes from (it is simpler than it looks)
Know when to reach for MSE, MAE, Huber, or cross-entropy in your own projects
Build loss functions from scratch and connect them to the backward pass
Loss functions are one of those topics that feel abstract at first but quickly become your best debugging tool. Once you understand them, you will start seeing training problems before they happen. Stay with it — this knowledge is deeply practical.
Pros: Smooth, differentiable everywhere, strongly penalizes large errors which can be good if all errors matter.
Cons: Sensitive to outliers. A single prediction that is 10x off contributes 100x as much to the loss as a prediction that is 1x off. In a noisy dataset, one bad label can dominate training.
Open the first derivation to see where the MSE gradient comes from, and the second to see why the best constant prediction under MSE is the mean.
Try it! Compute MSE by hand for predictions [3, 5, 7] vs true values [2, 5, 10]. Which prediction contributes most to the loss? Now try MAE on the same data. Notice how the outlier (7 vs 10) dominates less with MAE.
Pros: Robust to outliers. The optimal prediction under MAE is the median (not the mean), which is valuable when data is skewed.
Cons: Non-differentiable at zero (the gradient flips sign discontinuously). In practice, a subgradient of 0 is used at the kink. The constant-magnitude gradient means the optimizer doesn't apply extra force to large errors — convergence can be slower.
Open the derivation to see why the best constant prediction under MAE is the median.
Two models predict house prices. Model A: MSE=400 (RMSE=20), MAE=8. Model B: MSE=169 (RMSE=13), MAE=11. Which model should you trust more for typical predictions?
Open the derivation to see why the check in the last paragraph always works.
Model A has lower MAE (better typical-case performance) but higher MSE (worse worst-case performance). Model B misses most typical inputs by more, but it never misses by a lot. Always report both metrics. MSE and MAE tell different stories about the same model.
#Binary Cross-Entropy (BCE): From First Principles
Where does the BCE formula come from? It is not arbitrary — it falls out of maximum likelihood estimation.
Setup: We have a binary label y ∈ . Our model outputs p = P(y=1|x). We want to find parameters that maximize the probability of observing the training data.
The likelihood of a single example is:
P(y∣x)=py⋅(1−p)1−y
Take the log (it only increases, so the best parameters do not change), negate it so that we minimise instead of maximise, and average over n examples:
LBCE=−n1i=1∑n[yilogpi+(1−yi)log(1−pi)]
Open the derivation to see each of those moves written out, and why they do not change which parameters are best. Maximum likelihood is derived in MLE, MAP & Fisher Information.
The step from the sigmoid derivative to the gradient can be done in full. Open the derivation to see exactly what cancels, and why MSE does not get the same cancellation. The same argument for softmax is derived in Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules.
What Do You Think?
You're classifying emails as spam/not-spam. Your model outputs a sigmoid probability. You accidentally use MSE loss. What goes wrong?
The model will train and converge — MSE never causes NaN with bounded sigmoid outputs. But it will plateau at a worse accuracy than BCE. The weak gradients for confident mistakes mean the model never strongly corrects itself when it predicts 0.01 for a true spam email. BCE is the right tool.
Standard cross-entropy gives equal gradient weight to every example. In object detection, an image might have 100,000 background anchors (all easy negatives, p≈0.99 after a few epochs) and 10 actual objects. The gradient from 100,000 easy examples overwhelms the gradient from 10 hard ones.
FL(pt)=−(1−pt)γ⋅log(pt)γ≥0
With γ=2: an example with p_t=0.9 (easy) gets weight (0.1)²=0.01. An example with p_t=0.05 (hard) gets weight (0.95)²=0.90. The hard example gets 90× more gradient attention. This is what made RetinaNet competitive with two-stage detectors.
Open the derivation to see the full gradient of focal loss, including a term that a quick guess leaves out.
Label smoothing replaces a hard one-hot target with a slightly softened one. Open the first derivation to see the new target values, and the second to see how the gradient and the best logits change.
Used in: VAEs (latent space regularization), knowledge distillation (matching student to teacher distribution), and information-theoretic divergence minimization.
Open the derivation to see why minimising KL and minimising cross-entropy are the same job when P is fixed. The definitions of entropy and KL divergence are in Information Theory & Entropy.
InfoNCE scores a query against one positive key and several negative keys. Write q for the query, k_1 for the positive and k_2 to k_N for the negatives, and score each pair as s_j = q·k_j / tau, where tau is a temperature. The loss is then the negative log of how much of the softmax weight the positive gets. Open the first derivation to see that this is plain cross-entropy, and the second to see why it is tied to mutual information (defined in Information Theory & Entropy).
Visualize how different loss functions shape the optimization surface — see why MSE on classification creates flat plateaus while cross-entropy gives strong gradients.
The loss function is the only feedback signal a neural network has. Every gradient update is a response to the loss; choosing the wrong loss function means optimizing the wrong objective, regardless of how sophisticated the architecture is
MSE and cross-entropy are not interchangeable. BCE applies 50× stronger gradients to confident wrong predictions than MSE does; using MSE for classification is a silent bug that degrades but doesn't break training
Binary cross-entropy derives from maximum likelihood estimation. It is not an arbitrary formula; minimizing BCE is mathematically equivalent to maximizing the probability the model assigned to the correct labels
Loss function engineering is model engineering. Focal loss enabled single-stage object detection to compete with two-stage; label smoothing prevents overconfidence; class weighting handles imbalance; these are high-leverage interventions
You now understand how a neural network measures its own mistakes. Next: Backpropagation — how those mistake signals propagate backward through every layer to update every weight.