A loss function measures how wrong a model’s predictions are. Training means adjusting weights to make this number smaller, so choosing the right loss is essential.
What You Will Learn
- MSE, MAE and Huber for regression
- Binary and categorical cross-entropy for classification
- Why cross-entropy punishes confident mistakes
- Matching loss to output layer
- Framework names
Regression Losses
import numpy as np
y_true = np.array([3.0, 5.0, 2.5])
y_pred = np.array([2.5, 5.0, 4.0])
err = y_true - y_pred
mse = np.mean(err ** 2)
mae = np.mean(np.abs(err))
huber = np.mean(np.where(np.abs(err) <= 1, 0.5 * err ** 2, np.abs(err) - 0.5))
print(round(mse, 4), round(mae, 4), round(huber, 4))
0.8333 0.6667 0.375
Explanation: MSE squares errors, so the 1.5 miss dominates – sensitive to outliers. MAE treats all errors linearly – robust. Huber (δ = 1) is quadratic for small errors and linear for large ones, a compromise.
Binary Cross-Entropy
y = np.array([1, 0, 1, 1])
p = np.array([0.9, 0.2, 0.6, 0.99])
bce = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
print(round(bce, 4))
print(round(-np.log(0.01), 3), round(-np.log(0.4), 3))
0.2123 4.605 0.916
Explanation: Cross-entropy is the negative log of the probability given to the correct class. Predicting 0.4 for a true positive costs 0.916, but a confident wrong 0.01 costs 4.605 – five times more. This strong push against confident mistakes is why cross-entropy trains classifiers faster than MSE.
Categorical Cross-Entropy
logits = np.array([2.0, 1.0, 0.1])
probs = np.exp(logits) / np.exp(logits).sum()
print(round(-np.log(probs[0]), 4), round(-np.log(probs[2]), 4)) # true class 0 vs true class 2
0.417 2.317
Explanation: If the true class is 0 (highest score) the loss is small; if it is class 2 the loss is large. See activation functions for softmax.
Choosing a Loss
| Problem | Output layer | Keras loss | PyTorch loss |
|---|---|---|---|
| Regression | Linear | “mse”, “mae”, “huber” | nn.MSELoss, nn.L1Loss, nn.HuberLoss |
| Binary classification | Sigmoid | “binary_crossentropy” | nn.BCEWithLogitsLoss (takes logits) |
| Multi-class, one-hot labels | Softmax | “categorical_crossentropy” | nn.CrossEntropyLoss (takes logits) |
| Multi-class, integer labels | Softmax | “sparse_categorical_crossentropy” | nn.CrossEntropyLoss |
| Multi-label | Sigmoid per class | “binary_crossentropy” | nn.BCEWithLogitsLoss |
Other losses: focal loss for heavy class imbalance, contrastive/triplet loss for embeddings, KL divergence in VAEs and distillation.
Series
Deep learning series: Intro to DL · ANN · Activation Functions · Loss Functions · Backpropagation · Optimizers · Dropout & BatchNorm · CNN · RNN · LSTM & GRU · Transfer Learning · Autoencoders · GANs · PyTorch vs TensorFlow
Interview Questions
Q: Why use cross-entropy instead of MSE for classification?
It gives larger gradients for confident wrong predictions and matches a probabilistic output, so it trains faster and better.
Q: MSE vs MAE?
MSE penalises large errors more and is outlier-sensitive; MAE is robust to outliers.
Practice Exercises
- Compute MSE and MAE again after changing one prediction to 10. Which changes more?
- Implement focal loss for the binary example with γ = 2.
Summary
Regression: MSE, MAE or Huber. Classification: binary or categorical cross-entropy matched to sigmoid or softmax outputs. The loss defines what “better” means during training.
Next: Backpropagation
Machine Learning Tutorials, Courses and Certifications