Level 3 In-Depth AI · Classical Machine Learning
Loss Functions
The single number a model is trained to make small. Choosing it is choosing what "wrong" means, so it quietly decides which mistakes your model will avoid and which it will tolerate.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 9 concepts →
- Quiz
- 5 questions ↓
Read first
Linear RegressionThis leads to
—The full path from zero — 9 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- How Machines Learn
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- Loss Functions
Read them roughly in this order. See it on the concept map →
Why it matters
Training a model means making a number small. That number is the loss, and the formula that computes it is the loss function. You will also see it called the cost function or the objective function. Some authors use "loss" for one example and "cost" for the average over the data, but most people use the words interchangeably.
The loss function is the only thing the training algorithm ever sees. Gradient Descent doesn't know that you are predicting house prices or diagnosing tumours. It only knows how to push the loss down. So the loss is your definition of a good model, written in maths. Choose it carelessly and you get a model that is excellent at the wrong thing.
The choice matters at every scale. A delivery company predicting arrival times wants to be roughly right most of the time and doesn't want a handful of freak traffic jams to distort every prediction. A bank estimating risk cares a lot about rare large losses. A spam filter needs confident, calibrated probabilities. Large language models are trained with a single loss, the cross-entropy of the next token, and almost everything they can do emerges from pushing that one number down (Language Modeling and Next-Token Prediction, Pretraining Large Language Models).
The intuition
Think of the loss function as a fine schedule. Every time the model misses, it pays a fine, and training is the model's attempt to pay as little as possible in total. Different fine schedules produce different behaviour:
- A fine proportional to the size of the miss (absolute error) treats a 10-minute error as exactly ten times as bad as a 1-minute error.
- A fine proportional to the square of the miss (squared error) treats a 10-minute error as a hundred times as bad. The model will bend over backwards to avoid big misses, even if that means many small misses elsewhere.
- A fine that is zero if you are right and 1 if you are wrong (0–1 loss) counts mistakes and nothing else.
None of these is "correct". Each encodes a different idea of what matters. Here is the classic consequence. Suppose you must predict one number for five deliveries that took 10, 12, 13, 15 and 50 minutes. Under squared error the best single guess is the mean, 20 minutes. Under absolute error it is the median, 13 minutes. The one 50-minute delivery drags the mean up, but the median ignores how extreme it was. Which is better depends on what you care about.
Key idea A loss function turns "how wrong is this prediction?" into a number. Squared error chases the mean and fears big misses. Absolute error chases the median and shrugs at outliers. Cross-entropy rewards confident correct probabilities and punishes confident wrong ones. Pick the one that matches what a mistake really costs you.
How it works
Throughout, is the true label, the prediction, and the residual is the error on one example. The loss over a dataset is the average of the per-example losses.
Losses for regression
Mean squared error (MSE), the loss from Linear Regression:
It is smooth everywhere, which makes gradient descent easy, and its gradient is proportional to the error, so big errors produce big corrections. Its weakness is the same fact seen from the other side: one huge error can dominate the sum.
Mean absolute error (MAE), also called L1 loss:
The vertical bars mean "absolute value": drop the minus sign. Every unit of error costs the same, so outliers can't take over. Its gradient is always +1 or −1 (undefined at exactly zero), so it gives the same size of push for a tiny error as for a huge one, which can make optimisation slower and jumpier near the minimum.
Huber loss combines the two. Below a threshold ("delta") it is squared, and above it, it is absolute:
The two pieces join smoothly at . Small errors get the smooth, well-behaved squared treatment, and large ones are only charged linearly. You choose to say where "normal noise" ends and "outlier" begins.
A worked example: one guess for five deliveries
Deliveries took 10, 12, 13, 15 and 50 minutes. Compare guessing the mean (20) with guessing the median (13).
| Guess | Errors | Squared errors | MSE | Absolute errors | MAE |
|---|---|---|---|---|---|
| 20 (mean) | −10, −8, −7, −5, +30 | 100, 64, 49, 25, 900 | 227.6 | 10, 8, 7, 5, 30 | 12.0 |
| 13 (median) | −3, −1, 0, +2, +37 | 9, 1, 0, 4, 1369 | 276.6 | 3, 1, 0, 2, 37 | 8.6 |
Each loss prefers its own answer. MSE prefers 20, because the single miss of 37 minutes costs 1,369 on its own. MAE prefers 13, which is within 3 minutes for four of the five deliveries. This is not a coincidence: for any set of numbers, the mean minimises squared error and the median minimises absolute error. A model trained with MSE predicts the average outcome for each input. A model trained with MAE predicts the typical outcome.
A related loss, the quantile loss (or pinball loss), charges under-predictions and over-predictions at different rates. With rates 0.9 and 0.1 the model learns the 90th percentile instead of the median: useful for "we should have enough stock 90% of the time".
Losses for classification
A classifier usually outputs a probability that the example belongs to the positive class (label rather than ). The standard loss is cross-entropy, here in its two-class form, binary cross-entropy (also called log loss):
It looks fiddly, but only one of the two terms is ever active. If the true label is 1 the loss is . If it is 0 the loss is . Either way it is minus the log of the probability the model gave to the right answer. ( is the natural logarithm.)
That has a sharp effect. Three examples, all truly positive, with predicted probabilities 0.9, 0.6 and 0.1:
| for the true class | Loss |
|---|---|
| 0.9 (confident, right) | 0.105 |
| 0.6 (unsure, right) | 0.511 |
| 0.1 (confident, wrong) | 2.303 |
Average: 0.973. The confident wrong answer costs 22 times as much as the confident right one, and as approaches 0 the loss heads to infinity. Cross-entropy is what you get from Maximum Likelihood Estimation: minimising it is the same as choosing the parameters that make the observed labels most probable. With many classes the formula keeps the same meaning, , and it is exactly what softmax classifiers (Logistic Regression) and language models minimise. Logistic Regression works through it in detail, and Entropy, Cross-Entropy and KL Divergence explains the name.
What we actually care about is often just 0–1 loss: 1 for each wrong answer, 0 for each right one, so the average is the error rate. Why not train on that directly? Because it is flat almost everywhere. Nudge a parameter slightly and the number of mistakes usually doesn't change at all, so its gradient is zero and gradient descent has nothing to follow. We therefore train on a smooth surrogate loss that goes down when the 0–1 loss would, and then report the error rate separately (Evaluation Metrics).
Two surrogates dominate. Both are written in terms of the margin , where the label is coded as or and is the model's raw score (positive means "predict +1"). A positive margin means correct, and a bigger margin means more confidently correct.
- Logistic loss, , is cross-entropy rewritten in terms of the score. It never quite reaches zero, so it always rewards a bit more confidence.
- Hinge loss, , is zero once an example is correct by a margin of at least 1, and grows linearly otherwise. It is the loss of support vector machines. With scores 2, 0.5 and −1 on three positive examples, the hinge losses are 0, 0.5 and 2.
The loss encodes what you care about
Choosing a loss is a modelling decision, not a technicality. Some examples:
- Outliers are errors in the data (typos, sensor glitches): use MAE or Huber, so they don't distort the model.
- Outliers are real and expensive (a rare huge insurance claim): use MSE, which takes them seriously.
- Mistakes have different costs (missing a cancer is worse than a false alarm): weight the loss, for example by multiplying the loss on positive examples by 10. Most libraries offer
class_weightorsample_weightfor this. - You need probabilities you can act on (risk scores, betting odds): use cross-entropy, which rewards honest probabilities. Hinge loss does not.
- You need a range, not a point: use quantile loss at, say, the 10th and 90th percentiles.
Many models add a second term to the loss that has nothing to do with the data: a penalty for large weights. That is Regularization: L1 and L2, and the total is often written .
In code
All five losses from scratch, checked on the worked examples:
import numpy as np
def mse(y, p): return np.mean((p - y) ** 2)
def mae(y, p): return np.mean(np.abs(p - y))
def huber(y, p, delta=1.0):
r = np.abs(p - y)
return np.mean(np.where(r <= delta, 0.5 * r**2, delta * (r - 0.5 * delta)))
def bce(y, p, eps=1e-12): # y in {0,1}, p = predicted P(y=1)
p = np.clip(p, eps, 1 - eps)
return np.mean(-(y * np.log(p) + (1 - y) * np.log(1 - p)))
def hinge(y, s): # y in {-1,+1}, s = raw score
return np.mean(np.maximum(0, 1 - y * s))
# Delivery times in minutes; one delivery got stuck in traffic
y = np.array([10, 12, 13, 15, 50.0])
for c in [y.mean(), np.median(y)]:
p = np.full_like(y, c)
print(f"predict {c:4.1f}: MSE {mse(y,p):6.1f} MAE {mae(y,p):5.1f} Huber {huber(y,p):5.2f}")
print("cross-entropy:", bce(np.array([1, 1, 1]), np.array([0.9, 0.6, 0.1])).round(3))
print("hinge: ", hinge(np.array([1, 1, 1]), np.array([2.0, 0.5, -1.0])).round(3))
from sklearn.metrics import log_loss # the library version agrees
print("sklearn log_loss:", round(log_loss([1, 1, 1], [0.9, 0.6, 0.1], labels=[0, 1]), 3))
# predict 20.0: MSE 227.6 MAE 12.0 Huber 11.50
# predict 13.0: MSE 276.6 MAE 8.6 Huber 8.20
# cross-entropy: 0.973
# hinge: 0.833
# sklearn log_loss: 0.973
The np.clip in bce stops log(0), which would be minus infinity. Every real implementation has a guard like this.
Now the same data fitted with three different losses. scikit-learn has a model for each: LinearRegression (squared), HuberRegressor and QuantileRegressor at the median (absolute).
import numpy as np
from sklearn.linear_model import LinearRegression, HuberRegressor, QuantileRegressor
rng = np.random.default_rng(0)
x = rng.uniform(0, 10, 50)
y = 2 * x + 1 + rng.normal(0, 1, 50) # true line: slope 2, intercept 1
y[np.argsort(x)[-4:]] -= 30 # corrupt the 4 right-most points
X = x.reshape(-1, 1)
for name, model in [("squared (OLS)", LinearRegression()),
("Huber", HuberRegressor()),
("absolute (LAD)", QuantileRegressor(quantile=0.5, alpha=0))]:
model.fit(X, y)
print(f"{name:15s} slope {model.coef_[0]:5.2f} intercept {model.intercept_:5.2f}")
# squared (OLS) slope 0.82 intercept 4.83
# Huber slope 2.00 intercept 0.90
# absolute (LAD) slope 2.01 intercept 0.99
Four bad points out of fifty cut the least-squares slope from 2 to 0.82. Huber and absolute loss recover the truth almost exactly. In PyTorch the same losses are nn.MSELoss, nn.L1Loss, nn.HuberLoss, nn.BCEWithLogitsLoss and nn.CrossEntropyLoss.
Common pitfalls
- Training on one loss, judging on another, and being surprised. A model trained with MSE predicts means. If your business metric is "within 5 minutes most of the time", the median (MAE) may serve better. Make the training loss and the evaluation metric agree as far as possible.
- Comparing loss values across different losses or datasets. An MSE of 227.6 and an MAE of 12.0 are in different units (minutes² versus minutes). Report RMSE, the square root of MSE, to get back to the label's units.
- Taking the log of 0. Cross-entropy on a predicted probability of exactly 0 or 1 gives infinity or
NaN. Clip probabilities, or better, let the library compute the loss directly from raw scores (logits), which is numerically stable. - Applying softmax twice. In PyTorch,
nn.CrossEntropyLossexpects raw scores and applies the softmax itself. Feeding it probabilities silently trains a worse model. - Ignoring class imbalance. If 99% of transactions are legitimate, unweighted cross-entropy is happy to predict "legitimate" for everything. Weight the classes or resample (Data Cleaning and Preparation).
Watch out MSE on probabilities is a poor classification loss. If the true label is 1 and the model says 0.0001, squared error is at most 1, so the model is barely punished for being confidently wrong. Cross-entropy charges about 9.2 and drives the model to fix it. Use cross-entropy for classifiers.
Where it leads
- Logistic Regression derives cross-entropy from probabilities and trains a classifier with it.
- Regularization: L1 and L2 adds a penalty on weights to the loss.
- Evaluation Metrics covers the numbers you report, which are often not the numbers you train on.
- Support Vector Machines is built around the hinge loss and its margin.
- Maximum Likelihood Estimation shows that MSE assumes bell-shaped (Gaussian) noise, MAE assumes a sharper-peaked Laplace noise, and cross-entropy assumes categorical labels.
- In deep learning, special losses shape what is learned: contrastive losses in CLIP and Contrastive Learning and Sentence Embeddings, adversarial losses in Generative Adversarial Networks, preference losses in RLHF and Preference Optimization.
A bit of history
Squared error came first, with Legendre and Gauss around 1805–1809, partly because it gives a clean formula you can solve by hand. Absolute error is actually older as an idea: Roger Boscovich fitted lines by minimising absolute deviations in the 1750s, but without computers it was much harder to solve. Peter Huber introduced his loss in 1964 as part of founding robust statistics: methods that don't fall apart when a few data points are bad. Cross-entropy comes from Claude Shannon's information theory (1948) and the statistics of logistic models. The hinge loss came with support vector machines in the 1990s (Cortes and Vapnik, 1995). Today cross-entropy is probably the most heavily optimised function in history, since it is the training objective of every large language model.
Try it
- For the five deliveries, compute the Huber loss (δ = 1) of guessing 13 by hand. The code says 8.20. Which of the five errors are in the squared zone?
- In the outlier example, change
-= 30to-= 300. How do the three slopes change? Which loss is affected most?- A model gives probability 0.99 to the wrong class. What is its cross-entropy loss on that example? What would squared error on the probability give?
Hint for 1: the errors 0 and −1 are in the squared zone (at exactly 1 both formulas give 0.5). The others cost .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Probabilistic Machine Learning
A comprehensive two-volume reference viewing ML through probability. Free drafts online.
scikit-learn: Metrics and Scoring
Every classification, regression and ranking metric in scikit-learn (accuracy, precision, recall, ROC AUC, log loss, MSE, R² and more) with definitions and advice on choosing one.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/loss-functions.md