Regression Metrics & Validation
MAE, MSE, RMSE and R² with a worked example; how to split data into train/validation/test; k-fold, stratified, group and time-series cross-validation; and how data leakage silently inflates your scores.
Two questions decide whether a model's reported number means anything: what you measure (the metric) and on which data you measure it (the validation scheme). A perfect metric on a leaky split is worthless; a perfect split with the wrong metric optimizes the wrong thing. This lesson covers both for Regression problems — and the validation part applies to every kind of model.
Regression metrics
- MAE
- Mean Absolute Error (MAE), mean absolute error — in the target's units
- MSE
- Mean squared error (MSE), mean squared error — in squared units
- RMSE
- Root Mean Squared Error (RMSE), root mean squared error — back in the target's units
- R²
- R² (coefficient of determination): fraction of the variance in y explained by the model
- 1/n
- divide by n, the number of examples (i.e. take the average)
- Σ
- sum over all examples i = 1 … n
- |yᵢ − ŷᵢ|
- absolute error of example i (drop the minus sign)
- yᵢ
- true value of example i
- ŷᵢ
- the model's prediction for example i
- √
- square root
- SS_res
- residual sum of squares Σ(yᵢ − ŷᵢ)²: your model's total squared error
- SS_tot
- total sum of squares Σ(yᵢ − ȳ)²: the total squared error of always predicting the mean
- ȳ
- “y-bar”: mean of the true values
▸Worked example
| Metric | Units | Behaviour | Use when |
|---|---|---|---|
| MAE | same as y | Every unit of error counts equally; robust to outliers. Optimal constant predictor = median. | You want an easy-to-explain 'typical error' and outliers should not dominate. |
| MSE | y² | Squares errors: big mistakes dominate. Smooth, so it is the usual training loss. Optimal constant = mean. | Training objective; large errors are disproportionately bad. |
| RMSE | same as y | Like MSE but back in the original units; always ≥ MAE. | Reporting an error in units while still penalizing large errors. |
| R² | unitless | Fraction of variance explained vs predicting the mean. 1 = perfect, 0 = as good as the mean, < 0 = worse than the mean. | Comparing models on the same target; communicating 'how much is explained'. |
mean_absolute_error, mean_squared_error, root_mean_squared_error (≥ 1.4), r2_score.[5]Worked example
True y = [3, 5, 2, 8], predictions ŷ = [2.5, 5, 4, 7]. Errors: 0.5, 0, −2, 1. MAE = (0.5 + 0 + 2 + 1)/4 = 0.875. Squared errors: 0.25, 0, 4, 1 → MSE = 5.25/4 = 1.3125, RMSE ≈ 1.146. The mean of y is 4.5, so SS_tot = 1.5² + 0.5² + 2.5² + 3.5² = 21 and SS_res = 5.25 → R² = 1 − 5.25/21 = 0.75. Notice how the single error of 2 contributes 4 of the 5.25 squared-error total: RMSE is dominated by the worst prediction, MAE much less so.
sklearn.dummy.DummyRegressor), or 'yesterday's value' for time series. A model that barely beats it is not learning much. R² already builds this in: it compares your model against the mean predictor.Train / validation / test
- [[training-set|Training set]] (e.g. 70–80%): fit the model's parameters.
- [[validation-set|Validation set]] (e.g. 10–15%): choose hyperparameters, features, thresholds, the early-stopping epoch. You will look at it many times, so it slowly becomes 'seen'.
- [[test-set|Test set]] (e.g. 10–15%): touched once, at the end, to estimate real-world performance. If you change the model after looking at it, you need a new test set.
- With millions of examples, 1% for val and test can be plenty; with a few hundred, use cross-validation instead of a single val split.
k-fold cross-validation
A single validation split is noisy: a lucky or unlucky split can swing your score. In k-fold [[cross-validation]] you split the training data into k folds, train k times — each time holding out a different fold for validation — and report the mean ± standard deviation of the k scores. Every example is used for validation exactly once. The test set stays outside this loop.[2]
- CV score
- the cross-validated estimate of model performance
- 1/k
- divide by k, the number of folds (typically 5 or 10) — i.e. take the average
- Σⱼ
- sum over the folds j = 1 … k
- score
- your metric (accuracy, F1, RMSE …) computed on one validation fold
- j
- index of the fold held out in this round
- ·
- multiplication
▸Worked example
| Splitter (scikit-learn) | Use when |
|---|---|
KFold(shuffle=True) | i.i.d. regression data. |
StratifiedKFold | Classification, especially imbalanced: keeps the class ratio equal in every fold. |
GroupKFold | Several rows belong to the same entity (patient, user, house, document). All rows of a group stay in the same fold, so the model cannot 'recognize' a patient it saw during training. |
TimeSeriesSplit | Temporal data: always train on the past and validate on the future (expanding window). Never shuffle time series. |
Data leakage: the silent score inflater
Data leakage means information that would not be available at prediction time sneaks into training or evaluation. The model looks great offline and fails in production. Kaufman et al. describe leakage as one of the top mistakes in applied data mining and show real competition examples where leaked features dominated the winning models.[3] The usual suspects:
- Preprocessing fit on all data — scaling, imputation, feature selection or PCA fitted before splitting. Fix: put them inside a scikit-learn
Pipelineso they are re-fit on each training fold.[4] - Target leakage — a feature computed from, or after, the label (e.g. 'number of follow-up visits' when predicting a diagnosis; 'refund issued' when predicting fraud).
- Temporal leakage — random splits on time-ordered data, or features using future values (rolling means centered on the current day).
- Duplicates / group leakage — the same image, user, or near-duplicate text in train and test.
- Oversampling or augmentation before splitting, and tuning on the test set.
Leak-free cross-validation in code
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.dummy import DummyRegressor
from sklearn.model_selection import train_test_split, KFold, cross_validate
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42) # test set: sealed envelope
model = make_pipeline(SimpleImputer(), StandardScaler(), Ridge(alpha=1.0))
cv = KFold(n_splits=5, shuffle=True, random_state=42)
scoring = {"rmse": "neg_root_mean_squared_error",
"mae": "neg_mean_absolute_error", "r2": "r2"}
for name, est in [("baseline", DummyRegressor()), ("ridge", model)]:
res = cross_validate(est, X_train, y_train, cv=cv, scoring=scoring)
print(name,
"RMSE %.3f ± %.3f" % (-res["test_rmse"].mean(), res["test_rmse"].std()),
"R2 %.3f" % res["test_r2"].mean())
model.fit(X_train, y_train) # final fit, then ONE test look
print("test R2:", model.score(X_test, y_test))neg_...). The imputer and scaler live inside the pipeline, so each fold fits them on its own training part only.Knobs
- What it is
- How many folds cross-validation uses. Each model trains on (k−1)/k of the data.
- ↑ If you increase it
- Each model sees more training data (less pessimistic estimate), but k× the compute and folds overlap more, so fold scores are correlated. k = n is leave-one-out.
- ↓ If you decrease it
- Cheaper, but each model trains on less data and the estimate is noisier (k = 2 uses only half the data per model).
- Typical values
- 5 or 10. Use
RepeatedKFold/RepeatedStratifiedKFoldfor small datasets; a single holdout split for big deep-learning datasets.
- What it is
- Share of the data held out for testing (or validation).
- ↑ If you increase it
- More precise estimate of performance, but less data left to train on — the model itself gets worse.
- ↓ If you decrease it
- More training data, but the test score has wide error bars (with 100 test examples, an accuracy of 90% has a ±6% 95% interval).
- Typical values
- 20% for small/medium tabular data; a fixed few thousand to tens of thousands of examples for large datasets.
- What it is
- Number of samples dropped between each training window and its validation window (
TimeSeriesSplit(n_splits=5, gap=...)). - ↑ If you increase it
- Removes leakage from features that look back over a window (lags, rolling means) and mimics the real delay before labels arrive; you lose some data.
- ↓ If you decrease it
- Uses all data, but adjacent, highly correlated samples straddle the boundary and inflate the score.
- Typical values
- ≥ the longest lookback window of your features or your prediction horizon.
▸Go deeper: nested CV, Huber loss and why R² can be negative
Nested cross-validation wraps hyperparameter search (inner CV) inside an outer CV loop that only evaluates. It gives an almost unbiased estimate of 'this whole procedure, including tuning', at the cost of k_outer × k_inner × n_candidates fits.[2]
Huber loss is quadratic for small errors and linear for errors larger than δ — a compromise between MSE (smooth) and MAE (robust to outliers). R² < 0 on a test set simply means the model is worse than predicting the training mean on that data, which happens with heavy overfitting or distribution shift. The ISLR book (chapter 5) gives an accessible treatment of resampling methods.[1]
Quiz
References
- [1]An Introduction to Statistical Learning (2nd ed.), Chapter 5: Resampling MethodsBookJames, Witten, Hastie, Tibshirani2021statlearning.com
- [2]scikit-learn User Guide — Cross-validation: evaluating estimator performanceDocsscikit-learn developersscikit-learn.org
- [3]Leakage in Data Mining: Formulation, Detection, and AvoidancePaperKaufman, Rosset, Perlich, Stitelman2012doi.orgACM TKDD 6(4); earlier version at KDD 2011.
- [4]scikit-learn User Guide — Common pitfalls and recommended practices (data leakage)Docsscikit-learn developersscikit-learn.org
- [5]scikit-learn User Guide — Regression metricsDocsscikit-learn developersscikit-learn.org