Sub topic 1
Prediction errors: the raw material of every metric
Every regression metric in this tutorial is a summary of one list of numbers: the errors a model makes on individual examples. MAE, MSE, RMSE and R squared all start from that list and differ only in how they compress it into a single score. This chapter defines the list precisely, shows how to compute it, and covers the details that cause bugs later. Those details are the sign convention, units, shape mismatches and the data the errors come from.
Prerequisites
This chapter assumes you have:
- Basic Python and NumPy array operations, including element-wise arithmetic and
np.mean. - Familiarity with averages (the mean) and square roots.
- A general idea of what a regression model does: it predicts a numeric target such as a price, a temperature or a delivery time.
- Basic awareness that data is split into training and test sets.
You do not need any statistics beyond the mean. Later chapters define MAE, RMSE and R squared from scratch.
What a residual is
A regression model takes the input features of one example and returns a number, the prediction. The true value for that example is the target. The difference between the two is the prediction error, usually called the residual.
This tutorial uses one convention throughout:
residual = predicted value - true valueWith this convention the sign has a direct meaning:
- A positive residual means the model over-predicted. It guessed too high.
- A negative residual means the model under-predicted. It guessed too low.
- A residual of zero means the prediction was exact.
Many textbooks and some libraries define the residual the other way around, as true minus predicted. This flips every sign but changes nothing else about the metrics in this tutorial, because they either use absolute values or square the errors. Any metric that keeps the sign, such as the mean error in the next section, will flip its sign too. When you read someone else's code or report, check which direction they used before you interpret a "positive error".
A worked example
Take four examples. A model predicts a numeric target, and we know the true values.
| Example | True value | Prediction | Residual (prediction - true) |
|---|---|---|---|
| 1 | 3.0 | 2.5 | -0.5 |
| 2 | 5.0 | 5.0 | 0.0 |
| 3 | 2.5 | 4.0 | 1.5 |
| 4 | 7.0 | 8.0 | 1.0 |
Example 1 is under-predicted by half a unit. Example 2 is exact. Examples 3 and 4 are over-predicted by 1.5 and 1.0. The same numbers in NumPy:
import numpy as np
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
residuals = y_pred - y_true
print(residuals) # [-0.5 0. 1.5 1. ]
print(residuals.mean()) # 0.5NumPy subtracts the two arrays element by element, so residuals[i] is the error for example i. The whole array is the raw material. Every metric in the next chapters is a function of this array, and R squared also needs the spread of y_true.
The next diagram shows where the residuals sit in the evaluation process.
Units: the residual speaks the target's language
A residual has the same unit as the target. If the model predicts house prices in dollars, residuals are in dollars. If it predicts temperature in degrees Celsius, residuals are in degrees Celsius. A residual of 1.5 means nothing until you know what is being predicted. Compare "off by 1.5 degrees" with "off by 1.5 dollars" with "off by 1.5 million dollars".
This matters for two reasons.
- Absolute-error summaries can be read directly in the target's unit. MAE is one example, and the next chapter covers it. A stakeholder can understand "the model is typically off by about 0.75 degrees" without any statistics.
- Metrics from different targets cannot be compared directly. An error of 2 on a target that ranges from 0 to 10 is large. An error of 2 on a target that ranges from 0 to 10,000 is tiny. Before you compare scores across datasets, think about the scale of the target.
Squared errors, which come in the RMSE chapter, have squared units (dollars squared). That is why RMSE takes a square root at the end: it returns the score to the original unit.
Why not just average the residuals?
The obvious summary of a list of errors is their mean. For the example above, residuals.mean() is 0.5. That number is real and useful. It is called the mean error, or bias, and it tells you the model over-predicts by 0.5 on average. But as a measure of how wrong the model is, it fails because positive and negative residuals cancel.
import numpy as np
y_true = np.array([10.0, 10.0, 10.0, 10.0])
y_pred = np.array([8.0, 12.0, 7.0, 13.0])
residuals = y_pred - y_true # [-2. 2. -3. 3.]
print(residuals.mean()) # 0.0
print(np.abs(residuals).mean()) # 2.5The mean error is exactly 0.0, which would suggest a perfect model. But no prediction is within 2 units of the truth. The errors cancel out because the model is too high as often as it is too low.
The fix is to remove the sign before averaging. There are two standard ways:
- Take the absolute value of each residual. This leads to Mean Absolute Error (MAE).
- Square each residual. This leads to Mean Squared Error (MSE) and, after a square root, Root Mean Squared Error (RMSE).
Both choices discard direction and keep size. The two ways of measuring size have different consequences when a few errors are large, which is the subject of a later chapter. For now, keep the distinction in mind: mean error answers "is the model biased up or down?", and the other metrics answer "how large are the misses?" A model can have zero bias and still be useless.
Residuals as a diagnostic tool
Before reducing residuals to one number, look at them. A single metric hides structure that the raw list shows. Three quick checks are worth making on any model:
- Mean of the residuals. A value far from zero, compared with the typical residual size, indicates systematic bias. For ordinary linear regression with an intercept, residuals on the training data average to essentially zero by construction. On new data they do not have to.
- Largest absolute residuals. Sort by
np.abs(residuals)and look at the worst few examples. One or two huge misses often point to bad labels, data entry mistakes or a region of inputs the model has not seen. - Residuals against the prediction or a feature. If errors are positive for low predictions and negative for high ones, the model is not capturing the relationship's shape. Plotting residuals against predictions is the standard check for this.
import numpy as np
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
residuals = y_pred - y_true
worst = np.argsort(-np.abs(residuals))[:2]
print(worst) # [2 3]
print(residuals[worst]) # [1.5 1. ]np.argsort(-np.abs(residuals)) returns indices ordered from the largest absolute residual to the smallest. Here examples 2 and 3 (zero-based) are the worst misses, which matches the table above.
Shape bugs: the silent n-by-n error
The most common practical mistake in computing residuals is a shape mismatch. NumPy broadcasting is designed to be permissive, so it does not raise an error when you subtract a column vector from a row vector. It produces a matrix instead.
import numpy as np
y_true = np.array([3.0, 5.0, 2.5, 7.0]) # shape (4,)
y_pred_col = np.array([[2.5], [5.0], [4.0], [8.0]]) # shape (4, 1)
wrong = y_pred_col - y_true
print(wrong.shape) # (4, 4)
right = y_pred_col.ravel() - y_true
print(right.shape) # (4,)
print(right) # [-0.5 0. 1.5 1. ]The wrong result has 16 entries instead of 4. Taking the mean of it still gives a number, so nothing crashes. The number is simply wrong. It compares every prediction with every true value. This happens often when a model's predict returns shape (n, 1) (common with some deep learning libraries) while the target is a flat (n,) array.
A cheap guard is a helper that checks shapes before subtracting:
import numpy as np
def residuals(y_true, y_pred):
y_true = np.asarray(y_true, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
if y_true.shape != y_pred.shape:
raise ValueError(
f"shape mismatch: y_true {y_true.shape} vs y_pred {y_pred.shape}"
)
return y_pred - y_true
print(residuals([3.0, 5.0, 2.5, 7.0], [2.5, 5.0, 4.0, 8.0]))
# [-0.5 0. 1.5 1. ]The dtype=float conversion also protects against integer arrays, where subtraction of unsigned integer types can wrap around instead of going negative. For example, np.uint8(3) - np.uint8(5) does not give -2. Scikit-learn's metric functions perform their own shape checks and raise an error on mismatched lengths, but they will accept a (n, 1) array against a (n,) array in some cases. Do not rely on them to catch every shape problem.
Missing values and non-finite numbers
If either array contains NaN, the residual at that position is NaN, and np.mean of the whole array becomes NaN. Scikit-learn's metric functions raise a ValueError for NaN input instead of silently returning NaN. Neither behavior is a silent success. Decide deliberately how to handle missing predictions or missing labels. Drop those rows, impute them, or fix the pipeline upstream. Do not replace missing predictions with zero just to make the metric run, because that invents errors that the model did not make.
Which data the errors come from
A residual is only informative if it measures how the model behaves on data it will meet in use. Errors computed on the data the model was fitted to are usually optimistic. The model has already seen those examples, and a flexible model can memorize them. The residuals you care about come from held-out data: examples the model did not see during fitting. The chapter on held-out evaluation covers this in detail. For now, remember one rule: when someone gives you a metric, ask which data the residuals came from. A very low error on training data says little about future performance.
Quick reference
| Question | Answer |
|---|---|
| Residual formula in this tutorial | prediction - true value |
| Positive residual means | the model predicted too high |
| Negative residual means | the model predicted too low |
| Unit of a residual | the unit of the target |
| Why not report the plain mean residual? | positive and negative errors cancel, so it measures bias, not accuracy |
| Two ways to remove the sign | absolute value (MAE) or squaring (MSE, RMSE) |
| Most common code bug | `(n, 1)` against `(n,)` arrays broadcasting to `(n, n)` |
| Where residuals should come from | held-out data |
Exercises
Exercise
A model predicts the delivery time in minutes for four orders. The true times are [20, 35, 15, 40] and the predictions are [25, 30, 15, 50]. Using prediction minus true, compute the residuals, their mean, and the mean of their absolute values. What does the difference between the two means tell you?
Show answer
The residuals are [5, -5, 0, 10], in minutes. Their mean is (5 - 5 + 0 + 10) / 4 = 2.5 minutes, so the model over-predicts by 2.5 minutes on average (a small positive bias). The mean of the absolute values is (5 + 5 + 0 + 10) / 4 = 5.0 minutes, so the typical miss is 5 minutes. The two numbers differ because the +5 and -5 residuals cancel in the plain mean but not in the absolute mean. The plain mean measures bias, and the absolute mean measures the size of the errors.
Exercise
Your model's predict method returns an array of shape (100, 1), and your target y_test has shape (100,). You compute (pred - y_test).mean() and get a value close to zero, even though the model is poor. What went wrong, and how do you fix it?
Show answer
NumPy broadcasts the (100, 1) array against the (100,) array into a (100, 100) matrix of every prediction minus every true value. That matrix mixes unrelated pairs, and its mean sits near the difference between the average prediction and the average target, so it can look deceptively small. Fix it by flattening the predictions, for example pred.ravel() - y_test, and by checking that both shapes are equal before subtracting.