Section 2 · Lesson 2
Measuring regression error: MAE, RMSE and R²
Score regression models on held-out data with MAE, RMSE and R², and compare them with a predict-the-mean baseline.
A regression model is never exactly right, so the question is how wrong it is, in which way, and compared with what. Three metrics cover almost every situation. All of them start from the errors on the test set:
error = actual - predicted
MAE: the typical miss
MAE = mean(|error|)
Mean absolute error is in the same units as the target (“off by 15 conversions a day, on average”), and it treats a miss of 20 as exactly twice as bad as a miss of 10. It’s the easiest metric to explain to a stakeholder.
RMSE: punishing big misses
MSE = mean(error²)
RMSE = sqrt(MSE)
Squaring makes large errors dominate, then the square root brings the result back to the target’s units. RMSE is always at least as large as MAE, and a big gap between them means a few large misses. Use RMSE when big errors are disproportionately costly, such as underestimating demand for a sell-out product. Least-squares regression minimizes exactly this quantity on the training data.
R²: share of variation explained
SSE = sum(error²) # the model's squared errors
SST = sum((actual - mean(actual))²) # squared errors of always predicting the mean
R² = 1 - SSE / SST
R² compares the model with the simplest possible predictor, the mean. R² = 1 is perfect, R² = 0 is no better than the mean, and on test data R² can be negative when a model is worse than the mean. Because it has no units, it’s handy for comparing models of the same target. It doesn’t say whether the errors are small enough to be useful. An R² of 0.5 can be excellent for noisy daily data and poor for a physical process.
Baselines for regression
DummyRegressor(strategy="mean") predicts the training mean for every row, so its test R² is
about 0 and its MAE is the number to beat. For our clicks → conversions line, on a 75/25 split:
| Model | Test MAE | Test RMSE | Test R² |
|---|---|---|---|
| Predict the mean | 23.3 | 30.7 | 0.00 |
| Linear regression on clicks | 15.0 | 21.7 | 0.50 |
The model cuts the typical error by about 36%. That’s a real improvement, but a miss of 15 conversions on an average day of 27 is still large. The residual patterns from the last lesson explain why, and the next lesson fixes much of it.
Train versus test scores
Compute metrics on data the model didn’t learn from. Here the training R² (0.45) happens to be lower than the test R² (0.50), purely because of which campaign-days landed in each split. More often the training score is higher, and a large gap is a sign of overfitting. With small test sets, metrics bounce around from split to split, which is why the final section introduces cross-validation.
In Python
from sklearn.metrics import mean_absolute_error, root_mean_squared_error, r2_score
pred = model.predict(X_test)
mean_absolute_error(y_test, pred)
root_mean_squared_error(y_test, pred)
r2_score(y_test, pred) # same as model.score(X_test, y_test)
A warning about MAPE (mean absolute percentage error): it divides by the actual value, so it breaks when actuals are zero, and campaign-days with zero conversions are common here. Prefer MAE or RMSE for counts that can be zero.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Score the line on test data
DoneSplit X = ds[["clicks"]] and y = ds["conversions"] with train_test_split(X, y, test_size=0.25, random_state=42), fit a LinearRegression on the training part and predict the test part.
Compute these test-set metrics yourself with NumPy from errors = y_test - pred, each rounded to 3 decimals:
mae: mean absolute errorrmse: root mean squared errorr2:1 - SSE / SST, where SSE is the sum of squared errors and SST is the sum of squared
differences between y_test and its mean
Then check your numbers against scikit-learn's mean_absolute_error, root_mean_squared_error and r2_score.
Need a hint?
np.abs(errors)anderrors ** 2work element by element on a Series.- SST uses the test set's own mean:
np.sum((y_test - y_test.mean()) ** 2).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, root_mean_squared_error, r2_score
ds = pd.read_csv("daily_stats.csv")
X = ds[["clicks"]]
y = ds["conversions"]
# TODO: split, fit on the training part, predict the test part
mae = None
rmse = None
r2 = None
print(mae, rmse, r2)
Files in the working directory
audience.csv (5,000 rows)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)How much better than the mean?
DoneOn the same split, fit a DummyRegressor(strategy="mean"), which always predicts the training mean. Each rounded to 3 decimals:
baseline_mae,baseline_r2: the baseline's MAE and R² on the test setmodel_mae: the linear regression's test MAEmae_improvement:(baseline_mae - model_mae) / baseline_mae, computed from the
unrounded MAEs, as a fraction
Need a hint?
DummyRegressoruses the same API as any model:.fit(X_train, y_train)then.predict(X_test).- Keep the unrounded MAEs in their own variables and round only when you assign the final answers.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error, r2_score
ds = pd.read_csv("daily_stats.csv")
X_train, X_test, y_train, y_test = train_test_split(
ds[["clicks"]], ds["conversions"], test_size=0.25, random_state=42
)
model = LinearRegression().fit(X_train, y_train)
baseline_mae = None
baseline_r2 = None
model_mae = None
mae_improvement = None
print(baseline_mae, baseline_r2, model_mae, mae_improvement)
Files in the working directory
audience.csv (5,000 rows)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)