Foundations to Frontier
Tests
D. Classical Machine Learning › D0 Core Concepts (concept pages)

Loss Functions for Classical Machine Learning

The loss function says what a model should care about. For regression, squared loss targets the mean and is sensitive to outliers, absolute loss targets the median, Huber and log-cosh combine the two, and the pinball loss targets any chosen quantile. For classification, the 0–1 loss counts mistakes but cannot be optimised directly, so models minimise convex surrogates: logistic loss (logistic regression), hinge loss (SVMs), exponential loss (AdaBoost) and squared loss, plus cross-entropy for many classes. This page compares their shapes, gradients, statistical targets and robustness. In the exercises you implement each loss with its gradient, check them numerically and find the constant each one prefers; then you measure how each loss copes with gross outliers in regression and with far-away mislabeled points in classification.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

How much does a mistake cost?

A loss function is a price list for mistakes. One rule says “pay the square of how far off you were”. Being off by 10 then costs 100, so the model worries a lot about a few big misses. Another says “pay how far off you were”. Being off by 10 costs only 10, so a few crazy points can’t boss the model around. Choosing the price list changes what the model learns.

How each loss treats outliers
loss vs residual
fitted slopes (true 0.8): ■ squared 1.53■ absolute 0.88■ Huber 0.95■ log-cosh 0.97
Dashed: the true line. Orange points are outliers lifted by the chosen height. The gradient of squared loss is the residual itself, so one far point pulls as hard as many near ones; the other losses cap that pull (absolute and Huber at a constant, log-cosh smoothly), which is why they are called robust.
Why engineers care

Sensor data contain glitches: a dropped bit, a saturated reading, a mislabeled log entry. With squared loss, a handful of glitches can tilt a calibration curve. Robust losses keep the fit honest without hand-cleaning every point.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Which loss is most pulled by a single far-away point?
  2. 2. A loss function measures…
  3. 3. In the demo, robust losses…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Regression losses (residual r = y − ŷ)

Loss Formula Best constant Notes
squared (L2) ½r² mean smooth; outlier-sensitive
absolute (L1) |r| median robust; kink at 0
Huber (δ) ½r² if |r| ≤ δ, else δ(|r| − δ/2) between mean and median smooth and robust
log-cosh log cosh r close to Huber with δ ≈ 1 twice differentiable
pinball (τ) max(τr, (τ−1)r) τ-quantile prediction intervals

Classification losses (margin m = y·f(x), y = ±1)

Loss Formula Used by
0–1 1[m ≤ 0] the goal, not optimisable
hinge max(0, 1 − m) SVM
logistic log(1 + e^(−m)) logistic regression
exponential e^(−m) AdaBoost
squared (1 − m)² ridge classifier

Multiclass models use cross-entropy, −log softmax(f)_y.

from sklearn.linear_model import HuberRegressor, QuantileRegressor, SGDClassifier
HuberRegressor(epsilon=1.35).fit(X, y)
QuantileRegressor(quantile=0.9, alpha=0).fit(X, y)          # 90% quantile
SGDClassifier(loss="hinge").fit(X, y)                        # loss="log_loss", "modified_huber", …
📝 Quick check (Level 1)
0/3 answered
  1. 1. Which loss estimates the median?
  2. 2. The SVM minimises…
  3. 3. To predict the 90th percentile of delivery time, use…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Gradients decide behaviour

The gradient with respect to the prediction says how hard each example pulls.

  • Regression: for squared loss the pull is the residual r, unbounded. For absolute loss it is sign(r), bounded. Huber clips the pull at ±δ; log-cosh gives tanh(r).
  • Classification: for a badly wrong point (m very negative):
    • hinge pulls with constant force;
    • logistic pulls with force tending to 1;
    • exponential pulls with force e^(−m), which explodes;
    • squared loss even pulls on points that are too correct (m > 1).

Statistical targets. Squared loss is minimised by E[y | x]; absolute loss by the median; pinball loss by the τ-quantile. Logistic loss gives calibrated probabilities (σ(f) estimates P(y = 1 | x)). Hinge loss only estimates the sign. All convex surrogates above are classification-calibrated: minimising them over all functions gives the Bayes classifier (Bartlett, Jordan and McAuliffe, 2006).

🐍 Exercise 1: losses, gradients and what they estimate
Implement squared, absolute, Huber, log-cosh and pinball regression losses and hinge, squared hinge, logistic and exponential margin losses with their derivatives; check every derivative numerically; check the convex losses upper-bound the 0–1 loss; implement multiclass cross-entropy with its gradient; find the constant each regression loss prefers for data with an outlier.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Gradient of Huber loss for a residual of 5 with δ = 1?
  2. 2. Which loss pull explodes for badly misclassified points?
  3. 3. Which loss gives calibrated probabilities?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Choosing a loss

  • Match the decision: predict means (cost proportional to squared error), medians (absolute costs), quantiles (asymmetric costs, safety margins), or probabilities (logistic or cross-entropy, then a threshold, D0.9).
  • Robustness: use Huber, absolute or a quantile loss when outliers are expected in the target. In classification, prefer hinge or logistic over exponential when labels may be noisy.
  • Optimisation: smooth losses (squared, logistic, log-cosh) allow Newton and L-BFGS methods. L1, hinge and pinball need subgradients, linear programs or smoothing.
  • Evaluation and training can differ: train on log-loss, evaluate on F1 or a business cost.

Interview questions.

  • Why not optimise accuracy directly? The 0–1 loss is piecewise constant, so it has zero gradient almost everywhere and is NP-hard to minimise for linear models.
  • Why is AdaBoost sensitive to label noise? Exponential loss weights misclassified points by e^(−m), so mislabeled points dominate.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Asymmetric costs (under-predicting fuel is worse than over-predicting) call for…
  2. 2. Why is 0–1 loss not optimised directly?
  3. 3. Squared loss for classification penalises…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Robustness, measured

Exercise 1. For y = 1, 2, 3, 4, 100 the losses prefer different constants:

  • squared loss: the mean, 22;
  • absolute loss: the median, 3;
  • Huber (δ = 1): 3.00, ignoring the outlier;
  • pinball with τ = 0.7: the 70% quantile, 4.

All derivatives match finite differences. Hinge, scaled logistic and exponential losses upper-bound the 0–1 loss.

Exercise 2a: regression with gross outliers. Setup: y = 2 + 3x + noise (σ = 0.5), 200 points, a fraction ε of points shifted by +20 to +40 in a pattern that tilts the line; median absolute slope error over 30 datasets.

ε squared absolute Huber (δ = 1.35σ) log-cosh
0 0.028 0.034 0.022 0.023
5% 1.204 0.029 0.033 0.049
10% 2.445 0.044 0.074 0.113
20% 4.429 0.128 0.169 0.249
30% 6.946 0.223 0.292 0.437

On clean data, Huber is most precise and absolute least, as theory predicts. With just 5% outliers, squared loss is off by 40% of the slope. The robust losses stay within a few percent even at 20–30%. Log-cosh, whose pull saturates only slowly, is the least robust of the three.

Exercise 2b: classification with far-away mislabeled points. Setup: two Gaussian classes, 400 training points; a fraction ρ replaced by a tight cluster far on the positive side, labelled negative; clean test accuracy over 20 datasets.

ρ logistic hinge exponential squared
0 0.909 0.909 0.909 0.909
2% 0.907 0.910 0.844 0.898
5% 0.845 0.906 0.731 0.811
10% 0.543 0.714 0.535 0.542

The exponential loss, whose pull explodes, breaks first (−6.5 points at only 2%). Hinge, with a bounded constant pull, survives 5% almost untouched. Logistic sits in between. At 10%, all convex losses are dragged substantially. Fully robust classification needs non-convex losses or data cleaning.

🐍 Exercise 2 (research): which losses survive dirty data?
Fit lines by iteratively reweighted least squares under squared, absolute, Huber and log-cosh losses with 0–30% gross outliers and compare slope errors; train linear classifiers with logistic, hinge, exponential and squared losses on data containing 0–10% far-away mislabeled points and compare clean test accuracy.

Loss functions in AI, robotics and aerospace

  • Robust state estimation: Huber and Cauchy losses in bundle adjustment and SLAM back-ends reject bad feature matches.
  • Quantile forecasts: pinball loss for battery state-of-charge bounds and demand intervals.
  • Safety margins: asymmetric losses when under-prediction (of load, of distance to obstacles) is costlier.
  • Classification under label noise: hinge or bounded losses for crowd-labelled or automatically labelled data.

References

  1. P. J. Huber (1964). “Robust estimation of a location parameter.” Annals of Mathematical Statistics 35(1).
  2. R. Koenker, G. Bassett (1978). “Regression quantiles.” Econometrica 46(1).
  3. P. L. Bartlett, M. I. Jordan, J. D. McAuliffe (2006). “Convexity, classification, and risk bounds.” JASA 101(473).
  4. P. M. Long, R. A. Servedio (2010). “Random classification noise defeats all convex potential boosters.” Machine Learning 78(3).
  5. T. Hastie, R. Tibshirani, J. Friedman (2009). The Elements of Statistical Learning, 2nd ed., section 10.6. Springer.