Split data and compare with a baseline

scikit-learn 1.9.1

Hold out rows for evaluation, and use a simple prediction rule as a reference.

On this page

Choose a split that matches the task

For independent rows, train_test_split can shuffle and hold out part of the data. random_state makes that split repeatable. Consider stratify=y for classification when enough examples of each class exist. Use time-aware or group-aware splitting when rows are dependent.

from sklearn.model_selection import train_test_split

train, test = train_test_split(list(range(20)), test_size=0.25, random_state=42)
print(len(train), len(test))
Twenty records divide into fifteen training records and five test records. Download image
A test size of 0.25 holds out one-quarter of these records for evaluation.
Example output
15 5

Build a simple comparison

A median-price baseline learns the median of the training targets and predicts it for every test row. Compare models using the same untouched test rows and the same metric.

from sklearn.dummy import DummyRegressor

baseline = DummyRegressor(strategy="median")
baseline.fit([[1], [2], [3]], [5, 6, 20])
print(baseline.predict([[8], [9]]).tolist())
Example output
[6.0, 6.0]

Official references