AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
↘Training Results & Evaluation
  1. Reading Loss & Accuracy Curves
  2. Classification Metrics
  3. Regression Metrics & Validation
  4. Experiment Logging & Reproducibility
  5. Hyperparameter Tuning
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Training Results & Evaluation

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.

Intermediate~24 min·5 references
Key terms
Mean Absolute Error (MAE)Mean squared error (MSE)Root Mean Squared Error (RMSE)R² (coefficient of determination)Training setValidation setTest setCross-validationData leakageBaseline

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.

≈
Exam rules
The training set is the textbook, the validation set is the practice exams you use to decide how to study, and the test set is the final exam in a sealed envelope. If you peek at the final exam while studying — even once — your grade no longer tells anyone how well you really learned. Data leakage is any way the sealed envelope gets opened.

Regression metrics

MAE = (1/n) · Σ |yᵢ − ŷᵢ| MSE = (1/n) · Σ (yᵢ − ŷᵢ)² RMSE = √MSE R² = 1 − SS_res / SS_tot = 1 − Σ(yᵢ − ŷᵢ)² / Σ(yᵢ − ȳ)²
yᵢ = true value, ŷᵢ = prediction, ȳ = mean of the true values.
In words: Read the lines as four summaries of the errors yᵢ − ŷᵢ. MAE averages their absolute size; MSE averages their squares, so big errors dominate; RMSE takes the square root to get back to the target's units; R² compares your squared error with that of always predicting the mean — 1 is perfect, 0 is no better than the mean, negative is worse than the mean.
Symbols(hover a symbol in the formula)
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
House prices (in thousands): true y = (200, 300, 250), predicted ŷ = (210, 280, 250) Errors yᵢ − ŷᵢ: −10, 20, 0 MAE = (10 + 20 + 0) / 3 = 10 MSE = (100 + 400 + 0) / 3 ≈ 166.7 RMSE = √166.7 ≈ 12.9 ← above MAE because the error of 20 weighs more ȳ = 250 → SS_tot = 50² + 50² + 0² = 5000, SS_res = 100 + 400 + 0 = 500 R² = 1 − 500 / 5000 = 0.90 (the model explains 90% of the variance)
MetricUnitsBehaviourUse when
MAEsame as yEvery 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.
MSEy²Squares errors: big mistakes dominate. Smooth, so it is the usual training loss. Optimal constant = mean.Training objective; large errors are disproportionately bad.
RMSEsame as yLike MSE but back in the original units; always ≥ MAE.Reporting an error in units while still penalizing large errors.
R²unitlessFraction 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'.
In scikit-learn: 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.

✓
Always compute a baseline
Before celebrating an RMSE, compute the RMSE of a trivial Baseline: predict the training mean (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 = (1/k) · Σⱼ score(model trained on all folds except j, evaluated on fold j)
The k-fold cross-validation estimate: the average of k held-out scores.
In words: “for each of the k folds, train a fresh model on the other k − 1 folds, score it on the held-out fold, then average the k scores.” Every example is used for validation exactly once, so the average depends much less on one lucky or unlucky split. Report the standard deviation of the k scores alongside it.
Symbols(hover a symbol in the formula)
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
1,000 training examples, k = 5 → five folds of 200 Round 1: train on folds 2–5 (800 examples), validate on fold 1 → 0.82 Rounds 2–5 → 0.85, 0.80, 0.84, 0.83 CV score = (0.82 + 0.85 + 0.80 + 0.84 + 0.83) / 5 = 4.14 / 5 = 0.828 Std of the five scores ≈ 0.017 → report 0.828 ± 0.017 Cost: 5 training runs instead of 1.
Splitter (scikit-learn)Use when
KFold(shuffle=True)i.i.d. regression data.
StratifiedKFoldClassification, especially imbalanced: keeps the class ratio equal in every fold.
GroupKFoldSeveral 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.
TimeSeriesSplitTemporal 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 Pipeline so 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

python
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))
scikit-learn scorers follow 'higher is better', so error metrics are negated (neg_...). The imputer and scaler live inside the pipeline, so each fold fits them on its own training part only.

Knobs

knobNumber of folds k (n_splits)
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 / RepeatedStratifiedKFold for small datasets; a single holdout split for big deep-learning datasets.
knobtest_size / validation fraction
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.
knobTimeSeriesSplit gap
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.
!
Pitfalls
Comparing RMSE across targets with different scales; reporting R² on training data; MAPE explodes when true values are near zero; using the CV score you tuned on as your final estimate (it is optimistically biased — use a held-out test set or nested CV); shuffling time series; and fitting any preprocessing step outside the CV loop.
▸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

1.
Your dataset has a few extreme outliers you do not want to dominate the evaluation. Which metric is more appropriate to report?
2.
A model gets R² = −0.2 on the test set. What does this mean?
3.
You standardize all features with StandardScaler on the full dataset, then run 5-fold CV. What is the problem?
4.
You predict next week's sales from daily data. Which validation scheme is right?
5.
Medical images: each patient has ~20 scans. A random split gives 98% val accuracy, but performance on new patients is much lower. Why?
Score: 0/5

References

  1. [1]
    An Introduction to Statistical Learning (2nd ed.), Chapter 5: Resampling Methods
    BookJames, Witten, Hastie, Tibshirani2021statlearning.com
  2. [2]
    scikit-learn User Guide — Cross-validation: evaluating estimator performance
    Docsscikit-learn developersscikit-learn.org
  3. [3]
    Leakage in Data Mining: Formulation, Detection, and Avoidance
    PaperKaufman, Rosset, Perlich, Stitelman2012doi.org
    ACM TKDD 6(4); earlier version at KDD 2011.
  4. [4]
    scikit-learn User Guide — Common pitfalls and recommended practices (data leakage)
    Docsscikit-learn developersscikit-learn.org
  5. [5]
    scikit-learn User Guide — Regression metrics
    Docsscikit-learn developersscikit-learn.org
← Previous
Classification Metrics
Next →
Experiment Logging & Reproducibility