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.
- cross_val_score with cv=5
- StratifiedKFold with shuffle
- Changing the metric with scoring
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.
cv=5📚 Split the questions into 5 pilestrain on 4, test on 1📝 Five exams, each on a different pilescores.mean()🎓 The average gradescores.std()📉 How much the grades varyk-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
cross_val_score(model, X, y, cv=5)returns 5 accuracies, one per fold.- The mean is 0.981 with a standard deviation of 0.007.
- The scaler inside the pipeline is refitted on the training part of each fold.
StratifiedKFold(shuffle=True, random_state=42)andscoring="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
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}")
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.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Scaling before cross-validation
The scaler sees every fold's test rows, which leaks information into the score.
cross_val_score(LogisticRegression(), StandardScaler().fit_transform(X), y)
cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X, y)
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.