Sub topic 1
Prediction Errors, MAE, MSE, and RMSE
Prerequisites
This chapter assumes basic Python and NumPy, familiarity with means and square roots, and a general understanding of regression models and train/test splits.
Prediction errors: the raw material of every metric
A regression model predicts a numeric value, such as a house price. For observation \(i\), the residual is the prediction minus the actual value:
\[ ei = \hat{y}i - y_i \]
A positive residual means the model overpredicted. A negative residual means it underpredicted. The residual's unit is the target's unit. For house prices, a residual might be measured in dollars.
For actual values [3.0, 5.0, 2.5, 7.0] and predictions [2.5, 5.0, 4.0, 8.0], the residuals are [-0.5, 0.0, 1.5, 1.0].
MAE: the average size of the error
Mean Absolute Error (MAE) is the average absolute residual:
\[ \mathrm{MAE} = \frac{1}{n}\sum{i=1}^{n}|ei| \]
Absolute values remove the signs, so overpredictions and underpredictions cannot cancel each other. In this example:
\[ \mathrm{MAE} = (0.5 + 0 + 1.5 + 1.0) / 4 = 0.75 \]
The MAE is in the target's original units. You can interpret it as the model's average distance from the correct value.
MSE and RMSE: squaring errors, then returning to original units
Mean Squared Error (MSE) averages squared residuals:
\[ \mathrm{MSE} = \frac{1}{n}\sum{i=1}^{n}ei^2 \]
Here, MSE is:
\[ (0.25 + 0 + 2.25 + 1.0) / 4 = 0.875 \]
MSE uses squared target units, which can make it harder to interpret. Root Mean Squared Error (RMSE) takes its square root:
\[ \mathrm{RMSE} = \sqrt{\mathrm{MSE}} = \sqrt{0.875} \approx 0.935 \]
RMSE is therefore in the original target units. Squaring makes large errors count more heavily. A residual of 4 contributes 16 to the squared-error total, while a residual of 1 contributes only 1.
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
mae = np.mean(np.abs(residuals))
mse = np.mean(residuals ** 2)
rmse = np.sqrt(mse)
print(residuals)
print(f"MAE={mae:.3f}, MSE={mse:.3f}, RMSE={rmse:.3f}")Exercise
For residuals [-2, 1, 1], calculate the MAE and RMSE. Which metric penalizes the residual of -2 more strongly?
Show answer
MAE is 4/3, or about 1.33. RMSE is sqrt(2), or about 1.41. RMSE penalizes the -2 residual more strongly because it squares residuals.