Sub topic 3
Measuring Regression Performance on Held-Out Data
Assume you know basic NumPy operations, averages, regression predictions, and training–test splits. A metric is useful only when it measures performance on data the model did not use during training.
Measuring on held-out data, not training data
A model can memorize training examples. Its training error may be very small while its errors on new examples are large. To estimate generalization, split the data before fitting:
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, 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)
prediction = model.predict(X_test)
print("MAE:", mean_absolute_error(y_test, prediction))
print("RMSE:", np.sqrt(mean_squared_error(y_test, prediction)))
print("R²:", r2_score(y_test, prediction))Use the test set for the final report. If you repeatedly tune choices against it, it stops being a reliable final check. Use cross-validation or a separate validation set for repeated tuning.
R squared pitfalls
R squared compares your model with a baseline that always predicts the training-target mean. On held-out data, it can be negative when the model is worse than that baseline. Negative R² is a warning about poor generalization, distribution shift, or an unsuitable model.
Adding predictors cannot reduce training R², even when those predictors add noise. Adjusted R² accounts for the number of predictors and can decrease when a new feature provides too little improvement. However, it remains a summary statistic, not proof of useful predictions.
Choosing and reporting a metric
Choose the metric that matches the cost of mistakes:
- Report MAE when the typical absolute error is easy to explain.
- Report RMSE when large errors deserve extra penalty.
- Report R² to describe improvement over the mean baseline.
Include the evaluation split, target units, and a baseline when possible. Do not compare metrics from different target scales without care.
Related metrics
Median absolute error reports the middle absolute error. It resists outliers more than MAE. MAPE expresses error as a percentage, but it becomes unstable or undefined when actual values are zero or close to zero.
Exercise
A test-set R² is negative, but the training-set R² is high. What is the most likely interpretation?
Show answer
The model generalizes poorly. It may be overfitting, or the test data may differ from the training data.