Loss Functions (Cross-Entropy, MSE, Huber)
Match losses to tasks: cross-entropy for classification, MSE/Huber for regression.
In plain words
The loss is a score for how wrong the model is. Training tries to make that score smaller, so the way you score mistakes decides what the model learns to care about.
Think of it like…
A strictness setting on a marker. MSE is a teacher who penalises a 6-point mistake 36 times harder than a 1-point mistake; MAE penalises it 6 times harder; Huber is a teacher who is strict on small slips but stops escalating after a point so one awful answer doesn't ruin the whole grade.
Where you’ve seen it
A delivery-time model predicts minutes for three orders with true times (3, 5, 10) and predictions (2.5, 5.5, 4). The residuals are −0.5, +0.5 and −6. MSE = (0.25 + 0.25 + 36) / 3 = 12.17, MAE = (0.5 + 0.5 + 6) / 3 = 2.33 and Huber with δ = 1 gives (0.125 + 0.125 + 5.5) / 3 = 1.92, because the 6-minute miss is charged linearly as 1 × (6 − 0.5) = 5.5 rather than quadratically. One bad order accounts for 36 of the 36.5 total squared error, so MSE would steer the model towards that outlier; the team trains with Huber and still reports MAE to operations. For the companion fraud classifier, the true-class probabilities 0.9, 0.5, 0.1 and 0.01 cost −ln p = 0.105, 0.693, 2.303 and 4.605 nats, so a confident wrong answer is punished hard. They also tried MSE on the sigmoid output: for a fraud case at logit z = −5 (p = 0.0067), the cross-entropy gradient with respect to z is p − y = −0.993, while the MSE gradient is 2(p − y)p(1 − p) ≈ −0.013, about 75 times smaller, so the model barely corrects the worst mistakes. With a 1:200 fraud rate they add class weights rather than resampling, and evaluate with precision-recall metrics.
Words you’ll hear
- Cross-entropy / log loss
- Negative log probability assigned to the true class.
- MSE / MAE
- Mean of squared or absolute residuals; MSE targets the mean, MAE the median.
- Huber loss
- Quadratic below δ, linear above, so outliers have bounded influence.
- Class weights
- Multipliers that make errors on rare classes cost more.
Visual diagram
Theory & deep dive
Regression losses and what they estimate
MSE = mean((y − ŷ)²) is minimised by the conditional mean, is smooth everywhere and has a gradient that shrinks as the model improves, which helps convergence. Its cost is sensitivity: with residuals −0.5, +0.5 and −6 the squared terms are 0.25, 0.25 and 36, so a single outlier supplies about 99% of the total. MAE = mean(|y − ŷ|) is minimised by the conditional median, and with the same residuals gives (0.5 + 0.5 + 6) / 3 = 2.33, but its gradient is ±1 regardless of the error size, which makes fine convergence noisy and the loss non-differentiable at zero.
Huber loss uses 0.5r² when |r| ≤ δ and δ(|r| − 0.5δ) otherwise. With δ = 1 the three residuals cost 0.125, 0.125 and 1 × (6 − 0.5) = 5.5, a mean of 1.92. Pick δ near the scale of typical errors (a common starting point is about one standard deviation of the residuals) and treat it as a hyperparameter. Quantile (pinball) loss targets a chosen percentile and is used for prediction intervals, and log-cosh is a smooth alternative. When the target spans orders of magnitude, train on log(y) so that errors are relative, and report errors in original units.
r = 0.5: 0.5 × 0.25 = 0.125. r = 6 with δ = 1: 1 × (6 − 0.5) = 5.5. Mean over (−0.5, +0.5, −6) = (0.125 + 0.125 + 5.5) / 3 = 1.917, compared with MSE 12.17 and MAE 2.33.
Cross-entropy for classification
For a binary label y ∈ {0, 1} and predicted probability p, the loss is −[y ln p + (1 − y) ln(1 − p)]; for K classes it is −ln p_true. A model that gives the true class 0.9 pays 0.105, at 0.5 pays 0.693, at 0.1 pays 2.303 and at 0.01 pays 4.605, so the penalty explodes as confidence in the wrong answer grows, which is exactly the incentive you want from a probabilistic model. With a softmax output the gradient with respect to the logits is simply p − y: for probabilities (0.659, 0.242, 0.099) and one-hot target (1, 0, 0) it is (−0.341, 0.242, 0.099), a clean push towards the right class.
Squared error on a sigmoid output has the extra factor p(1 − p), which is nearly zero when the output is saturated: for a positive example at logit −5 (p = 0.0067) the cross-entropy gradient is −0.993 but the MSE gradient is only about −0.013, so learning stalls precisely where the model is most wrong. Handling imbalance: use class weights or a focal loss to down-weight easy examples, and judge the model with precision, recall and PR-AUC rather than accuracy. Remember that cross-entropy rewards calibrated probabilities, so its value can improve while accuracy is unchanged.
Positive example, logit z = −5, p = σ(z) = 0.0067. Cross-entropy gradient wrt z: p − y = −0.993. MSE gradient: 2(p − y) p (1 − p) = 2 × (−0.993) × 0.0067 × 0.993 ≈ −0.013. The ratio is about 75 to 1.
How it works, step by step
Step 1 of 41. Identify the task and outputs
Decide whether the target is continuous, a single label, several labels or a distribution, and choose the output head.
- Head
- decides the loss
When to use it & trade-offs
What it is
A loss function turns a prediction and a target into one number that training minimises. For regression, mean squared error (MSE) averages squared residuals and punishes large errors heavily, mean absolute error (MAE) is robust but has a constant gradient, and Huber loss is quadratic for small errors and linear beyond a threshold δ, combining both behaviours. For classification, cross-entropy (log loss) is the negative log of the probability assigned to the true class: it is the maximum-likelihood objective for a categorical model and pairs naturally with sigmoid and softmax outputs. The loss you optimise is not always the metric you report, so pick the loss for good gradients and the metric for business meaning.
Why it matters: The loss defines what the model is rewarded for. MSE on data with outliers lets one wild point dominate the gradient; cross-entropy on a sigmoid output gives strong gradients when the model is confidently wrong, whereas squared error on the same output nearly stalls. Class imbalance, noisy labels and asymmetric costs all call for adjustments (weights, focal terms, quantile losses). Reading a loss curve correctly, and knowing why accuracy can stay flat while log loss improves, requires understanding these formulas.
When to reach for it
- Cross-entropy for fraud, churn and intent classification
- Huber for delivery-time and price regression with outliers
- Quantile loss for prediction intervals
When to avoid or be careful
- MSE on sigmoid outputs for classification
- Judging an imbalanced classifier by accuracy alone
- Optimising the log-scale loss but reporting it as business error
Choosing a loss
Strengths: Maximum likelihood; strong gradient when wrong.
Watch out: Sensitive to label noise and imbalance.
Strengths: Smooth; targets the mean.
Watch out: Outliers dominate.
Strengths: Robust to outliers.
Watch out: Constant gradient; slower fine convergence.
Strengths: Quadratic near zero, linear far away.
Watch out: Extra hyperparameter δ.
Interview signals & numbers to know
When this topic comes up
- “Why cross-entropy and not MSE for classification?”
- MSE versus MAE and the mean versus median
- Huber loss and its δ
- Loss versus evaluation metric
- Class weights and focal loss
Benchmarks & rules of thumb
- −ln p
- cross-entropy: 0.105 at 0.9, 0.693 at 0.5, 4.605 at 0.01
- 12.17 · 2.33 · 1.92
- MSE, MAE and Huber for residuals −0.5, +0.5, −6
- p − y
- gradient of softmax or sigmoid with cross-entropy, per logit
Common mistakes & follow-ups
Common interview mistakes
- Using MSE for classification and wondering why training stalls.
- Leaving δ at a default unrelated to the residual scale.
- Treating a falling loss as proof of better decisions without checking the metric.
Likely interviewer follow-ups
- Why does MSE estimate the mean and MAE the median?
- How would you pick δ for Huber?
- What does cross-entropy reward beyond accuracy?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Loss Functions (Cross-Entropy, MSE, Huber) with data science interview Q&A and hands-on practice.