Representativeness, splits and leakage
Clean data can still mislead if it's unrepresentative or leaks the answer. This module covers the checks that separate trustworthy models from impressive-looking ones.
Learning objectives
- Compare a dataset's make-up with the population the model will serve
- Recognise proxies and historical bias in data
- Choose stratified, time-based or entity-based splits
- Identify four kinds of data leakage
- Build a leakage-safe preprocessing pipeline
- Demonstrate contamination with a group split
- Split time-ordered data correctly
Setup: the cleaned data from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport pandas as pd
import numpy as np
customers = pd.DataFrame({
"customer_id": [101, 102, 103, 103, 104, 105, 106, 107, 108, 109],
"signup_date": ["2025-01-04", "04/02/2025", "2025-02-10", "2025-02-10", "2025-03-15",
"2025-13-01", "2025-04-02", None, "2025-05-20", "2025-06-01"],
"country": ["UK", "United Kingdom", "uk", "uk", "Ireland", "UK", "IE", "UK", "U.K.", "UK"],
"age": [34, 29, None, None, 41, 230, 38, 27, -1, 52],
"monthly_spend": [42.5, 18.0, 63.2, 63.2, None, 25.0, 12000.0, 31.4, 22.0, 47.9],
"churned": ["no", "yes", "No", "No", "no", "yes", "no", "YES", "no", "no"],
})
clean = customers.drop_duplicates().reset_index(drop=True)
country_map = {"uk": "UK", "united kingdom": "UK", "u.k.": "UK", "ireland": "IE", "ie": "IE"}
clean["country"] = clean["country"].str.strip().str.lower().map(country_map).fillna(clean["country"])
clean["churned"] = clean["churned"].str.strip().str.lower().map({"yes": True, "no": False})
dates = pd.to_datetime(clean["signup_date"], format="%Y-%m-%d", errors="coerce")
alt = pd.to_datetime(clean["signup_date"], format="%d/%m/%Y", errors="coerce")
clean["signup_date"] = dates.fillna(alt)
clean.loc[(clean["age"] < 16) | (clean["age"] > 110), "age"] = np.nan
clean["age_missing"] = clean["age"].isna()
clean["age"] = clean["age"].fillna(clean["age"].median())
clean.loc[clean["monthly_spend"] > 1000, "monthly_spend"] /= 1005.1 Is your data representative?
A dataset can be clean and still give a misleading picture if it doesn't reflect the people and situations the model will meet. Compare the make-up of your data with the population the model will serve: regions, age groups, languages, device types, customer segments, time periods.
Python · compare data with the population you'll servedata_share = clean["country"].value_counts(normalize=True)
target_share = pd.Series({"UK": 0.70, "IE": 0.30}) # from business records
compare = pd.DataFrame({"in_data": data_share, "target": target_share}).round(2)
compare["gap"] = (compare["in_data"] - compare["target"]).round(2)
print(compare)
If a group is under-represented, consider collecting more data, re-weighting, or at least measuring performance for that group separately — and documenting the limitation.
Representativeness is about more than headcounts. Ask how the data was collected and who that leaves out: a survey sent by email misses customers who never gave an address; support tickets over-represent unhappy customers; data from the last two months misses the Christmas rush. The same applies to the documents and examples used to test an AI assistant: if every test question is in formal English, you have learned nothing about how it copes with the way customers really write.
5.2 Watch for proxies and historical bias
Features like postcode, school or employment gaps can act as proxies for protected characteristics. Labels based on past human decisions can carry past unfairness. These are data problems before they are model problems — see Responsible AI, Module 3.
5.3 Splitting data correctly
Python · a stratified train/test splitfrom sklearn.model_selection import train_test_split
X = clean[["age", "monthly_spend", "country"]]
y = clean["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y) # keeps the churn rate similar in both
print("Training rows:", len(X_train), " Test rows:", len(X_test))
print("Churn rate, train:", y_train.mean().round(2), " test:", y_test.mean().round(2))
- Stratify on the label (and sometimes key groups) so rare classes appear in both splits.
- Split by time when predicting the future: train on older data, test on newer — never the reverse.
- Split by entity (customer, patient) so the same person doesn't appear in both training and testing.
With nine rows, the split is only an illustration: a two-row test set can't tell you anything. The sections below use larger made-up datasets so the effects are visible.
5.4 Data leakage
Leakage happens when information that wouldn't be available at prediction time sneaks into training — producing models that look brilliant in testing and fail in reality.
| Leak | Example |
|---|---|
| Target leakage | Using "cancellation_reason" to predict churn — it only exists after churn |
| Train–test contamination | Duplicates or the same customer in both splits |
| Preprocessing leakage | Calculating means or scaling on the full dataset before splitting |
| Time leakage | Using next month's data to predict this month |
5.5 Preparing features: encoding and scaling inside a pipeline
Models need numbers. Categories are commonly one-hot encoded (a 0/1 column per category), and numeric features are often scaled to similar ranges. Wrapping these steps in a scikit-learn pipeline fits them on training data only — the standard defence against preprocessing leakage.
Python · leakage-safe preprocessing pipelinefrom sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
numeric = ["age", "monthly_spend"]
categorical = ["country"]
preprocess = ColumnTransformer([
("num", Pipeline([("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())]), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
preprocess.fit(X_train) # learns medians, scales and categories from TRAINING data only
X_train_ready = preprocess.transform(X_train)
X_test_ready = preprocess.transform(X_test)
print(pd.DataFrame(X_train_ready, columns=preprocess.get_feature_names_out()).round(2))
You'll attach a model to the end of this pipeline in Machine Learning Fundamentals.
5.6 Watch leakage happen
Leakage is easier to believe once you've seen it. The cell below builds 300 customers whose label is pure chance, so no honest model can beat 50%. Each customer appears three times (think of three monthly snapshots). Then it splits the rows two ways.
Python · the same customers on both sides of the splitfrom sklearn.model_selection import GroupShuffleSplit
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
people = pd.DataFrame({"customer": range(300),
"feature_a": rng.normal(size=300), "feature_b": rng.normal(size=300),
"label": rng.integers(0, 2, 300)}) # label is random: nothing to learn
rows = pd.concat([people] * 3, ignore_index=True) # each customer appears 3 times
feats = ["feature_a", "feature_b"]
# 1. Split rows at random: the same customer lands in both training and test
tr, te = train_test_split(rows, test_size=0.25, random_state=0)
leaky = DecisionTreeClassifier(random_state=0).fit(tr[feats], tr["label"])
print("Random row split: test accuracy", round(leaky.score(te[feats], te["label"]), 2))
# 2. Split by customer: nobody appears on both sides
tr_idx, te_idx = next(GroupShuffleSplit(test_size=0.25, random_state=0).split(rows, groups=rows["customer"]))
tr, te = rows.iloc[tr_idx], rows.iloc[te_idx]
honest = DecisionTreeClassifier(random_state=0).fit(tr[feats], tr["label"])
print("Split by customer: test accuracy", round(honest.score(te[feats], te["label"]), 2))
The first model scores well above 90% on a problem with nothing to learn. It hasn't found a pattern; it has memorised customers it then meets again in the test set. Split by customer and the score falls to about a coin toss, which is the truth. Any real project that reports the first number would be deployed and then fail.
5.7 Splitting by time
When a model will be used to predict the future, the test set must come after the training set. A random split lets the model study next month before being examined on last month.
Python · train on the past, test on the most recentorders = pd.DataFrame({
"date": pd.date_range("2026-01-01", periods=12, freq="MS"),
"sales": [120, 115, 130, 142, 150, 149, 160, 171, 168, 180, 240, 310],
})
cutoff = "2026-10-01"
train_period = orders[orders["date"] < cutoff]
test_period = orders[orders["date"] >= cutoff]
print("Train:", train_period["date"].min().date(), "to", train_period["date"].max().date(), f"({len(train_period)} months)")
print("Test: ", test_period["date"].min().date(), "to", test_period["date"].max().date(), f"({len(test_period)} months)")
print("Average sales, train:", train_period["sales"].mean().round(0), " test:", test_period["sales"].mean().round(0))
The test months include the pre-Christmas surge, which the training months never saw. That makes the test harder — and far more honest about how the model will cope next winter.
A survey dataset has the age-band counts in the starter code, and the customer base is known to be 20% under 30, 50% aged 30–59 and 30% aged 60+. Build a comparison table with the gap for each band. Which group is under-represented, and what could you do about it?
Your turnsurvey = pd.Series({"under 30": 180, "30-59": 280, "60+": 40}) # number of responses
# Compare with the target shares, then press RunShow a solution
survey = pd.Series({"under 30": 180, "30-59": 280, "60+": 40}) # number of responses
in_data = (survey / survey.sum()).round(2)
target = pd.Series({"under 30": 0.20, "30-59": 0.50, "60+": 0.30})
table = pd.DataFrame({"in_data": in_data, "target": target})
table["gap"] = (table["in_data"] - table["target"]).round(2)
print(table)
# Customers aged 60+ are badly under-represented (8% of the data, 30% of customers).
# Options: collect more (phone or post, not just online), re-weight, and report results for that group separately.Each feature in the starter list is proposed for a model that predicts, on the day an order is placed, whether it will be returned. Sort them into safe and leaky, with a reason for each leaky one.
Your turnfeatures = ["product_category", "order_value", "refund_amount", "customer_past_returns",
"days_until_returned", "delivery_country", "customer_service_notes_after_delivery"]
# Decide which are safe and which leak, then press RunShow a solution
features = ["product_category", "order_value", "refund_amount", "customer_past_returns",
"days_until_returned", "delivery_country", "customer_service_notes_after_delivery"]
leaky = {
"refund_amount": "only exists after a return",
"days_until_returned": "is the outcome itself in another form",
"customer_service_notes_after_delivery": "written after the moment of prediction",
}
safe = [f for f in features if f not in leaky]
print("Safe: ", safe)
for f, why in leaky.items():
print("Leaky:", f, "-", why)
# The test: would you know this value at the moment you need the prediction?Key takeaways
- Representativeness is a data quality issue — measure it.
- Proxies and historical labels can encode unfairness.
- Stratify; split by time for forecasting; split by entity.
- Leakage produces great test scores and poor real-world performance.
- Pipelines fit preprocessing on training data only.
- If the same customer is on both sides of a split, the test score is fiction.
- Ask of every feature: would I know this at the moment of prediction?