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.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • 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

The problem

A model that is scored on the same rows it learned from looks better than it really is: it can simply remember the answers. To know how it will do on new data, you need rows it has never seen.

Think of it like this

Splitting data is like a teacher who keeps some exam questions out of the practice sheets. Students practise on the sheets, and the held-back questions show what they really learned. If the practice sheets contained the exam, every score would be perfect and meaningless.

From exam questions to code
X, y📚 All the questions and answers
X_train, y_train📝 Practice sheets the model learns from
X_test, y_test🔒 Exam questions kept back
stratify=y⚖️ Same mix of topics in both piles
The test set stays unseen until the final check.
In one sentence

train_test_split shuffles the rows of your features and labels and splits them into a training set and a test set, in the proportion you choose with test_size.

Key points

  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.

When should you use it?

  • Measuring how well a model works on new data.
  • Keeping a final test set aside while you tune a model.
  • Making results repeatable for reports and homework.

When not to use it

  • Small datasets where one split is too noisy: use cross-validation instead.
  • Time series: shuffling lets the model see the future, so split by date.

Example code

Open in editor →
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())
Get a Run button for this example

Result of running the code

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

Code explanation

load_iris returns 150 flowers, 50 of each class. train_test_split shuffles the rows and keeps test_size=0.2, so X_train gets 120 rows and X_test 30. stratify=y makes both parts keep the same class balance, which is why the test set has exactly 10 flowers of each class. random_state=42 fixes the shuffle, so calling it again gives the identical split, and the comparison prints True.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  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.
Run in the Python compiler →

Common mistakes

Mixing up the order of the results

The four arrays always come back as X_train, X_test, y_train, y_test.

Problem
X_train, y_train, X_test, y_test = train_test_split(X, y)
Fix
X_train, X_test, y_train, y_test = train_test_split(X, y)

Forgetting stratify on classification data

Without it, a rare class can end up missing from the test set.

Problem
train_test_split(X, y, test_size=0.2)
Fix
train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson