This is the first post in a series about Mensura, a programming language I am building in which data leakage is a compile-time error. Before any language, though, this post is about the problem: why leakage is so easy to write and so hard to notice. It is useful even if you never touch Mensura.
I started caring about this kind of leakage while teaching Machine Learning and Data Science to graduate students at the same time. In Machine Learning, we teach preprocessing and the train/test split as separate topics, and students often fail to connect the two. In Data Science, we teach many data handling techniques, and students often confuse which belong to collecting the data (selecting and joining tables, aggregating) and which belong to training the model (scaling, imputing, encoding). Both are the same mistake: a failure to understand the semantic changes an operation makes to the data. The result is a pipeline that runs without error but does not reflect how the model will be used.
A pipeline that looks fine
Suppose we want to predict whether a machine will fail within the next seven days. We have sensor readings, many per machine, and a label for each reading. Here is a perfectly ordinary scikit-learn script:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
df = pd.read_csv("readings.csv") # one row per reading, many readings per machine
df["temp"] = df["temp"].fillna(df["temp"].mean()) # (1)
X = df[["temp", "vibration", "machine_age"]]
y = df["fails_within_7d"]
X_tr, X_te, y_tr, y_te = train_test_split( # (2)
X, y, test_size=0.2, random_state=0)
model = RandomForestClassifier().fit(X_tr, y_tr)
print(roc_auc_score(y_te, model.predict_proba(X_te)[:, 1]))
It runs. No warnings. The AUC is excellent. And the number is wrong, for two independent reasons.
(1) The imputation looked at the test set. The mean used to fill missing temperatures was computed over all rows, including those that will later be used for evaluation. Information about the test data flowed into the training data before the split even happened. In this example the effect is probably small; with target encoding, feature selection, or scaling by global statistics, it can be large.
(2) The split is over readings, not machines. train_test_split shuffles
rows. Machine 17 has two hundred readings; about one hundred and sixty go to
training and forty to test. The model does not need to learn what precedes a
failure. It only needs to recognize machine 17, whose readings look alike
and share the same label in the days before it breaks. The test set is
measuring memory, not prediction.
In production, the model meets machines it has never seen, and the excellent AUC evaporates.
The fix is knowledge, not tooling
The corrected script is not longer:
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GroupShuffleSplit
from sklearn.pipeline import make_pipeline
gss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
tr, te = next(gss.split(X, y, groups=df["machine_id"])) # whole machines per side
model = make_pipeline(SimpleImputer(strategy="mean"), # mean learned on train only
RandomForestClassifier())
model.fit(X.iloc[tr], y.iloc[tr])
print(roc_auc_score(y.iloc[te], model.predict_proba(X.iloc[te])[:, 1]))
Here X is the raw feature frame, before the global fillna. Of course, a better
evaluation pipeline would use cross_val_score or similar to avoid a single lucky
split, but for the sake of this example let us focus on the two fixes: the imputer is now
inside a pipeline, and the split is done by machine ID.
Notice what made the difference. Not a new library, not more compute: the analyst had to know that readings of the same machine are not independent, and that every statistic must be learned inside the training fold. The first script and the second are equally valid Python. Nothing in pandas or scikit-learn can tell them apart, because the information that separates them (which rows belong to the same entity, and which data each statistic has seen) is not represented anywhere the tools can check.
Temporal data adds a third way to fail: a random split lets the model train on the future and be tested on the past. The fix is again a different splitter, and again the wrong one runs without complaint.
Why discipline does not scale
I teach this material every year in my graduate course, and I wrote a large part of a book about it. Students learn the rules. Then the pipeline grows: a join here, a feature computed by a colleague there, a dataset that turned out to have repeated customers. Each step is reasonable on its own. The leak appears in the composition, and it appears silently. This happens even more often when using tools like Jupyter notebooks, where the order of execution is not guaranteed to match the order of the cells.
That is the property that makes leakage different from most bugs. A crash announces itself. A leaked metric looks better than the honest one, so it is the last result anyone feels like questioning. Code review rarely catches it, because the reviewer would have to reconstruct how every row reached every table. Unit tests rarely catch it, because the code does exactly what it says.
What if the compiler knew?
Programming languages solved a similar problem long ago. We stopped relying on discipline to avoid adding a string to an integer; the type checker refuses. The question behind Mensura is whether the facts that separate the two scripts above can be types too:
- these two tables share no entity (no machine on both sides);
- this table was derived without looking at that one (no statistic learned on the test set);
- these rows are ordered in time, so only temporal splits are allowed.
If those facts live in the type of a table, then a split that scatters one machine across training and test is not a bad practice to remember; it is a program that does not compile. A design preview of what that looks like (the syntax is still evolving, and the learning operations are not implemented yet):
let (train, test) = readings |> split |k| hash k < 0.8 // disjoint by construction
let model = train |> fit random_forest
let score = test |> evaluate model // demands: train and test disjoint
Getting there takes more than adding annotations to a dataframe library. It needs a precise definition of what a table is, which operations preserve which facts, and proofs that the rules are sound. That is the story of the next posts.
Mensura is open source and early. If you want to follow along, the repository is at github.com/mensura-lang/mensura. Comments are open below; I would like to hear about the leaks that bit you.