DL Notes
Comprehensive guide to loss functions - MSE, Cross-Entropy, Hinge Loss, Focal Loss with mathematical formulations, PyTorch implementations, and selection criteria.
Loss functions measure how far a model's predictions are from the true values. They provide the mathematical signal that drives learning through gradient descent and backpropagation.
Why Loss Functions Matter
| True Label | y = 1 (cat) |
| Prediction | y_hat = 0.9 --> Low Loss --> Small weight update |
| Prediction | y_hat = 0.1 --> High Loss --> Large weight update |
Mean Squared Error (MSE)
Used primarily for regression tasks.
Formula: MSE = (1/n) * sum((yi - y_hat_i)^2)
Binary Cross-Entropy Loss
Used for binary classification tasks.
Formula: BCE = -(1/n) * sum[y*log(y_hat) + (1-y)*log(1-y_hat)]
Categorical Cross-Entropy Loss
Used for multi-class classification.
Formula: CCE = -(1/n) * sum(sum(y_ij * log(y_hat_ij)))
Loss Function Comparison Table
| Loss Function | Task | When to Use |
|---|---|---|
| MSE | Regression | Continuous targets, Gaussian noise |
| MAE | Regression | Robust to outliers |
| Huber | Regression | Balanced robustness |
| BCE | Binary Classification | Two classes |
| Cross-Entropy | Multi-class | Mutually exclusive classes |
| Focal Loss | Detection | Class imbalance |
| Hinge Loss | SVM-style | Margin-based learning |
| KL Divergence | Distribution matching | VAEs, distillation |
Focal Loss (for Imbalanced Data)
Formula: FL = -alpha * (1 - p_t)^gamma * log(p_t)
Custom Loss Functions
import torch
import torch.nn as nn
class CombinedLoss(nn.Module):
def __init__(self, alpha=0.5):
super().__init__()
self.alpha = alpha
self.mse = nn.MSELoss()
self.l1 = nn.L1Loss()
def forward(self, predictions, targets):
return self.alpha * self.mse(predictions, targets) + \
(1 - self.alpha) * self.l1(predictions, targets)
loss_fn = CombinedLoss(alpha=0.7)
pred = torch.randn(32, 1)
target = torch.randn(32, 1)
print(f"Combined Loss: {loss_fn(pred, target).item():.4f}")Loss Function Selection Guide
Interview Questions
- Why is cross-entropy preferred over MSE for classification?
Cross-entropy produces larger gradients when predictions are wrong, leading to faster learning. MSE gradients vanish near 0 and 1 due to sigmoid saturation.
- What is label smoothing and why use it?
Replaces hard labels (0,1) with soft labels (0.05, 0.95). Prevents overconfidence and improves generalization.
- How does focal loss handle class imbalance?
It down-weights easy examples by multiplying by (1-pt)^gamma, focusing training on hard, misclassified examples.
- What is the relationship between MSE and maximum likelihood?
Minimizing MSE equals maximum likelihood under Gaussian noise. Cross-entropy equals MLE for Bernoulli/categorical distributions.
- When would you use KL divergence vs cross-entropy?
For training with fixed targets, they differ by a constant (entropy of true distribution). KL divergence is preferred when comparing two learned distributions.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Loss Functions in Deep Learning.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Deep Learning topic.
Search Terms
deep-learning, deep learning, deep, learning, neural, network, fundamentals, loss
Related Deep Learning Topics