Sub topic 7
Computing the metrics with scikit-learn
What you need first
This chapter assumes you can read basic Python and NumPy. It also assumes you know what MAE, RMSE, and R squared mean, and that you know why a model is scored on a held-out test split. Here you apply those ideas with scikit-learn's sklearn.metrics module and learn where its behavior can surprise you.
The working model
scikit-learn's regression metrics are plain functions. Each takes the true targets first and the predictions second, and returns a number (or an array of numbers). They do not know anything about your model. They compare two arrays.
| Metric | Function | Units of result | Better is |
|---|---|---|---|
| MAE | `mean_absolute_error(y_true, y_pred)` | Same as the target | Lower |
| MSE | `mean_squared_error(y_true, y_pred)` | Target units squared | Lower |
| RMSE | `root_mean_squared_error(y_true, y_pred)` | Same as the target | Lower |
| R squared | `r2_score(y_true, y_pred)` | Unitless, at most 1 | Higher |
The function root_mean_squared_error exists from scikit-learn 1.4 onward. Older code takes the square root by hand, and that still works in every version.
Reproducing the hand calculation
Start with the same four points used earlier in this tutorial. The hand-computed answers were MAE 0.75, RMSE about 0.9354, and R squared about 0.7241.
import numpy as np
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score,
)
y_true = [3.0, 5.0, 2.5, 7.0]
y_pred = [2.5, 5.0, 4.0, 8.0]
mae = mean_absolute_error(y_true, y_pred)
rmse = np.sqrt(mean_squared_error(y_true, y_pred))
r2 = r2_score(y_true, y_pred)
print(f"MAE={mae:.4f} RMSE={rmse:.4f} R2={r2:.4f}")
# MAE=0.7500 RMSE=0.9354 R2=0.7241The functions accept Python lists, NumPy arrays, and pandas Series. They return NumPy floats, so formatting with :.4f works directly.
Getting RMSE in each version
You will see three spellings of RMSE in real code. Know which one your environment supports.
np.sqrt(mean_squared_error(y_true, y_pred))works in every version.root_mean_squared_error(y_true, y_pred)works in 1.4 and later.mean_squared_error(y_true, y_pred, squared=False)was deprecated in 1.4 and removed in 1.6. Old tutorials use it, and on a current install it raises aTypeError.
Argument order matters
The signature is metric(y_true, y_pred). For MAE and MSE, swapping the arguments gives the same number, because the absolute value or square of a difference ignores its sign. This hides the mistake. R squared is different. Its denominator is built from y_true, so swapping the arguments changes the answer.
from sklearn.metrics import r2_score
y_true = [3.0, 5.0, 2.5, 7.0]
y_pred = [2.5, 5.0, 4.0, 8.0]
print(r2_score(y_true, y_pred)) # about 0.7241
print(r2_score(y_pred, y_true)) # a different valueKeep the habit of writing y_true first everywhere, even for the symmetric metrics. Then you never have to remember which ones forgive a swap.
A full held-out evaluation
This is the standard pattern: split, fit on the training part only, predict on the test part, and score the predictions against the test targets.
import numpy as np
from sklearn.datasets import make_regression
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
X, y = make_regression(n_samples=200, n_features=3, noise=10.0, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
print("MAE :", mean_absolute_error(y_test, pred))
print("RMSE:", np.sqrt(mean_squared_error(y_test, pred)))
print("R2 :", r2_score(y_test, pred))The data was generated with noise of standard deviation 10. A good linear fit should therefore give an RMSE near 10 and an MAE somewhat below it. For normally distributed errors, MAE is about 0.8 times RMSE. If your RMSE is far above that ratio, a few large misses are driving it, which is the outlier effect from the earlier chapter.
A second check is available: model.score(X_test, y_test) returns R squared for regressors. It gives the same number as r2_score(y_test, pred), but it hides the metric inside the estimator. Calling r2_score explicitly makes the code easier to read and lets you swap in other metrics.
Scoring on the training set by mistake
The metric functions will happily score whatever you give them. They cannot tell whether y_pred came from data the model has already seen. If you call model.predict(X_train) and score against y_train, you get a valid number that measures memorization instead of generalization. For a flexible model such as a deep decision tree, the training R squared can be near 1.0 while the test R squared is much lower.
A useful diagnostic is to compute both and compare:
from sklearn.metrics import r2_score
train_r2 = r2_score(y_train, model.predict(X_train))
test_r2 = r2_score(y_test, model.predict(X_test))
print(f"train R2={train_r2:.3f} test R2={test_r2:.3f}")A large gap between the two means overfitting. Report the test number.
Multiple targets
When y_true and y_pred have several columns, the metrics score each column and then combine them. The multioutput parameter controls the combination.
from sklearn.metrics import mean_absolute_error
y_true = [[0.5, 1.0], [-1.0, 1.0], [7.0, -6.0]]
y_pred = [[0.0, 2.0], [-1.0, 2.0], [8.0, -5.0]]
print(mean_absolute_error(y_true, y_pred))
# 0.75 (default: uniform_average)
print(mean_absolute_error(y_true, y_pred, multioutput="raw_values"))
# [0.5 1. ] (one value per column)The accepted values are:
"uniform_average"is the default. It takes the plain mean across columns."raw_values"returns one score per column.- An array of weights returns a weighted average.
"variance_weighted"is available forr2_scoreonly. It weights each column by the variance of its true values.
Averaging across columns mixes units, so a uniform average of MAE over a price column and a distance column is hard to interpret. Prefer raw_values unless the columns share units.
Sample weights
Every metric function accepts sample_weight, an array with one weight per row. Use it when some rows should count more, such as rows that represent many customers or recent observations.
from sklearn.metrics import mean_absolute_error
y_true = [3.0, 5.0, 2.5, 7.0]
y_pred = [2.5, 5.0, 4.0, 8.0]
weights = [1, 1, 1, 3]
print(mean_absolute_error(y_true, y_pred, sample_weight=weights))
# (0.5*1 + 0*1 + 1.5*1 + 1*3) / 6 = 0.8333...The result is a weighted mean, so the weights are divided by their sum. Doubling every weight changes nothing.
Metrics inside cross-validation
Cross-validation tools such as cross_val_score and GridSearchCV choose metrics by a scoring string. They maximize the score, so error metrics are negated. Lower error then becomes a higher (less negative) score.
| Scoring string | Underlying metric | Sign of returned value |
|---|---|---|
| `"neg_mean_absolute_error"` | MAE | Negative |
| `"neg_mean_squared_error"` | MSE | Negative |
| `"neg_root_mean_squared_error"` | RMSE | Negative |
| `"r2"` | R squared | As is |
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=200, n_features=3, noise=10.0, random_state=0)
scores = cross_validate(
LinearRegression(),
X,
y,
cv=5,
scoring={
"mae": "neg_mean_absolute_error",
"rmse": "neg_root_mean_squared_error",
"r2": "r2",
},
)
print("MAE :", -scores["test_mae"].mean())
print("RMSE:", -scores["test_rmse"].mean())
print("R2 :", scores["test_r2"].mean())With a dictionary of scorers, cross_validate returns arrays under the keys test_mae, test_rmse, and test_r2, one value per fold. Negate the error arrays to get back to positive errors. Forgetting the minus sign is a common reporting error: a table that lists "RMSE = -10.2" is a sign that the scorer's output was pasted in unchanged.
Averaging RMSE across folds is not identical to computing RMSE on all predictions pooled together. The fold average is a mean of square roots. For reporting, either is acceptable, but state which one you used.
Edge cases and errors
Mismatched lengths
If y_true and y_pred have different numbers of rows, scikit-learn raises a ValueError about inconsistent numbers of samples. This usually means the predictions came from a different split than the targets. Check that you are pairing y_test with predictions made on X_test.
Too few samples for R squared
R squared needs at least two samples, because the baseline variance of one point is zero. With a single sample, r2_score returns nan and emits a warning. MAE and RMSE work with one sample.
Constant true values
If every value in y_true is the same, the denominator of R squared is zero. By default (force_finite=True), scikit-learn avoids returning nan or infinity. It returns 1.0 for perfect predictions and 0.0 otherwise. Be careful when you see 0.0 on a tiny or filtered subset, because it may reflect a constant target and not a model that matches the mean baseline. Pass force_finite=False if you would rather get the raw nan or -inf.
Negative R squared
r2_score can be negative. This happens when the predictions are worse than always predicting the mean of y_true. It is not a bug and not a sign that the function misbehaves. It is a meaningful result, common on held-out data when a model has overfit or the test distribution differs from training.
Non-finite values
If y_pred contains nan or infinity, for example from a model that divided by zero, the metrics raise a ValueError about input containing NaN or infinity. Fix the source of the bad values instead of dropping rows silently, because dropped rows make the score look better than the model deserves.
A reusable reporting helper
When you compare several models, compute the same three numbers each time. A small function prevents drift between notebooks.
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
def regression_report(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),
}
print(regression_report([3.0, 5.0, 2.5, 7.0], [2.5, 5.0, 4.0, 8.0]))The same function can be called on the training split and the test split to produce the comparison described above.
Summary of habits
- Pass
y_truefirst, every time. - Fit on training data only and score on the held-out split.
- Choose the RMSE spelling your scikit-learn version supports.
- Negate the
neg_scorers before reporting. - Treat negative R squared and constant-target zeros as signals to investigate, not noise.
Exercise
You run crossvalidate with scoring="negrootmeansquarederror" and get test scores of [-9.8, -10.4, -10.1, -9.6, -10.6]. A colleague reports "average RMSE is -10.1". What is wrong, and what should the report say? Also, your script uses meansquarederror(ytest, pred, squared=False) and fails on a fresh install of scikit-learn 1.6. How do you fix it?
Show answer
The scorer negates the error so that higher is better, so the values must be negated before reporting. RMSE cannot be negative. The mean of the fold values is -10.1, so the report should say the average RMSE is 10.1 (state that it is a mean of per-fold RMSE values). The squared=False argument was removed in scikit-learn 1.6. Replace the call with rootmeansquarederror(ytest, pred), available from 1.4, or with np.sqrt(meansquarederror(y_test, pred)), which works in every version.