cat /en/where-the-leak-hides/
MDN-118:50
SERIES Inside Ordito · Chapter 3

Where the leak hides

· Artificial Intelligence · 5 min read

How much will a new store take? To answer, we have 113 rows: 39 Ordito stores, each with the revenue of one, two or three years. A regression model learns from the floor area, the population, the income of the area. The problem is giving it an honest grade.

Two ways of splitting

Cross-validation splits the data into five parts, trains the model on four and measures it on the fifth, in turn. KFold splits the rows at random. But the rows are not independent: three years of the same store resemble each other. If one year ends up in the test set and the other two in the training set, the model is being examined on a store it already partly knows.

GroupKFold splits by groups: each store sits entirely on one side. This is the real situation, because a new store has no siblings in the training set.

In the lab, each small square is one store in one year. In amber the test fold, in red the years of the same store left in the training set: the leaks.

DEMO Where the leak hides · about this demo · full screen ↗

Three experiments

The grade that is too good. With KFold almost every test row has a sibling in the training set. The MAE goes down: in the book, 145.5 thousand euros.

The honest grade. With GroupKFold the red squares disappear and the MAE goes up: in the book, 170.0. This is the number to present to management. The difference does not come from an error in the code, which runs without complaint, but from an error in the reasoning.

The lottery. Press “Nuova divisione a caso” (new random split) several times. With KFold the grade changes with the seed, and the histogram shows a hundred seeds: they all lie below the line of the per-store grade.

The same experiment in Python

The chapter’s pipeline: median for the missing floor area, standardisation, one-hot for type and parking, linear regression. The whole pipeline is retrained in every fold, so the median too is computed on the training rows alone.

import warnings
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import GroupKFold, KFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
warnings.filterwarnings("ignore")

URL = "https://raw.githubusercontent.com/mid079/machine-learning-teoria-pratica/main/dati/"
negozi = pd.read_parquet(URL + "negozi.parquet")
sc = pd.read_parquet(URL + "scontrini.parquet", columns=["data_ora", "id_negozio", "canale", "totale"])
sc = sc[sc["canale"] == "negozio"].assign(anno=lambda d: d["data_ora"].dt.year)
dati = (sc.groupby(["id_negozio", "anno"])["totale"].sum() / 1000).reset_index(name="incasso").merge(negozi, on="id_negozio")
dati = dati[dati["data_apertura"] < pd.to_datetime(dati["anno"].astype(str) + "-01-01")].copy()   # full years only
dati["anni_aperto"] = dati["anno"] - dati["data_apertura"].dt.year

numeriche = ["mq", "popolazione_comune_migliaia", "indice_reddito_area", "anni_aperto"]
preparazione = ColumnTransformer([
    ("numeri", Pipeline([("riempi", SimpleImputer(strategy="median")), ("scala", StandardScaler())]), numeriche),
    ("categorie", OneHotEncoder(drop="first"), ["tipo", "parcheggio"])])
modello = Pipeline([("prepara", preparazione), ("regressione", LinearRegression())])
for nome, cv in [("KFold", KFold(5, shuffle=True, random_state=42)), ("GroupKFold", GroupKFold(5))]:
    mae = -cross_val_score(modello, dati, dati["incasso"], groups=dati["id_negozio"], cv=cv, scoring="neg_mean_absolute_error")
    print(f"{nome:10s} mean MAE {mae.mean():.1f}")   # KFold is lower: it is an illusion

In the book

This lab accompanies chapter 3, “A project from start to finish”, which goes through the whole cycle of a project on the stores problem: the question, the data, the exploration, the split, the preparation, the model, the evaluation. Data leakage appears there in two forms: the median computed on the test set too, and the split that ignores the stores.

COVER COMING SOON
mltp · 2026

Machine Learning. Teoria, matematica e pratica degli algoritmi

Michele di Nuzzo · in Italian

Every algorithm in two steps: first derive it, with the mathematics it needs and an example worked by hand, then write it from scratch in NumPy. Only at the end use it with scikit-learn.

[the book’s page] [shop links coming soon]

The “Inside Ordito” series