Monday , November 30 2026
How to use train_test_split in scikit-learn: test_size, random_state, stratify, train/validation/test splits, TimeSeriesSplit and common leakage mistakes.

Train-Test Split in Python (scikit-learn) with Examples

Updated: 29 November 2026Level: BeginnerReading time: about 7 minutesscikit-learn 1.x · tested

To know whether a model will work on new data, we must test it on data it did not see during training. train_test_split divides a dataset into a training set and a test set in one line.

What You Will Learn

  • Why we split data
  • Use train_test_split with test_size, random_state and stratify
  • Train / validation / test splits
  • Time-series splits
  • Common mistakes

Basic Split

Example
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import numpy as np

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y)
print(X_train.shape, X_test.shape)
print(np.bincount(y_train), np.bincount(y_test))
Output
(426, 30) (143, 30)
[159 267] [53 90]

Explanation: 25% of the 569 rows go to the test set. random_state makes the shuffle reproducible. stratify=y keeps the class ratio (about 37% malignant) the same in both sets – important for imbalanced data.

Parameter Meaning
test_size Fraction (0.2) or number of rows for the test set
train_size Optional; the rest goes to test
random_state Seed for reproducible shuffling
shuffle Default True; set False for ordered data
stratify Keep class proportions, usually stratify=y

Train / Validation / Test

Example
X_tmp, X_test, y_tmp, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_train, X_val, y_train, y_val = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
print(len(X_train), len(X_val), len(X_test))
Output
341 114 114

Explanation: A 60/20/20 split. Tune hyperparameters on the validation set and look at the test set only once at the end. With small datasets, use k-fold cross-validation instead of a single validation set.

Time-Series Data

Example
from sklearn.model_selection import TimeSeriesSplit
tscv = TimeSeriesSplit(n_splits=3)
for train_idx, test_idx in tscv.split(np.arange(12)):
    print(train_idx, test_idx)
Output
[0 1 2] [3 4 5]
[0 1 2 3 4 5] [6 7 8]
[0 1 2 3 4 5 6 7 8] [ 9 10 11]

Explanation: For data ordered in time, never shuffle – you would be training on the future. TimeSeriesSplit always tests on later data than it trains on.

Common Mistakes

  • Scaling or imputing on the full dataset before splitting – the test data leaks into training. Fit preprocessing on the training set only, ideally inside a pipeline.
  • Tuning repeatedly on the test set, which makes the final score optimistic.
  • Duplicate rows (or the same customer) appearing in both sets – use GroupShuffleSplit.
  • Forgetting stratify on imbalanced classes.

Series

ML fundamentals series: What is ML · Types of ML · Train/Test Split · Overfitting & Bias-Variance · Regularization · Confusion Matrix · ROC & AUC · Cross-Validation · Ensembles · DBSCAN

Interview Questions

Q: Why split into train and test sets?
To estimate performance on unseen data and detect overfitting.

Q: What does stratify do?
Keeps the class proportions equal in the train and test sets.

Q: Why not shuffle time-series data?
The model would learn from future data, giving unrealistically good scores.

Practice Exercises

  1. Split with and without stratify on an imbalanced dataset and compare class counts.
  2. Use GroupShuffleSplit to keep all rows of a customer in one set.

Summary

Split before any preprocessing, stratify classification data, keep a validation set or use cross-validation for tuning, and use time-ordered splits for time series.

Next: Overfitting and Underfitting

About Machine Learning

Check Also

Confusion Matrix in Machine Learning (with Python Example)

Confusion matrix explained with a tested scikit-learn example: TP, TN, FP, FN, classification report, metrics formulas and the effect of thresholds.