Machine Learning with scikit-learn

Cross Validation in Python with scikit-learn

Get a reliable score by training and testing on 5 different splits, then report the mean and the spread.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • cross_val_score with cv=5
  • StratifiedKFold with shuffle
  • Changing the metric with scoring
5 folds: T = test part
T
T
T
T
T

Testing on every part of the data

The problem

A single train/test split can be lucky or unlucky, and the score can change by several points just by changing random_state. You need a score you can trust.

Think of it like this

Cross-validation is like giving a class five different exams, each made from a different fifth of the question bank, and averaging the grades. One hard or easy exam no longer decides the result.

From five exams to code
cv=5📚 Split the questions into 5 piles
train on 4, test on 1📝 Five exams, each on a different pile
scores.mean()🎓 The average grade
scores.std()📉 How much the grades vary
Every row is used for testing exactly once.
In one sentence

k-fold cross-validation splits the data into k parts, trains on k-1 of them and tests on the remaining one, k times, and averages the k scores.

Key points

  1. cross_val_score(model, X, y, cv=5) returns 5 accuracies, one per fold.
  2. The mean is 0.981 with a standard deviation of 0.007.
  3. The scaler inside the pipeline is refitted on the training part of each fold.
  4. StratifiedKFold(shuffle=True, random_state=42) and scoring="f1" change the folds and the metric.

When should you use it?

  • Comparing models fairly.
  • Small datasets where one test set is too small.
  • Tuning hyperparameters (GridSearchCV uses it inside).

When not to use it

  • Time series: use TimeSeriesSplit so the model never trains on the future.
  • Huge datasets where one large test set is already reliable and training is slow.

Example code

Open in editor →
main.py
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))

# 5-fold: train on 4 parts, test on the 5th, five times
scores = cross_val_score(model, X, y, cv=5)
print("Fold scores:", [round(s, 3) for s in scores.tolist()])
print(f"Mean {scores.mean():.3f} +/- {scores.std():.3f}")

# Shuffled, stratified folds keep the class balance in every fold
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=folds, scoring="f1")
print("F1 per fold:", [round(s, 3) for s in scores.tolist()])
print(f"Mean F1 {scores.mean():.3f} +/- {scores.std():.3f}")
Get a Run button for this example

Result of running the code

Fold scores: [0.982, 0.982, 0.974, 0.974, 0.991]
Mean 0.981 +/- 0.007
F1 per fold: [0.979, 0.959, 0.973, 0.993, 0.993]
Mean F1 0.979 +/- 0.013

Code explanation

cross_val_score(model, X, y, cv=5) cuts the data into 5 parts, trains on 4 and tests on the remaining one, five times, and returns the five accuracies. Their mean is 0.981 and the standard deviation 0.007 shows how much the score moves between folds. The scaler lives inside the pipeline, so it is refitted on the training part of every fold. StratifiedKFold with shuffle=True and random_state=42 gives shuffled folds with the same class balance, and scoring="f1" switches the metric to F1.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Scaling before cross-validation

The scaler sees every fold's test rows, which leaks information into the score.

Problem
cross_val_score(LogisticRegression(), StandardScaler().fit_transform(X), y)
Fix
cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X, y)

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson