Skip to content

MLDay 6 of 50Foundations

Split Data Without Leaking

Your bike-rental model scores zero error.

7 min read

Your bike-rental model scores zero error. That should worry you, not please you. Either the model saw the answers, or the test asked an easier question than the one it will face next week.

The idea

A score only means something if it comes from rows the model never saw. So before you fit anything, hold some rows back. The rows you fit on are the training set; the rows you hold back are the test set. Cutting the data in two like this is a train/test split. The test score estimates how the model will do on new data, which is the only score that matters.

Leakage is any way the answer sneaks into training that won't exist when the model is in use. It makes the test score look better than the truth. Two kinds are common:

  • A feature that contains the answer, or that is only known after the fact.
  • Preprocessing that learns from every row, test rows included. Say you fill gaps with a column's average. Work that average out from the training rows only.

Time adds a third trap. When rows are ordered in time and you'll predict the future, a shuffled split hides future rows in the training set. The model then fills gaps between days it knows, which is easier than predicting days that come after everything it knows. A time-ordered split (also called chronological) trains on the earlier rows and tests on the latest ones.

Last rule: the test set stays locked until the end. If you try 20 models and keep the one with the best test score, the test set helped choose. It's no longer unseen, and its score now flatters the winner. Day 10 shows how to compare models without touching it.

A tiny example

Three real hours from Wednesday 6 June 2012. The dataset counts casual riders (no membership) and registered riders (members) separately, and cnt is all rentals:

Hour casual registered cnt
8 am 31 637 668
noon 80 235 315
6 pm 94 688 782

The rule "cnt = casual + registered" is never wrong: 31 + 637 = 668, 80 + 235 = 315, 94 + 688 = 782. A model that finds it gets zero error on any test set.

But at 7 am, when the crew decides how many bikes to put out for 8 am, nobody has counted the 8 am riders yet. Both columns are counts of the very thing you're predicting. Ask of every feature: will I know this at the moment I predict? If not, drop it.

Try it

Sixteen weeks at a new dock

The line is fitted on the training rows only. The test rows are the exam it never studied for: their RMSE is the honest score.

051015100200300400Week since the dock openedRentals that weektrain: Week since the dock opened = 1, Rentals that week = 122test: Week since the dock opened = 2, Rentals that week = 149train: Week since the dock opened = 3, Rentals that week = 200train: Week since the dock opened = 4, Rentals that week = 219test: Week since the dock opened = 5, Rentals that week = 262train: Week since the dock opened = 6, Rentals that week = 266train: Week since the dock opened = 7, Rentals that week = 277train: Week since the dock opened = 8, Rentals that week = 305train: Week since the dock opened = 9, Rentals that week = 307train: Week since the dock opened = 10, Rentals that week = 329train: Week since the dock opened = 11, Rentals that week = 320train: Week since the dock opened = 12, Rentals that week = 335train: Week since the dock opened = 13, Rentals that week = 333test: Week since the dock opened = 14, Rentals that week = 346test: Week since the dock opened = 15, Rentals that week = 337train: Week since the dock opened = 16, Rentals that week = 351

training row (12)test row (4)

train RMSE 24.12test RMSE 32.87test is 8.75 worse

A line is fitted to the training weeks, and the highlighted test weeks are scored with RMSE, the typical miss from Day 5. Start on Random split, then switch to Split by time: the test becomes the last four weeks. Rentals level off there, but a line fitted to the early growth keeps climbing, so the test RMSE jumps to 68 while the training RMSE is 20. Almost every random split looks better: 1,817 of the 1,820 ways to pick four test weeks give a lower test RMSE (press New random split a few times to see). Then tick Fit on all rows, test included, which fits the line on all 16 weeks. The test RMSE drops to 23, a fake score, because the model has seen those weeks.

In code

scikit-learn's train_test_split holds back a fraction of the rows (test_size=0.25 is a quarter). This scores a temperature model three ways on 17,379 real hours. The casual and registered columns go in as extra features in the leaky run; Day 7 explains how a line handles several features.

# script_id: day_006_splitting_without_leakage/three_splits
import os
from pathlib import Path

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import train_test_split

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
df = df.assign(temp_c=df["temp"] * 41)                    # undo the ÷ 41

def score(columns, shuffle):
    X_train, X_test, y_train, y_test = train_test_split(
        df[columns], df["cnt"], test_size=0.25, shuffle=shuffle, random_state=42)
    model = LinearRegression().fit(X_train, y_train)
    train = root_mean_squared_error(y_train, model.predict(X_train))
    test = root_mean_squared_error(y_test, model.predict(X_test))
    print(f"train {train:5.1f}  test {test:5.1f}  weights {model.coef_.round(2)}")

score(["temp_c", "casual", "registered"], shuffle=True)   # leaky features
score(["temp_c"], shuffle=True)                          # clean feature, shuffled hours
score(["temp_c"], shuffle=False)                         # clean feature, last 25% of hours held out
train   0.0  test   0.0  weights [0. 1. 1.]
train 166.6  test 163.7  weights [9.28]
train 146.2  test 217.2  weights [8.52]

The leaky model learned weights 0, 1 and 1: it ignores temperature and adds up the two rider counts. Its perfect score is worthless at 7 am.

The two clean runs use the same model and the same feature. The shuffled split says the model misses by about 164 rentals an hour. The time-ordered split trains on January 2011 to early July 2012, tests on the rest of 2012, and misses by 217. Rentals grew in 2012, and the shuffled model had already seen hours from every month. The time split asks the real question, so 217 is the honest score.

Quick check

Quick check

1. You predict tomorrow's 8 am rentals at 7 am. Which column leaks?

2. You have hourly rentals for 2011–2012 and will predict next month. How should you split?

3. You tried 20 models and kept the one with the best test RMSE. What's the problem?

Next

One feature misses the future by 217 rentals an hour; Day 7 gives the model several features at once.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.

Next · Day 7 · 8 minUse Many Features: Multiple Linear Regression← Previous: Day 5 · Measure Error: MSE, RMSE and MAE
Not tapped yet