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.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez Cross Validation in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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.

Quand l’utiliser ?

  • Train and evaluate classic machine learning models on tabular data.
  • Prepare features: split, scale and encode data the way real projects do.
  • Compare models fairly with cross-validation and the right metric.

Code d’exemple

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}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

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

Explication du code

Cet exemple montre Cross Validation in Python with scikit-learn en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon