ML Cross Validation
A single train/test split has a weakness: the score depends on which rows happened to land in the test set. A lucky split flatters the model; an unlucky one undersells it. With small data sets the difference can be large. Cross validation (CV) fixes this by repeating the split several times and averaging the results.
How much does one split vary?
Let's train the same model on the breast-cancer data with five different random splits:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
for seed in range(5):
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=seed)
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_tr, y_tr)
print(f"split {seed}: test accuracy = {model.score(X_te, y_te):.3f}")split 0: test accuracy = 0.937
split 1: test accuracy = 0.916
split 2: test accuracy = 0.923
split 3: test accuracy = 0.930
split 4: test accuracy = 0.895
Same model, same data — yet the "accuracy" moves by several percentage points depending on the split.
K-fold cross validation
K-fold CV cuts the data into k equal parts (folds). It trains k times; each time one fold is the validation set and the other k − 1 folds are the training set. Every row is used for validation exactly once.
fold: 1 2 3 4 5
run 1: [val] train train train train
run 2: train [val] train train train
run 3: train train [val] train train
run 4: train train train [val] train
run 5: train train train train [val]cross_val_score does the whole loop:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import KFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
model = DecisionTreeClassifier(max_depth=3, random_state=0)
folds = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=folds)
print("fold scores:", scores.round(3))
print(f"mean = {scores.mean():.3f}, std = {scores.std():.3f}")fold scores: [0.965 0.93 0.912 0.939 0.938]
mean = 0.937, std = 0.017
Report the mean as your estimate and the standard deviation as a measure of how stable it is. Note that cross_val_score clones the model for every fold, so you don't need to fit it first.
Stratified k-fold
For classification, each fold should contain the classes in about the same proportions as the full data set — especially when one class is rare. StratifiedKFold guarantees this. In fact, when you pass cv=5 with a classifier, scikit-learn uses stratified folds automatically:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import KFold, StratifiedKFold
X, y = load_breast_cancer(return_X_y=True)
print("whole data set: share of class 1 =", round(y.mean(), 3))
for name, splitter in [("KFold ", KFold(n_splits=5)),
("StratifiedKFold", StratifiedKFold(n_splits=5))]:
shares = [round(float(y[val].mean()), 3) for _, val in splitter.split(X, y)]
print(name, shares)whole data set: share of class 1 = 0.627
KFold [0.404, 0.57, 0.649, 0.746, 0.77]
StratifiedKFold [0.623, 0.623, 0.632, 0.632, 0.628]
Without shuffling, plain KFold takes consecutive blocks of rows, and because this data set isn't randomly ordered the class shares jump around. Stratified folds stay close to the overall share.
Comparing models fairly
The real use of cross validation is choosing between models or settings. Here we compare tree depths using 5-fold stratified CV:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
for depth in [1, 2, 3, 5, None]:
scores = cross_val_score(DecisionTreeClassifier(max_depth=depth, random_state=0), X, y, cv=5)
print(f"max_depth={str(depth):4} mean={scores.mean():.3f} std={scores.std():.3f}")max_depth=1 mean=0.900 std=0.016
max_depth=2 mean=0.928 std=0.010
max_depth=3 mean=0.917 std=0.022
max_depth=5 mean=0.916 std=0.016
max_depth=None mean=0.917 std=0.016
This is exactly what GridSearchCV does internally for every combination in its grid.
Other strategies
| Splitter | Idea | Typical use |
|---|---|---|
KFold |
k consecutive (optionally shuffled) folds | regression |
StratifiedKFold |
folds keep class proportions | classification (default) |
LeaveOneOut |
k = number of rows: train on all but one | very small data sets |
ShuffleSplit |
many independent random train/test splits | large data sets |
TimeSeriesSplit |
always validate on later rows than training | time-ordered data |
GroupKFold |
all rows of one group stay in the same fold | several rows per patient/customer |
from sklearn.datasets import load_wine
from sklearn.model_selection import LeaveOneOut, ShuffleSplit, cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_wine(return_X_y=True)
X, y = X[::3], y[::3] # a small sample: every third wine
model = DecisionTreeClassifier(max_depth=3, random_state=0)
loo = cross_val_score(model, X, y, cv=LeaveOneOut())
print(f"Leave-one-out: {len(loo)} fits, mean accuracy {loo.mean():.3f}")
ss = cross_val_score(model, X, y, cv=ShuffleSplit(n_splits=10, test_size=0.3, random_state=0))
print(f"ShuffleSplit: {len(ss)} fits, mean accuracy {ss.mean():.3f}")Leave-one-out: 60 fits, mean accuracy 0.917
ShuffleSplit: 10 fits, mean accuracy 0.906
Each leave-one-out score is either 0 or 1 (one test row, right or wrong), so only the mean is meaningful.
Tip:
cross_validate(with a -e) returns several metrics at once plus fit times:cross_validate(model, X, y, cv=5, scoring=["accuracy", "f1"]).
Go further: Stratified and Group Cross-Validation keeps related rows on one side of each fold, and Nested Cross-Validation scores a model that was tuned with cross-validation.
Test yourself
In 5-fold cross validation, how many times is the model trained?
- 1
- 4
- 5
- 10
Why use stratified folds for classification?
- They are faster
- Each fold keeps roughly the original class proportions
- They remove outliers
- They use more data for training
Which splitter should you use for data ordered in time, such as daily sales?
KFold(shuffle=True)LeaveOneOutTimeSeriesSplitStratifiedKFold