Sub topic 10
Choosing and reporting a metric
This chapter assumes you can compute residuals, MAE, RMSE, and R squared (R²) by hand and with scikit-learn. It also assumes you know why metrics must be measured on held-out data. Earlier chapters showed what each metric computes. This one covers which to lead with and what to include so a reader can trust your number.
No metric is best on its own
MAE, RMSE, and R² answer different questions about the same residuals.
- MAE is the typical size of a miss, in the units of the target.
- RMSE is also in target units, but it is pulled toward the largest misses.
- R² is unitless. It tells you how much of the baseline's squared error the model removed.
You choose among them by asking what an error costs, whether the data contains outliers you should not chase, and who will read the number.
Start from the cost of an error
Write down what a miss of 10 units costs compared with a miss of 5.
- If it costs twice as much, the cost is linear in the error. MAE matches that cost directly.
- If it costs more than twice as much, large misses are disproportionately harmful. Examples are a power grid forecast that is far too low, or a dosage that is far too high. RMSE reflects this because squaring grows faster than the error itself.
- If the cost is hard to state, you still need a default. MAE is easier to explain. RMSE is the more common choice when the model was trained with squared loss.
The training loss also matters. Minimizing squared error pushes predictions toward the conditional mean. Minimizing absolute error pushes them toward the conditional median. If stakeholders care about totals, such as the sum of predicted demand over a month, mean-oriented predictions and RMSE fit better. If they care about the typical case, and a few extreme rows should not dominate, the median-oriented MAE fits better.
Decision criteria at a glance
| Situation | Lead metric | Reason |
|---|---|---|
| Cost is proportional to error size | MAE | It is the average cost, in the units of the target |
| Large misses are especially costly | RMSE | Squaring weights big errors more heavily |
| A few labels are known to be corrupted | MAE, plus median absolute error | Less pulled by extreme rows |
| Comparing models on one dataset | Any, but the same one for all | Rankings can differ between metrics |
| Comparing across datasets or targets with different scales | R² | It is unitless, but read it with care |
| Explaining results to non-technical readers | MAE | "Off by 3.2 degrees on average" needs no further explanation |
The same data can rank models differently
Two models can tie on MAE and still differ sharply on RMSE. Here is a small, complete example.
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
y_true = np.array([10.0, 20.0, 30.0, 40.0, 50.0])
# Model A misses every point by 2. Model B is perfect except one miss of 10.
pred_a = np.array([12.0, 18.0, 32.0, 38.0, 52.0])
pred_b = np.array([10.0, 20.0, 30.0, 40.0, 60.0])
for name, pred in (("A", pred_a), ("B", pred_b)):
mae = mean_absolute_error(y_true, pred)
rmse = np.sqrt(mean_squared_error(y_true, pred))
r2 = r2_score(y_true, pred)
print(f"{name}: MAE={mae:.2f} RMSE={rmse:.2f} R2={r2:.2f}")
# A: MAE=2.00 RMSE=2.00 R2=0.98
# B: MAE=2.00 RMSE=4.47 R2=0.90Judged by MAE alone, the models are tied. Judged by RMSE or R², model A is clearly better. Which is the right verdict depends on your cost of error. If one miss of 10 is acceptable and ten misses of 2 are not, model B is fine. If a miss of 10 would be a serious incident, model A is the better choice. The metric encodes that judgment, so choose it before looking at the results. Choosing it afterward to make a favorite model win is a common way to fool yourself.
Always report a baseline
A bare "RMSE is 4.2" cannot be judged. Is that good? It depends on the spread of the target. R² solves this by building in the mean baseline. You can do the same for MAE and RMSE by also reporting the baseline's score on the same test set.
The baseline must use the training mean, not the test mean. A model never sees test labels, so the baseline should not either. scikit-learn's DummyRegressor does this correctly.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
def score(y_true, y_pred):
return {
"MAE": mean_absolute_error(y_true, y_pred),
"RMSE": float(np.sqrt(mean_squared_error(y_true, y_pred))),
"R2": r2_score(y_true, y_pred),
}
X, y = make_regression(n_samples=300, n_features=4, noise=15.0, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=1
)
baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
model = LinearRegression().fit(X_train, y_train)
print("test rows:", len(y_test))
for name, est in (("baseline", baseline), ("linear", model)):
s = score(y_test, est.predict(X_test))
print(f"{name:9s} " + " ".join(f"{k}={v:.2f}" for k, v in s.items()))The baseline row shows an R² near 0, and slightly below it, because the training mean differs from the test mean. The linear row should show much lower MAE and RMSE and an R² close to 1. The gap between the two rows is the real result. If your model's RMSE is barely below the baseline's, the model has learned little, however good a raw number looks.
One split is one sample
A test score from a single split carries noise. With 75 test rows, a different random split could move RMSE noticeably. Cross-validation gives you a spread to report alongside the mean.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_validate
X, y = make_regression(n_samples=300, n_features=4, noise=15.0, random_state=1)
scores = cross_validate(
LinearRegression(),
X,
y,
cv=5,
scoring={
"mae": "neg_mean_absolute_error",
"rmse": "neg_root_mean_squared_error",
"r2": "r2",
},
)
mae = -scores["test_mae"] # flip the sign back
rmse = -scores["test_rmse"]
r2 = scores["test_r2"]
print(f"MAE {mae.mean():.2f} +/- {mae.std():.2f}")
print(f"RMSE {rmse.mean():.2f} +/- {rmse.std():.2f}")
print(f"R2 {r2.mean():.3f} +/- {r2.std():.3f}")Report in the units your reader cares about
If you trained on a transformed target, such as log(price), an RMSE computed on the log scale is not an error in dollars. It is a roughly relative error, and it cannot be compared with a dollar-valued baseline. Transform predictions back to the original scale, then compute the metrics. State which scale you used.
Other reporting details that change how a number reads:
- Name the metric and its units, for example "MAE = 3.2 °C", never just "error = 3.2".
- Say which data the number was measured on: training, validation, or test.
- Give the number of test rows and the splitting method (random, time-based, grouped).
- Report the baseline's score on the same rows.
- Give a spread when you used cross-validation.
Common mistakes when choosing
- Choosing the metric after seeing results. Fix the metric, or the shortlist, before comparing models.
- Reporting R² alone. It hides the size of the error in real units, and a high R² can still mean unacceptable misses for a target with large variance.
- Comparing RMSE across datasets. A value of 5 means different things on a target that ranges from 0 to 10 and one that ranges from 0 to 10,000.
- Treating all outliers as noise. If the extreme rows are real and matter to the business, MAE can make a model look good while it fails exactly where it counts.
- Treating all outliers as signal. If a few labels are data-entry errors, RMSE rewards a model for fitting them. Clean the labels, or add the median absolute error alongside.
- Mixing in-sample and out-of-sample numbers. A training-set R² next to a test-set RMSE is not a fair comparison.
- Computing the baseline from the test mean. It leaks test information and inflates the baseline's score.
A practical reporting template
When you have no strong reason to deviate, report these four things together:
- The lead metric chosen from the cost of error, in target units.
- MAE and RMSE side by side. If RMSE is much larger than MAE, a few large misses are driving the error, and you should inspect them.
- R² against the training-mean baseline, on the same held-out data.
- The baseline's MAE and RMSE, the test size, and the splitting method.
That is a few lines of text, and it lets another person decide whether the model is useful without rerunning anything.
Exercise
A model predicts delivery times in minutes. On the test set it has MAE = 4.0 and RMSE = 9.0. A teammate says the model is "off by about 4 minutes, so it's fine." What does the gap between MAE and RMSE tell you, and what would you check before agreeing?
Show answer
RMSE is more than twice MAE, so the errors are not evenly spread. A few large misses dominate the squared error while most predictions are close. Before agreeing, look at the distribution of residuals (for example the largest 5% by absolute value) and ask whether late deliveries of 30 or more minutes are costly. Also report the training-mean baseline's MAE and RMSE on the same test set to see how much the model actually improves on it.
Exercise
You trained a model on log(price) and got an RMSE of 0.25 on the test set. Your manager asks how many dollars the model is off by. Why can't you answer from this number, and what should you do?
Show answer
The 0.25 is an error on the log scale, so it is roughly a relative error and not a dollar amount. Convert the predictions back with exp() and compute MAE and RMSE against the original prices on the same test rows. Report those dollar-valued numbers, state that the model was trained on the log scale, and include the mean-price baseline in dollars for comparison.