Loss Functions & Objectives
The Central Role of Loss Functions
A neural network learns by minimizing a loss function (also called objective function, cost function, or criterion). The loss function answers: “How wrong is my prediction?” Think of the loss function as the coach’s scoring rubric. Two different coaches might evaluate the same performance differently — one penalizes big mistakes harshly (MSE), another treats all mistakes equally (MAE). The rubric you choose shapes what the athlete (model) optimizes for. Choose the wrong rubric and you get a model that is technically “optimizing” but optimizing the wrong thing. This is why loss function selection is one of the most consequential design decisions in deep learning. Where:- = model parameters (weights and biases)
- = model predictions
- = true labels
- = loss function
- The type of problem (regression, classification, ranking)
- The output distribution you expect
- What kind of errors you care about most
Regression Loss Functions
Mean Squared Error (MSE)
- Regression with Gaussian noise assumption (MSE is the maximum likelihood estimator when errors are normally distributed)
- When you want to penalize large errors heavily — a prediction off by 10 is penalized 100x more than one off by 1
Mean Absolute Error (MAE / L1 Loss)
- When outliers are expected
- When you care about median prediction
Huber Loss (Smooth L1)
Combines the best of MSE and MAE:Classification Loss Functions
Binary Cross-Entropy (BCE)
For binary classification with output :- Confident and correct: Low loss (you predicted what happened)
- Confident and wrong: Very high loss (the log penalty is brutal — this is by design)
- Uncertain (0.5): Medium loss (you are admitting you do not know)
Categorical Cross-Entropy
For multi-class classification with classes:Cross-Entropy with Logits
In practice, we use the numerically stable version that combines softmax + cross-entropy. This is not just a convenience — it is a necessity.Visualizing Loss Landscapes
Advanced Loss Functions
Focal Loss
Addresses class imbalance by down-weighting easy examples:Label Smoothing
Prevents overconfidence by softening targets:Contrastive Loss
For learning embeddings where similar items are close:Triplet Loss
For learning embeddings with anchor-positive-negative triplets:Loss Functions in PyTorch
Custom Loss Functions
Choosing the Right Loss Function
Decision Guide
Common Mistakes
Exercises
Exercise 1: Implement and Compare
Exercise 1: Implement and Compare
- Hinge loss:
- Exponential loss:
- Logistic loss:
Exercise 2: Custom Multi-Task Loss
Exercise 2: Custom Multi-Task Loss
- Classifies images (cross-entropy)
- Predicts bounding boxes (smooth L1)
- Estimates uncertainty (KL divergence)
Exercise 3: Loss Landscape Visualization
Exercise 3: Loss Landscape Visualization
- Along the line connecting initial and final weights
- In a random 2D plane around the minimum
Exercise 4: Focal Loss Tuning
Exercise 4: Focal Loss Tuning
- Train with BCE, Weighted BCE, and Focal Loss
- Tune the gamma parameter in Focal Loss
- Plot precision-recall curves for each
Key Takeaways
What’s Next
We’ve covered the foundations! Now let’s move to powerful architectures:Module 6: Convolutional Neural Networks
Interview Deep-Dive
Why is cross-entropy preferred over MSE for classification tasks? Derive the intuition from maximum likelihood estimation.
Why is cross-entropy preferred over MSE for classification tasks? Derive the intuition from maximum likelihood estimation.
- Cross-entropy is the negative log-likelihood of the data under the model’s predicted distribution. For a classification model that outputs probabilities via softmax, minimizing cross-entropy is mathematically equivalent to maximizing the likelihood of the correct labels — it is the maximum likelihood estimator for categorical data.
- MSE for classification has two fundamental problems: (1) the gradient for MSE with sigmoid output is , which includes the sigmoid derivative . When the model makes a confident wrong prediction (sigmoid saturated), , so the gradient vanishes precisely when it should be largest. Cross-entropy’s gradient is simply — no sigmoid derivative factor — so confident wrong predictions produce the largest gradients.
- (2) MSE’s loss landscape for classification has many flat regions (where sigmoid is saturated) and is non-convex with respect to the logits. Cross-entropy’s landscape is convex with respect to the logits (for a fixed linear model), leading to smoother optimization.
- Probabilistic interpretation: cross-entropy measures the KL divergence (plus a constant) between the true label distribution and the predicted distribution. It directly quantifies how surprised the model is by the true labels. MSE has no such information-theoretic interpretation for categorical data.
Explain focal loss. Why was it needed, and what problem does the gamma parameter solve?
Explain focal loss. Why was it needed, and what problem does the gamma parameter solve?
- Focal loss was introduced in the RetinaNet paper (Lin et al., 2017) to address the extreme class imbalance in object detection. In a typical image, there might be 100,000 background anchor boxes and only 10 foreground objects. Standard cross-entropy treats all examples equally, so the model is overwhelmed by the massive number of easy negatives.
- The formula: , where is the predicted probability for the true class. The key innovation is the modulating factor .
- When the model predicts correctly with high confidence (), the factor essentially eliminates this example’s contribution to the loss. The model no longer wastes gradient budget on examples it already classifies easily.
- When the model is wrong (), the factor keeps the loss nearly at its full value. Hard examples dominate the training signal.
- The gamma parameter controls the degree of focus. At , focal loss reduces to standard cross-entropy. At (the most common setting), easy examples are down-weighted by or more. At , the focusing is extreme and can make training unstable because too few examples contribute meaningful gradients.
- In practice, combined with class weighting is the standard recipe for detection and any heavily imbalanced classification problem.
You are designing a loss function for a model that must simultaneously classify objects AND predict their bounding boxes. How do you combine multiple loss terms?
You are designing a loss function for a model that must simultaneously classify objects AND predict their bounding boxes. How do you combine multiple loss terms?
- Multi-task learning requires a combined loss: , where is cross-entropy for classification and is smooth L1 (Huber loss) for bounding box regression. The challenge is balancing these losses so neither dominates.
- Why smooth L1 for bounding boxes: smooth L1 is quadratic for small errors (providing strong gradients near the optimum) and linear for large errors (preventing outlier boxes from dominating training). Pure MSE would cause one badly predicted box to overwhelm the gradients for all well-predicted boxes.
- Balancing loss terms: naive fixed-weight approaches () fail because the loss scales and gradient magnitudes differ. Three principled approaches:
- Manual tuning: start with equal weights, observe which task dominates (monitor individual loss curves), and adjust. Simple but tedious.
- Uncertainty-based weighting (Kendall et al., 2018): learn the weight for each task as where is a learned task uncertainty. Tasks with higher uncertainty receive lower weight. This is mathematically principled (derived from multi-task likelihood).
- GradNorm: normalize the gradient norms from each loss so they are approximately equal, preventing one task from dominating the shared representations.
- In modern object detectors (YOLO, Faster R-CNN), the standard approach uses fixed weights that are tuned on the validation set, typically with the classification loss weighted lower than the box regression loss because classification is easier to learn.
What is label smoothing, why does it improve generalization, and when can it hurt?
What is label smoothing, why does it improve generalization, and when can it hurt?
- Label smoothing replaces hard targets with soft targets (for and classes). Instead of driving the model to produce infinite logits for the correct class, it encourages the model to produce high but finite confidence.
- Why it improves generalization: (1) It prevents the model from becoming overconfident, which is a form of overfitting to the training labels. A model trained with hard labels can learn to output logits of magnitude 20+, which means tiny input perturbations can flip predictions. Label smoothing keeps logits moderate, producing more robust decision boundaries. (2) It implicitly regularizes by adding a uniform distribution component to the target, which is equivalent to adding a small KL-divergence penalty toward the uniform distribution. (3) It improves calibration — the predicted probabilities more accurately reflect the true uncertainty.
- When it can hurt: (1) In knowledge distillation, where the student should learn to match the teacher’s sharp predictions exactly. Smoothing the teacher’s targets reduces the information content. (2) When labels are genuinely certain and the data is clean — e.g., mathematical theorem proving where there is exactly one correct answer. (3) In metric learning or contrastive learning where you need the model to distinguish between semantically similar classes with high precision.
- Standard practice: use for image classification and for machine translation. It is essentially free to implement (one line in PyTorch:
nn.CrossEntropyLoss(label_smoothing=0.1)) and provides 0.2-0.5% accuracy improvement on most benchmarks.