A regression model predicts numbers, such as a house price or a patient’s blood sugar, so it is never exactly right. The question is how wrong it is, and which kinds of mistake matter most. MAE, MSE, RMSE and R² each answer that question differently. Two models can rank in opposite orders depending on the metric, so choosing the right one is part of solving the problem.
In this lesson you will learn
- Mean absolute error (MAE)
- Mean squared error (MSE) and root mean squared error (RMSE)
- The coefficient of determination, R²
- How outliers affect each metric
- Comparing models with a baseline and cross-validation
You should know linear regression.
Four Metrics on the Same Predictions
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# House prices in lakh taka: true values and two models' predictions
y_true = np.array([50, 65, 80, 120, 150, 90])
model_a = np.array([55, 60, 85, 115, 145, 95]) # always off by about 5
model_b = np.array([50, 65, 80, 120, 100, 90]) # perfect except one big miss
for name, pred in [("Model A", model_a), ("Model B", model_b)]:
mae = mean_absolute_error(y_true, pred)
mse = mean_squared_error(y_true, pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_true, pred)
print(f"{name}: MAE={mae:5.2f} MSE={mse:6.1f} RMSE={rmse:5.2f} R2={r2:.3f}")
baseline = np.full_like(y_true, y_true.mean(), dtype=float)
print(f"Predicting the mean every time: R2={r2_score(y_true, baseline):.3f}")
Output
Model A: MAE= 5.00 MSE= 25.0 RMSE= 5.00 R2=0.978
Model B: MAE= 8.33 MSE= 416.7 RMSE=20.41 R2=0.632
Predicting the mean every time: R2=0.000
- MAE is the average size of the errors, ignoring their sign. Model A is off by 5 lakh on every house, so its MAE is 5.
- MSE averages the squared errors. Squaring punishes large errors heavily: Model B’s single 50-lakh miss gives an MSE of 416.7.
- RMSE is the square root of MSE, which brings the units back to lakh taka. It always sits between MAE and the largest single error.
- R² compares the model with the simplest possible one: always predicting the average. 1 is perfect, 0 is no better than the average, and negative values are worse than the average.
- Model B is perfect on five of six houses, but every metric prefers Model A here, MSE and RMSE most strongly, because B’s one large miss dominates.
Comparing Models
from sklearn.datasets import load_diabetes
from sklearn.dummy import DummyRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_validate
X, y = load_diabetes(return_X_y=True)
models = {
"Baseline (mean)": DummyRegressor(),
"Linear regression": LinearRegression(),
"Random forest": RandomForestRegressor(n_estimators=200, random_state=0),
}
scoring = {"mae": "neg_mean_absolute_error", "rmse": "neg_root_mean_squared_error", "r2": "r2"}
print(f"{'Model':18s} {'MAE':>7s} {'RMSE':>7s} {'R2':>6s}")
for name, model in models.items():
s = cross_validate(model, X, y, cv=5, scoring=scoring)
print(f"{name:18s} {-s['test_mae'].mean():7.1f} {-s['test_rmse'].mean():7.1f} {s['test_r2'].mean():6.3f}")
Output
Model MAE RMSE R2
Baseline (mean) 66.0 77.3 -0.028
Linear regression 44.3 54.7 0.482
Random forest 47.1 57.7 0.424
- The diabetes dataset predicts a disease progression score. A
DummyRegressorthat always predicts the mean is the baseline: any useful model must beat it. - Scikit-learn’s scorers follow the rule “higher is better”, so error metrics come as negatives (
neg_mean_absolute_error) and the code flips the sign back. cross_validatecomputes several metrics in one run. Linear regression wins on all three: a more complex model is not automatically better on a small dataset.- The baseline’s cross-validated R² is slightly negative, because the mean of each training fold is not exactly the mean of its test fold.
Which Metric?
| Metric | Units | Sensitivity to outliers | Use when |
|---|---|---|---|
| MAE | Same as target | Low | Every unit of error costs the same; data has outliers |
| MSE | Target squared | High | Training loss; large errors are much worse |
| RMSE | Same as target | High | Reporting errors where big misses matter |
| R² | None (proportion) | High | Explaining how much variation the model captures |
| MAPE | Percent | Medium; breaks near zero | Business forecasts where relative error matters |
Common Mistakes
- Reporting only R²; it does not tell you how big the errors are in real units.
- Comparing RMSE across different targets, such as prices in taka and in dollars.
- Forgetting the baseline, so a model that barely beats the mean looks impressive.
- Using MAPE when true values can be zero, which divides by zero.
Practice Exercises
Exercise 1. True values [10, 20, 30], predictions [12, 18, 33]. Compute MAE and RMSE by hand.
Show answer
Errors: 2, −2, 3. MAE = (2 + 2 + 3) / 3 = 2.33. MSE = (4 + 4 + 9) / 3 = 5.67, so RMSE = √5.67 ≈ 2.38.
Exercise 2. Write a function for mean absolute percentage error with NumPy.
Show answer
import numpy as np
def mape(y_true, y_pred):
y_true, y_pred = np.asarray(y_true), np.asarray(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
print(round(mape([10, 20, 30], [12, 18, 33]), 1)) # 13.3 (%)
Scikit-learn also provides mean_absolute_percentage_error, which returns a fraction rather than a percentage.
Frequently Asked Questions
What is a good R² value?
It depends on the field. Physical measurements often reach 0.95 or more, while predictions about human behaviour may be useful at 0.3. Always compare with a baseline and with errors in real units.
Why do models train on MSE if MAE is easier to understand?
MSE is smooth and easy to optimise mathematically, and it corresponds to assuming normally distributed noise. MAE is often better for reporting, and models can also be trained on it when outliers are a problem.
Summary
- MAE: average absolute error, robust to outliers.
- MSE and RMSE: punish large errors; RMSE is in the target’s units.
- R²: share of variation explained, relative to predicting the mean.
- Always compare against a baseline using cross-validation.
