◆ AI All-in-One

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
↗ Plan a path here

Read first

Linear Regression

This leads to

—
The full path from zero — 9 concepts before this one
  1. What Is AI?
  2. Derivatives and Slopes
  3. Vectors
  4. How Machines Learn
  5. Partial Derivatives and Gradients
  6. Supervised, Unsupervised and Reinforcement Learning
  7. Gradient Descent
  8. Supervised Learning
  9. Linear Regression
  10. 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, yy is the true label, y^\hat{y} the prediction, and the residual r=y^−yr = \hat{y} - y 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:

LMSE=1N∑i=1N(y^i−yi)2L_{\text{MSE}} = \frac{1}{N}\sum_{i=1}^{N} (\hat{y}_i - y_i)^2

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:

LMAE=1N∑i=1N∣y^i−yi∣L_{\text{MAE}} = \frac{1}{N}\sum_{i=1}^{N} \lvert \hat{y}_i - y_i \rvert

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 ("delta") it is squared, and above it, it is absolute:

Lδ(r)={12r2if ∣r∣≤δδ(∣r∣−12δ)otherwiseL_{\delta}(r) = \begin{cases} \tfrac{1}{2} r^2 & \text{if } \lvert r \rvert \le \delta \\ \delta \left(\lvert r \rvert - \tfrac{1}{2}\delta\right) & \text{otherwise} \end{cases}

The two pieces join smoothly at ∣r∣=δ\lvert r \rvert = \delta. Small errors get the smooth, well-behaved squared treatment, and large ones are only charged linearly. You choose δ\delta to say where "normal noise" ends and "outlier" begins.

-3 -2 -1 0 1 2 3 1 2 3 4 residual r = ŷ − y loss δ Squared error r² MSE. Big misses dominate: an error of 3 costs 9 Absolute error |r| MAE. Every unit of error costs the same Huber (δ = 1) squared for small errors, absolute for big ones All three are 0 when the prediction is exact and grow as it misses in either direction.
Fig. 1 Three regression losses plotted against the residual. Squared error (red) explodes for large misses. Absolute error (blue) grows in a straight line. Huber (green, dashed) is squared inside the band from −δ to δ and straight outside it.

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.

0 2 4 6 8 10 -10 0 10 20 x y 4 corrupted points 30 too low (a data-entry error?) Squared error fit slope 0.82: dragged down by the four outliers Huber fit slope 2.00: shrugs them off True line y = 2x + 1, grey dashes, almost hidden under Huber
Fig. 2 Fitting a line to data with four corrupted points at the right. Least squares (red) is dragged far off the true line by the outliers. Huber loss (green) all but ignores them and recovers the true slope of 2.

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 pp that the example belongs to the positive class (label y=1y = 1 rather than y=0y = 0). The standard loss is cross-entropy, here in its two-class form, binary cross-entropy (also called log loss):

LCE=−1N∑i=1N[ yiln⁡pi+(1−yi)ln⁡(1−pi) ]L_{\text{CE}} = -\frac{1}{N}\sum_{i=1}^{N} \Big[\, y_i \ln p_i + (1 - y_i) \ln(1 - p_i) \,\Big]

It looks fiddly, but only one of the two terms is ever active. If the true label is 1 the loss is −ln⁡p-\ln p. If it is 0 the loss is −ln⁡(1−p)-\ln(1-p). Either way it is minus the log of the probability the model gave to the right answer. (ln⁡\ln is the natural logarithm.)

That has a sharp effect. Three examples, all truly positive, with predicted probabilities 0.9, 0.6 and 0.1:

pp for the true class Loss −ln⁡p-\ln p
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 pp 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, −ln⁡(probability of the true class)-\ln(\text{probability of the true class}), 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 m=y⋅sm = y \cdot s, where the label is coded as y=+1y = +1 or −1-1 and ss 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, ln⁡(1+e−m)\ln(1 + e^{-m}), is cross-entropy rewritten in terms of the score. It never quite reaches zero, so it always rewards a bit more confidence.
  • Hinge loss, max⁡(0,1−m)\max(0, 1 - m), 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.
-2 -1 0 1 2 3 1 2 3 margin m = y · s loss wrong side right side → 0–1 loss 1 if wrong, 0 if right. What we care about, but flat, so it has no useful gradient Hinge max(0, 1 − m) SVMs. Zero once the example is right by a margin of 1 Logistic log₂(1 + e⁻ᵐ) cross-entropy on the score. Never quite zero: always rewards more confidence y = ±1 is the true class, s the model's score; m > 0 means correct
Fig. 3 Classification losses as a function of the margin. The 0–1 loss (grey) jumps from 1 to 0 at the boundary and gives no gradient. Hinge (orange) and logistic (purple) are smooth upper bounds that push examples to the correct side and beyond.

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_weight or sample_weight for 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 Ldata+λ⋅penaltyL_{\text{data}} + \lambda \cdot \text{penalty}.

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.CrossEntropyLoss expects 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

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

  1. 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?
  2. In the outlier example, change -= 30 to -= 300. How do the three slopes change? Which loss is affected most?
  3. 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 ∣r∣−0.5\lvert r \rvert - 0.5.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Five deliveries took 10, 12, 13, 15 and 50 minutes. You must predict one number. Which guess minimises mean absolute error?

  2. Your data has a few sensor glitches that produce wild values. Which loss keeps them from distorting the fit while staying smooth for small errors?

  3. Why don't we train classifiers directly on 0-1 loss (the error rate)?

  4. A positive example gets predicted probability 0.1. What is its cross-entropy loss, roughly?

  5. You need a demand forecast that gives enough stock 90% of the time, not the average. Which loss fits?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Book

Probabilistic Machine Learning

Kevin P. Murphy · Advanced · Free

A comprehensive two-volume reference viewing ML through probability. Free drafts online.

Docs

scikit-learn: Metrics and Scoring

scikit-learn · Intermediate · Free

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.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Video

StatQuest

Josh Starmer · Beginner · Free

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