Sub topic 7
Computing the metrics with scikit-learn
This chapter assumes you know basic Python and NumPy, can compute a mean and a square root, and know what a regression model predicts. It also assumes you know that data is split into training and test sets. You have already computed MAE, RMSE, and R squared by hand. Here you will get the same numbers from sklearn.metrics and avoid the usual mistakes.
The three functions
scikit-learn provides one function per metric. All of them take the true values first and the predictions second.
| Metric | Function | Returns |
|---|---|---|
| MAE | `mean_absolute_error(y_true, y_pred)` | Average absolute error, in target units |
| MSE | `mean_squared_error(y_true, y_pred)` | Average squared error, in squared units |
| RMSE | `root_mean_squared_error(y_true, y_pred)` | Square root of MSE, in target units |
| R squared | `r2_score(y_true, y_pred)` | Improvement over the predict-the-mean baseline |
The root_mean_squared_error function was added in scikit-learn 1.4. On older versions, take the square root of mean_squared_error yourself. The older squared=False argument was deprecated and later removed, so don't rely on it.
Reproducing the hand calculation
Use the four-point example from earlier chapters. The hand-computed values 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 output matches the NumPy version. If your library result disagrees with a hand calculation, suspect the hand calculation or the argument order first.
Argument order matters for R squared
MAE and MSE give the same answer if you swap the two arguments, because the error is squared or made absolute. R squared does not. Its denominator is the variance of y_true, so the first argument defines the baseline.
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(round(r2_score(y_true, y_pred), 4)) # 0.7241
print(round(r2_score(y_pred, y_true), 4)) # 0.8182The swapped call runs without error and returns a plausible but wrong number. Always write metric(y_true, y_pred).
A full evaluation on a test split
In practice you fit on training data and score on held-out data. The next chapter covers why in detail. The code shows the pattern.
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, so the RMSE should land close to 10. MAE should be somewhat smaller than RMSE, since RMSE weights larger misses more. R squared should be high because the three features explain most of the variation in y.
Common errors
- Passing predictions first. This matters only for R squared, but form the habit for all metrics.
- Reporting MSE as if it were in target units. MSE is in squared units. Report RMSE when you want a number in dollars, degrees, or whatever the target uses.
- Scoring on the training set. The numbers will look better than real-world performance.
- Shape mismatches. A column of shape
(n, 1)against a vector of shape(n,)can broadcast in your own NumPy code and give wrong results. The scikit-learn functions validate shapes, but your hand-written checks will not. - Sign flips in model selection. Tools such as
cross_val_scoreexpect higher to mean better. Their scorer names for error metrics are therefore negated, for exampleneg_mean_absolute_errorandneg_root_mean_squared_error. Negate the result to recover the plain error.
Exercise
A colleague computes r2_score(preds, actuals) and gets 0.82. You compute r2_score(actuals, preds) on the same data and get 0.72. Which value should be reported, and why do the two differ?
Show answer
Report 0.72. The correct order is r2_score(y_true, y_pred). R squared divides the squared error by the variance of the first argument. Your colleague used the predictions' variance as the baseline. The two variances differ, so the scores differ, and the swapped call raises no error.
Exercise
You have scikit-learn 1.3 and want RMSE in the original target units. Write the expression, assuming y_test and pred exist.
Show answer
np.sqrt(mean_squared_error(y_test, pred)). The function root_mean_squared_error is not available before version 1.4.