MLDay 5 of 50Foundations
Measure Error
MSE, RMSE and MAE
Two models predict tomorrow's bike rentals. One is off by a few bikes every hour. The other is spot on most hours, then misses the evening rush by 300. Which is better depends on what a miss costs you, and you need a single score to say so.
The idea
A model's error on one row is its residual: the real value minus the prediction (Day 4). To score a whole model, you squash all the residuals into one number. There are two common ways.
- MAE (mean absolute error) drops the signs and averages the misses. Every bike you're off counts the same.
- RMSE (root mean squared error) squares each miss, averages the squares, then takes the square root. Squaring makes a miss of 10 count 100 times as much as a miss of 1, so big misses dominate.
Both come out in the same units as the target, here rentals per hour. The average of the squares, before the root, is MSE (mean squared error). Its units are rentals squared, which is hard to read, but it's the number least squares makes as small as it can.
So pick the measure that matches the cost. If every missing bike loses one rental fee, use MAE. If one empty dock at rush hour costs you a customer for good, use RMSE.
A score alone means little. Compare it with a baseline: the dumbest model you could ship, such as always predicting the average. A real model has to beat it.
A tiny example
Two models each predict four hours. Their misses, in bikes:
| Model | Misses | MAE | RMSE |
|---|---|---|---|
| Steady | 3, 3, 3, 3 | 12 ÷ 4 = 3 | √(36 ÷ 4) = √9 = 3 |
| Spiky | 1, 1, 1, 9 | 12 ÷ 4 = 3 | √(84 ÷ 4) = √21 ≈ 4.58 |
MAE calls them equal. RMSE says the spiky model is worse, because its one miss of 9 squares to 81. That is almost all of its total of 84.
The formula
| Symbol | Meaning |
|---|---|
| the number of rows | |
| the real value in row | |
| the model's prediction for row | |
| the residual: the miss in row | |
| add up over every row, from to | |
| the absolute value: drop the minus sign |
Worked, the spiky model: , and . MSE is RMSE before the root: 21.
Try it
One festival hour: do RMSE and MAE agree?
Move the sliders until the red gaps (the residuals) are as small as you can get them.
ŷ = 3·x + 0RMSE 189.77
These are Day 4's dock hours plus a 30 °C hour and one festival hour: 420 rentals at 15 °C. Line up with the six ordinary hours (near , ) and use the pills to note both scores: MAE about 47, RMSE about 99. Then press Show the best line under RMSE. It floats up toward the festival, which drops RMSE to about 93 but raises MAE to about 65. Switch to MAE and press it again: this best line ignores the festival and sits on the ordinary hours (MAE about 45). Each measure has its own best line.
In code
First, the three measures written from scratch on the tiny example, checked against scikit-learn.
# script_id: day_005_measuring_error/from_scratch
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error, root_mean_squared_error
def mae(y, y_hat):
return np.mean(np.abs(y - y_hat))
def mse(y, y_hat):
return np.mean((y - y_hat) ** 2)
def rmse(y, y_hat):
return np.sqrt(mse(y, y_hat))
y = np.array([50, 120, 150, 190]) # real rentals in four hours
steady = y - np.array([3, -3, 3, -3]) # misses by 3 every hour
spiky = y - np.array([1, -1, 1, -9]) # misses by 1, 1, 1, then 9
for name, y_hat in [("steady", steady), ("spiky", spiky)]:
print(f"{name}: MAE {mae(y, y_hat):.2f} MSE {mse(y, y_hat):.2f} RMSE {rmse(y, y_hat):.2f}")
print("scikit-learn agrees:",
np.isclose(mae(y, spiky), mean_absolute_error(y, spiky)),
np.isclose(mse(y, spiky), mean_squared_error(y, spiky)),
np.isclose(rmse(y, spiky), root_mean_squared_error(y, spiky)))
steady: MAE 3.00 MSE 9.00 RMSE 3.00
spiky: MAE 3.00 MSE 21.00 RMSE 4.58
scikit-learn agrees: True True True
Now Day 4's temperature line on all 17,379 hours, against a baseline that always predicts the average.
# script_id: day_005_measuring_error/bikes
import os
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score, root_mean_squared_error
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
X, y = df[["temp"]] * 41, df["cnt"] # °C, rentals per hour
line = LinearRegression().fit(X, y).predict(X) # Day 4's line
baseline = np.full(len(y), y.mean()) # always guess the average
for name, y_hat in [("mean baseline", baseline), ("temperature line", line)]:
print(f"{name:16} MAE {mean_absolute_error(y, y_hat):6.1f} "
f"RMSE {root_mean_squared_error(y, y_hat):6.1f} R² {r2_score(y, y_hat):.3f}")
mean baseline MAE 142.4 RMSE 181.4 R² 0.000
temperature line MAE 125.5 RMSE 165.9 R² 0.164
The line beats the baseline, but only by about 16 bikes an hour on RMSE. RMSE sits above MAE because a few hours have very large misses: the rush hours a temperature-only line can't see.
The last column, , compares the model's MSE with the baseline's: . The baseline scores 0 and a perfect model scores 1. Here : the line removes about 16% of the baseline's squared error.
Quick check
Quick check
1. Model A misses by 2, 2, 2, 2. Model B misses by 0, 0, 0, 8. Which statement is true?
2. Each bike you're short costs one lost rental, no matter how big the miss. Which measure matches that cost?
3. A model scores R² = 0 on the bike data. What does that mean?
Next
These scores come from the same hours the line learned from, which flatters it. Day 6: Split Data Without Leaking scores on hours the model never saw.
Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.