Lesson 3 of 12 · The Setup
Loss Functions
How models score their own mistakes: squared, absolute and Huber loss for regression, log loss for classifiers, and how the loss you choose shapes the model.
- 14 min read
- Intermediate
- Reviewed
- Explain what a loss function is and how training uses it
- Compute squared and absolute error, and see how each treats a big miss
- Show that the choice of loss changes what the best prediction is
- Compute log loss and explain why it punishes confident mistakes
- Tell a loss (what training minimises) from a metric (what you report)
The idea in plain words
In Learning From Labels, training was a search for the rule that best matches the labels. To search, the computer needs a precise score for "how wrong is this rule?". That score is the loss.
Training adds up the loss over every training example and adjusts the parameters until the average loss is as small as possible. Different loss functions disagree about which mistakes matter most, so the loss you choose quietly decides what kind of model you get.
The two classic losses for regression are:
error = prediction − actual
squared loss = error² (an error of 2 costs 4; an error of 30 costs 900)
absolute loss = |error| (an error of 2 costs 2; an error of 30 costs 30)
average loss = (loss of example 1 + … + loss of example n) ÷ nTry being the training algorithm. Move the sliders to find the line with the smallest total squared error for these 16 deliveries; the chart compares your line with the best possible one, which is exactly what LinearRegression finds.
Squared and absolute error
Here are five delivery-time predictions. Four are close; the last one is off by half an hour:
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
actual = np.array([30, 25, 40, 35, 28]) # delivery times in minutes
predicted = np.array([32, 24, 37, 36, 58]) # the last prediction is far off
errors = predicted - actual
print("errors: ", errors)
print("squared errors: ", errors ** 2)
print("absolute errors:", np.abs(errors))
print(f"MSE = {np.mean(errors ** 2):.1f} sklearn: {mean_squared_error(actual, predicted):.1f}")
print(f"MAE = {np.mean(np.abs(errors)):.1f} sklearn: {mean_absolute_error(actual, predicted):.1f}")
print(f"Share of the squared error from the last prediction: {errors[-1] ** 2 / np.sum(errors ** 2):.0%}")errors: [ 2 -1 -3 1 30] squared errors: [ 4 1 9 1 900] absolute errors: [ 2 1 3 1 30] MSE = 183.0 sklearn: 183.0 MAE = 7.4 sklearn: 7.4 Share of the squared error from the last prediction: 98%
The average of the squared errors is the MSE (mean squared error), and the average of the absolute errors is the MAE (mean absolute error), which you met as a metric in Introduction to Machine Learning. Squaring turns the miss of 30 into 900, which is 98% of the total. A model trained on squared error will therefore work very hard to avoid big misses, even if that makes many small errors slightly worse. Absolute error counts the big miss as just 30, in proportion to its size.
The loss decides what "best" means
The simplest possible model predicts the same number for every example. Which constant is best? It depends on the loss. Nine deliveries, one of them very late:
import numpy as np
times = np.array([22, 25, 25, 27, 28, 30, 31, 33, 94]) # one very late delivery
candidates = np.arange(20, 60.5, 0.5) # constant predictions to try
mse = [np.mean((times - c) ** 2) for c in candidates]
mae = [np.mean(np.abs(times - c)) for c in candidates]
print("Best constant for squared error: ", candidates[np.argmin(mse)], "| mean: ", times.mean())
print("Best constant for absolute error:", candidates[np.argmin(mae)], "| median:", np.median(times))Best constant for squared error: 35.0 | mean: 35.0 Best constant for absolute error: 28.0 | median: 28.0
Under squared error the best constant is 35 minutes, exactly the mean. Under absolute error it is 28 minutes, exactly the median. That is no coincidence: the mean always minimises squared error and the median always minimises absolute error. One 94-minute delivery drags the mean well above every other delivery time, while the median stays with the typical delivery.
Drag the slider to change the last delivery and watch the two lines:
So models trained with squared error aim for the average outcome, and models trained with absolute error aim for the typical outcome. Neither is wrong. Choose squared error when big misses are especially costly, and absolute error when rare extreme values shouldn't pull every prediction towards them.
Huber loss: a compromise
Huber loss, with a switch-over point δ:
if |error| ≤ δ: ½ × error²
otherwise: δ × (|error| − ½ × δ)The program below creates 40 readings that follow a line with slope 3, then corrupts four of them with a huge error, as a faulty sensor might. It fits one model with squared error and one with Huber loss:
import numpy as np
from sklearn.linear_model import HuberRegressor, LinearRegression
rng = np.random.RandomState(1)
x = rng.uniform(0, 10, size=40)
y = 3 * x + 5 + rng.normal(0, 1, size=40) # the true slope is 3
y[:4] = y[:4] + 60 # four readings with a huge error
X = x.reshape(-1, 1)
squared = LinearRegression().fit(X, y)
huber = HuberRegressor().fit(X, y)
print(f"Squared error (LinearRegression): slope {squared.coef_[0]:.2f}, intercept {squared.intercept_:.2f}")
print(f"Huber loss (HuberRegressor): slope {huber.coef_[0]:.2f}, intercept {huber.intercept_:.2f}")Squared error (LinearRegression): slope 2.37, intercept 13.95 Huber loss (HuberRegressor): slope 3.01, intercept 5.09
Four bad readings out of forty dragged the squared-error line well away from the truth (slope 2.37 instead of 3, intercept 13.95 instead of 5). The Huber line recovered the real pattern almost exactly, because beyond the switch-over point each bad reading only counts in proportion to its size. In HuberRegressor, the epsilon setting controls where the switch happens.
Loss for classifiers: log loss
For a classifier, the simplest loss is to count mistakes: 1 for a wrong class, 0 for a right one. Its average is just 1 minus the accuracy. It makes a poor training loss for two reasons. It can't tell a confident mistake from a near miss, and it gives the search no direction: nudging a parameter slightly almost never changes any predicted class, so the score stays flat and the search can't tell which way is better.
Classifiers are trained on log loss instead, which looks at the probability the model gave to the true class:
import math
from sklearn.metrics import accuracy_score, log_loss
# Log loss of one prediction: -log(probability given to the TRUE class)
for p in [0.99, 0.9, 0.7, 0.5, 0.3, 0.1, 0.01]:
print(f"probability of the true class {p:<4} -> loss {-math.log(p):.2f}")
y_true = [1, 1, 0, 0, 1]
careful = [0.8, 0.7, 0.3, 0.2, 0.4] # probability of class 1
overconfident = [0.99, 0.99, 0.01, 0.01, 0.01]
for name, p in [("careful", careful), ("overconfident", overconfident)]:
classes = [1 if q >= 0.5 else 0 for q in p]
print(f"{name:<13} accuracy {accuracy_score(y_true, classes):.1f} log loss {log_loss(y_true, p):.3f}")probability of the true class 0.99 -> loss 0.01 probability of the true class 0.9 -> loss 0.11 probability of the true class 0.7 -> loss 0.36 probability of the true class 0.5 -> loss 0.69 probability of the true class 0.3 -> loss 1.20 probability of the true class 0.1 -> loss 2.30 probability of the true class 0.01 -> loss 4.61 careful accuracy 0.8 log loss 0.415 overconfident accuracy 0.8 log loss 0.929
A confident correct prediction (0.99) costs almost nothing, a 50/50 guess costs 0.69, and a confident mistake (0.01 for the true class) costs 4.61, more than six times as much. Both models get the same four of five examples right, so their accuracy is the same 0.8. But the overconfident model said 0.01 for the last example, whose true class was 1, and log loss charges it heavily for that: 0.929 against 0.415. Log loss rewards honest probabilities, which is why the probabilities of a model trained on it tend to be meaningful.
Loss vs metric
- The loss is what the training algorithm minimises. It has to change smoothly as the parameters change, so the search can tell which way to move.
- The metric is what you report and make decisions with: accuracy, recall, MAE in minutes. It should match what mistakes cost in the real world.
They are often different. Logistic regression trains on log loss, and you then report its recall. That's fine, as long as the loss pushes the model in a direction the metric rewards.
| Model | Loss it minimises during training |
|---|---|
LinearRegression | Squared error |
Ridge, Lasso | Squared error plus a penalty on large weights (see Linear Models) |
HuberRegressor | Huber loss |
LogisticRegression | Log loss plus a penalty on large weights |
SVC (support vector machine) | Hinge loss, which also penalises correct predictions that sit too close to the boundary |
HistGradientBoostingRegressor, ...Classifier | Squared error and log loss by default; change with loss= |
DecisionTreeRegressor | Squared error by default (criterion="squared_error") |
Common mistakes
Practice
Compute the log loss of four predictions by hand.
import math
labels = [1, 0, 1, 1] # the true classes
p_one = [0.9, 0.2, 0.6, 0.99] # predicted probability of class 1
# Log loss = the average of -log(probability given to the TRUE class).
# For label 1 that probability is p; for label 0 it is 1 - p.
# Print it with three decimals, for example:
# Log loss: 0.123
losses = []
print(f"Log loss: {sum(losses):.3f}")
Your labels include a few extreme values that are real but rare, and you don't want them to pull every prediction towards them. Which training loss suits this best?
Summary
- A loss function scores how wrong each prediction is; training minimises the average loss on the training data.
- Squared error makes big misses dominate and aims for the mean; absolute error treats errors in proportion and aims for the median; Huber loss is a compromise that resists outliers.
- Classifiers train on log loss, which charges heavily for confident mistakes and so rewards honest probabilities.
- The loss is what training minimises; the metric is what you report. Choose both to match what mistakes really cost.
Next: Generalisation, or how to tell whether a model that fits its training data will also work on new data.
Finished reading? Tick it off to track your progress.