🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Cross-Validation

Cross-validation is a check that trains and tests a model several times on different folds. Each fold takes a turn as the test set.

Five folds, five scores

cross_val_score() trains the tree five times. Each fold gives its own score, and the scores are not all the same.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=3, random_state=42)
scores = cross_val_score(tree, X_train, y_train, cv=5)
print([round(float(s), 3) for s in scores])

The mean and the spread

The mean score is 0.932, and the spread is 0.044. One lucky split could report 0.945, and one unlucky split 0.901.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=3, random_state=42)
scores = cross_val_score(tree, X_train, y_train, cv=5)
print(round(scores.mean(), 3))
print(round(scores.max() - scores.min(), 3))

Stratified folds keep the mix

StratifiedKFold keeps the benign and malignant mix the same in every fold. Its mean score matches the plain folds here.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=3, random_state=42)
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(tree, X_train, y_train, cv=folds)
print([round(float(s), 3) for s in scores])
print(round(scores.mean(), 3))

Example

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, StratifiedKFold, train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
tree = DecisionTreeClassifier(max_depth=3, random_state=42)
scores = cross_val_score(tree, X_train, y_train, cv=5)
print("Fold scores:", [round(float(s), 3) for s in scores])
print("Mean score:", round(scores.mean(), 3))
print("Lowest fold:", round(scores.min(), 3))
print("Highest fold:", round(scores.max(), 3))
print("Spread:", round(scores.max() - scores.min(), 3))
tree.fit(X_train, y_train)
print("One split test accuracy:", round(tree.score(X_test, y_test), 3))
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
strat_scores = cross_val_score(tree, X_train, y_train, cv=folds)
print("Stratified fold scores:", [round(float(s), 3) for s in strat_scores])
print("Stratified mean:", round(strat_scores.mean(), 3))

Key points

  • Fold: one slice of the data that takes a turn as the test set
  • k-fold: cross-validation with k folds, so the model trains k times
  • Use cross_val_score() to run k-fold and get one score per fold
  • Use StratifiedKFold to keep the class mix the same in every fold
  • The mean of the fold scores is a steadier score than one split
  • The spread between the lowest and highest fold shows how much one split can lie
  • Use cv=5 for five folds, which is the usual starting point

In this example, the breast cancer measurements return, each row carrying a benign or malignant label. A fifth of the rows still stays aside for the final test. cross_val_score() runs a tree with max_depth=3 through five folds on the training rows. The fold scores are 0.945, 0.901, 0.945, 0.934, and 0.934, so the mean is 0.932 and the spread is 0.044. One split alone reports 0.947, which sits above the mean. Stratified folds give the same mean of 0.932.

Note

Cross-validation checks the model. The held-out test set still stays untouched until the end.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why can one train and test split lie about a model?