Skip to main content
Albero Academy

Datasets & Splitting

Load data and hold out a test set the right way.

Foundations8 min

To know if a model generalises, you evaluate it on data it never saw. train_test_split holds out a portion for testing — the single most important habit in ML.

train_test_split

hold out a test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.2, # 20% held out for testing
random_state=42, # reproducible split
stratify=y, # keep class proportions (classification)
)

Stratify for classification

Key takeaways

  1. 01train_test_split holds out a test set to measure generalisation.
  2. 02test_size sets the held-out fraction (commonly 0.2–0.3).
  3. 03random_state makes the split reproducible.
  4. 04stratify=y preserves class proportions — important for imbalanced classification.

Finished this chapter?

Mark it complete to track your progress through Scikit-learn.