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.

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

  1. test_size=0.2 keeps 20% of the rows for testing: 30 of the 150 iris flowers.
  2. It returns four arrays in a fixed order: X_train, X_test, y_train, y_test.
  3. stratify=y keeps the class balance, so each part has the same share of every class.
  4. random_state=42 fixes 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())
Obtenir un bouton Run pour cet exemple

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.

  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