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.
- train_test_split with test_size and random_state
- Keeping the class balance with stratify
- Checking the shapes and class counts of each part
- 120 rows
- 40 per class
- 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.
X, y📚 All the questions and answersX_train, y_train📝 Practice sheets the model learns fromX_test, y_test🔒 Exam questions kept backstratify=y⚖️ Same mix of topics in both pilestrain_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
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.
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
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())
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.
- 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.
Common mistakes
Mixing up the order of the results
The four arrays always come back as X_train, X_test, y_train, y_test.
X_train, y_train, X_test, y_test = train_test_split(X, y)
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.
train_test_split(X, y, test_size=0.2)
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
- Data Preparation for Machine Learning in PythonScale features with min-max normalization and z-score standardization, and multiply matrices by hand.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.