Machine Learning with scikit-learn
Train Test Split in Python with scikit-learn
Hold back part of your data as a test set with one call to train_test_split, so the score you report is honest.
Ce que vous allez apprendre
- train_test_split with test_size and random_state
- Keeping the class balance with stratify
- Checking the shapes and class counts of each part
150 iris flowers, test_size=0.2
X_train
- 120 rows
- 40 per class
X_test
- 30 rows
- 10 per class
Training data and test data
Découvrez Train Test Split in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.
Points clés
test_size=0.2keeps 20% of the rows for testing: 30 of the 150 iris flowers.- It returns four arrays in a fixed order:
X_train, X_test, y_train, y_test. stratify=ykeeps the class balance, so each part has the same share of every class.random_state=42fixes the shuffle, so the split is the same every time you run it.
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 collections import Counter
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
print("All data:", X.shape, dict(Counter(y.tolist())))
# Keep 20% for testing; stratify keeps the class balance in both parts
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print("Train:", X_train.shape, dict(sorted(Counter(y_train.tolist()).items())))
print("Test: ", X_test.shape, dict(sorted(Counter(y_test.tolist()).items())))
# The same random_state always gives the same split
again = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
print("Same split again:", (again[1] == X_test).all())
Résultat de l’exécution
All data: (150, 4) {0: 50, 1: 50, 2: 50}
Train: (120, 4) {0: 40, 1: 40, 2: 40}
Test: (30, 4) {0: 10, 1: 10, 2: 10}
Same split again: True
Explication du code
Cet exemple montre Train Test Split 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
- Préparation des données pour l'apprentissage automatique en PythonMettez les variables à l'échelle avec la normalisation min-max et la standardisation par score z, et multipliez des matrices à la main.
- 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.