Machine Learning Advanced 12 minutes

Cross Validation

Estimating a model's performance more reliably by rotating it over several splits of the data.

Your progress in the track0%

Idea

A single split into training and test gives an estimate affected by luck in the choice of sample. Cross-validation repeats the evaluation on several splits and gives a mean and a spread.

K-Fold

from sklearn.model_selection import cross_validate, StratifiedKFold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
res = cross_validate(model, X, y, cv=cv, scoring=["accuracy", "f1_macro"])
print(res["test_f1_macro"].mean(), res["test_f1_macro"].std())

Choosing the type of split

Nature of the dataTool
Classification with imbalanced classesStratifiedKFold
Several samples per patient or userGroupKFold or StratifiedGroupKFold
Time seriesTimeSeriesSplit
Very small dataRepeatedStratifiedKFold

Nested validation

When hyperparameters are tuned and the model is chosen on the same data, the best result is optimistic. The solution:

from sklearn.model_selection import GridSearchCV, cross_val_score
inner = StratifiedKFold(5, shuffle=True, random_state=1)
outer = StratifiedKFold(5, shuffle=True, random_state=2)
search = GridSearchCV(model, param_grid, cv=inner)
scores = cross_val_score(search, X, y, cv=outer)
print(scores.mean(), scores.std())

the inner loop chooses the parameters, and the outer loop estimates the performance of the whole procedure.

Common mistakes

  • Preprocessing outside the folds (leakage). Put everything in Pipeline.
  • Selecting features on the whole data before cross-validation.
  • Reporting the best fold instead of the mean.

Lesson terms

Stratified cross-validation
A split that preserves the class proportions in each fold.
Nested cross-validation
An outer loop to estimate performance and an inner loop to tune the hyperparameters, to avoid an optimistic estimate.
K-fold cross-validation
Splitting the data into K parts and training the model K times so that each part is used for evaluation once.

Abstract

K-fold cross-validation splits the data into K parts and trains the model K times, each time on K-1 parts, evaluating it on the remaining part, then computes the mean performance and its spread. It needs special variants depending on the data: Stratified for imbalanced classes, Group when there are related groups such as patients, and TimeSeriesSplit for temporal data. Nested cross-validation separates hyperparameter tuning from performance estimation.

Review questions

  1. When do you use GroupKFold?

    When the data contains related groups, such as several images of the same patient, to make sure members of one group do not appear in both training and evaluation.

  2. Why is best_score_ in GridSearchCV optimistic?

    Because it is the best result among many candidates on the same data that was used to choose the parameters.

Sources and references

  1. scikit-learn — Cross-validation: evaluating estimator performance
  2. scikit-learn — Nested versus non-nested cross-validation
  3. Varma & Simon (2006) Bias in error estimation when using cross-validation for model selection — BMC Bioinformatics

Complete the lesson