What learning is · lesson 7 of 13
Parts in this lesson
A((y_true - y_pred) ** 2).mean()mean squared error
Bnp.abs(y_true - y_pred).mean()mean absolute error
Cmean_squared_error, mean_absolute_error, zero_one_lossthe same, from sklearn.metrics

Loss functions

Last updated

To learn, a model needs a number that says how wrong it is: its loss. Different losses punish different mistakes, and choosing one is choosing what “good” means for your problem. This lesson measures the error on one example, then averages it three ways, squared, absolute and 0–1, and shows how one typo in the data can drag a squared-error model a long way.

By the end of this lesson you can

  • Compute the error, squared error, absolute error and 0–1 loss for one example
  • Compute mean squared error and mean absolute error, by hand and with scikit-learn
  • Explain why squared error is pulled by outliers and absolute error isn’t, and choose between them

Error on one example

A model predicts a penguin weighs 3,900 g; it really weighs 4,200 g. Its error (or residual) is the true value minus the prediction:

e=y−yˆ

In words: how far the prediction fell short. Here 4,200−3,900=300 g. A positive error means the guess was too low; a negative one, too high. In NumPy: y_true - y_pred.

A loss function turns that error into a single "how bad" number, always 0 or more, and 0 for a perfect prediction. The sign has to go: a guess 300 g too high is as bad as one 300 g too low.

Squared error and absolute error

The two standard ways to drop the sign:

squared error=(y−yˆ)2,absolute error=|y−yˆ|

In words: square the error, or take its size without the sign. In NumPy: (y_true - y_pred) ** 2 and np.abs(y_true - y_pred).

loss.ipynb

The 300 g miss has an absolute error of 300 g and a squared error of 90,000 g². The big difference is how they grow. Double the error and the absolute error doubles; the squared error goes up four times. Squared error barely minds small misses and hates big ones. Drag the guess on the ruler and watch the two columns:

Loss rulerone guess for every fare
10152025303540guess 15
FareErrorAbsoluteSquared
13−224
13−224
15000
15000
17224
18339
205525
AverageMAE 2MSE 6.57

MSE is smallest at the mean, 15.86; MAE is smallest at the median, 15.

0–1 loss, for classes

For classification there's no "how far": a penguin labelled Adelie that's really a Gentoo is just wrong. The 0–1 loss is 0 for a right answer and 1 for a wrong one:

ℓ0–1(y,yˆ)=𝟙[y≠yˆ]

In words: 1 if the prediction differs from the truth, else 0 (the same 𝟙 as in lesson 2.5's accuracy).

loss.ipynb

Its average over a dataset is the share labelled wrong: one minus accuracy. It's the loss you usually care about for a classifier, but models are rarely trained on it, because a small change to a model almost never changes it, so it gives gradient descent nothing to follow. Classifiers are trained on cross-entropy instead (lesson 1.11), and scored on 0–1 loss or the measures in lesson 2.8.

Average loss over the data

A model is judged on many examples, so the losses are averaged. The two most used averages have their own names:

MSE=1n∑i=1n(yi−yˆi)2,MAE=1n∑i=1n|yi−yˆi|

In words: the mean squared error is the average squared error; the mean absolute error is the average absolute error. In NumPy: ((y_true - y_pred) ** 2).mean() and np.abs(y_true - y_pred).mean(). scikit-learn has both, and zero_one_loss for classes:

average.ipynb

MAE is in the data's own units: these five predictions are 230 g out, on average. MSE is in squared units (g²), like a variance (lesson 1.10), so people often report its square root, the RMSE, here 113,500≈337 g. RMSE is bigger than MAE because the one 700 g miss counts extra once squared. The 0–1 loss of 0.25 means one label in four was wrong.

Stage 3 trains its first models by making MSE as small as possible, because squared error has a smooth slope everywhere, which gradient descent needs.

Wrong way: squared error and one huge outlier

Here's the simplest possible model: one number, the same guess for every example. Which guess makes each loss smallest? For seven jeepney fares, try every guess from 10 to 40 pesos:

outlier.ipynb

Squared error is smallest at 16, next to the mean, 15.86. (The search goes in steps of 0.5, so it can only land near 15.86.) Absolute error is smallest at 15, the median. That's no coincidence: the mean is exactly the guess that minimises squared error, and the median the one that minimises absolute error.

Now someone types 150 instead of 15:

outlier.ipynb

The best guess under squared error jumps to 32.5, more than double any real fare, because one squared miss of over 100 pesos outweighs all the others put together. The best guess under absolute error is still 15. (Any guess from 15 to 17 gives the same MAE now; the search reports the first.)

So if your data may contain outliers you can't clean out, or a few huge misses aren't much worse than several small ones, MAE (or a loss built like it) is the safer choice. If big misses really are much worse, a house price off by ₱5 million matters more than five off by ₱1 million, squared error says so. Either way, look at your data first: the typo should be fixed, not modelled.

Check what you learned

Predictions are 10 and 20; the truth is 12 and 17. What is the MAE?
Predict, then check with the loss ruler: one error doubles from 3 to 6. What happens to its squared error?
Delivery times have a few huge delays caused by typhoons, which you can’t remove. Which loss lets them pull a model least?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning