🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Split Data into Train and Test

A train/test split cuts one dataset into two parts. The training part teaches, and the test part checks.

One table, 150 rows

The Iris data holds 150 rows and 4 number columns. The labels hold 150 species names.

from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
print(X.shape)
print(y.shape)

The split cuts 120 and 30

One fifth goes to the test set. The training set keeps 120 rows and the test set takes 30.

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape)
print(X_test.shape)

Both parts keep all three species

The test set holds 10, 9, and 11 flowers per species. The training set holds 40, 41, and 39.

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(np.unique(y_test, return_counts=True)[1].tolist())
print(np.unique(y_train, return_counts=True)[1].tolist())

Example

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print("All rows:", X.shape[0])
print("Train rows:", X_train.shape[0])
print("Test rows:", X_test.shape[0])
print("Train species counts:", np.unique(y_train, return_counts=True)[1].tolist())
print("Test species counts:", np.unique(y_test, return_counts=True)[1].tolist())
print("Test share:", len(X_test) / len(X))

Key points

  • Training set: the part of the data the program studies
  • Test set: the part of the data kept aside for the final check
  • train_test_split: the scikit-learn tool that cuts the data into two parts
  • Use test_size=0.2 to keep one fifth of the rows for the test set
  • random_state: a seed number that makes the same split every time it runs
  • Use random_state=42 so every reader gets the same split

In this example, the split uses test_size=0.2 and random_state=42. All 150 rows split into 120 for training and 30 for testing. The test share is 0.2, exactly one fifth. One dataset becomes two parts, and the small part stays aside until the final check.

Note

The test set stays untouched until the final check. Peeking at it early leaks answers into training.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why does the test set stay untouched?