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.
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
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.
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}")
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.
- 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.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
Outils pour cette leçon
- Jupyter Notebook en ligne : exécuter des cellules Python dans le navigateurJupyter Notebook en ligne gratuit : exécutez des cellules Python avec pandas, NumPy et Matplotlib, ajoutez du texte en Markdown, ouvrez et téléchargez des fichiers .ipynb. Sans installation, sans compte.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.
- Exercices Python corrigés : s'entraîner en ligne gratuitementExercices Python corrigés pour débutants et défis vérifiés automatiquement, du plus facile au plus difficile. À faire dans le navigateur, sans installation.