Testing for data representativeness
Why This Matters
A model is only tested on the kind of data it was tested on. If the training and test data describe young applicants in five cities, and production serves older applicants in ten, every accuracy figure you reported is about a population the model does not serve. Representativeness testing asks the simple, uncomfortable question: does our data look like the real world the model will work in?
What you will learn
- The three steps of testing for data representativeness
- How to compare two datasets with EDA and with statistical tests (Kolmogorov-Smirnov, chi-squared)
- How to test the practice loan data against production, in code
Syllabus: AI-5.1.4.
Three steps
Representativeness measures how closely the training, validation and test data match the operational data.
1. Define the target population
Who and what will the model serve? Understand the use cases and the users. Identify the expected distributions (ages, incomes, regions, device types, lighting conditions) and the edge cases, with domain experts, existing data or trusted benchmarks (for example from NIST). Use stratified sampling to build a reference dataset that covers every subgroup in the right proportion.
2. Analyse the characteristics
Run EDA on the datasets you are evaluating and on the reference dataset:
- visualise distributions: histograms for numbers, bar charts for categories, scatter plots for pairs
- examine correlations: important relationships (income and credit score) should be the same in both
- find gaps and concentrations: groups that are missing, or over-represented
3. Assess statistically
Use formal tests to decide whether differences are real:
- Kolmogorov-Smirnov (KS) for a numeric feature: could two samples come from the same distribution? It measures the largest gap between their cumulative distributions (0 = identical, 1 = no overlap).
- Chi-squared for categories: are the proportions of cities, device types or classes the same?
- Class imbalance: is each class (approved, rejected) present in a useful proportion?
- Coverage: are the typical scenarios and the edge cases present?
Do this before training. After deployment the same comparison becomes drift monitoring (lesson 47): the training data was representative once; is it still?
Hands-on: training versus production
The practice API has a production dataset: 50 applications the loan model received after release, without labels. Compare it with the prepared training data. You continue in the practice project; create module-6/test_representativeness.py:
"""Lesson "Testing for data representativeness": does the training data represent what the model sees in production?"""
import sys
from pathlib import Path
import pandas as pd
import pytest
from scipy import stats
sys.path.insert(0, str(Path(__file__).parent.parent / "module-3"))
from test_data_preparation import prepare # noqa: E402
NUMERIC = ["age", "income", "creditScore"]
NOT_REPRESENTATIVE = pytest.mark.xfail(strict=True, reason="production differs from training: see the lesson")
@pytest.fixture(scope="module")
def training(api):
raw = pd.DataFrame(api.get(f"{api.base}/datasets/loans-train", timeout=10).json()["data"])
return prepare(raw)
@pytest.fixture(scope="module")
def production(api):
return pd.DataFrame(api.get(f"{api.base}/datasets/loans-production", timeout=10).json()["data"])
def test_describe_both(training, production):
"""Exploratory data analysis: put the two distributions side by side."""
table = pd.DataFrame({
f"{column} {name}": data[column].describe()[["min", "50%", "max"]]
for column in NUMERIC for name, data in [("train", training), ("prod", production)]
}).T.round(0)
print("\n" + table.to_string())
@NOT_REPRESENTATIVE
@pytest.mark.parametrize("column", NUMERIC)
def test_same_distribution(training, production, column):
"""Kolmogorov-Smirnov: could both samples come from the same distribution?"""
result = stats.ks_2samp(training[column], production[column])
print(f"\n {column}: KS statistic {result.statistic:.2f}, p = {result.pvalue:.1g}", end="")
assert result.pvalue >= 0.05
@NOT_REPRESENTATIVE
@pytest.mark.parametrize("column", NUMERIC)
def test_production_values_within_the_training_range(training, production, column):
low, high = training[column].min(), training[column].max()
outside = (~production[column].between(low, high)).mean()
print(f"\n {column}: {outside:.0%} of production outside the training range {low:.0f}-{high:.0f}", end="")
assert outside <= 0.05
@NOT_REPRESENTATIVE
def test_production_cities_were_seen_in_training(training, production):
known = {column.removeprefix("city_") for column in training.columns if column.startswith("city_")}
share_known = production["city"].isin(known).mean()
print(f"\n {share_known:.0%} of production applications come from a city in the training data", end="")
assert share_known >= 0.95
The tests state what should be true if the training data were representative, and are marked as expected failures, because the practice data is built to fail them. In a real project they would be plain tests that block training.
Run it
pytest module-6/test_representativeness.py -v -s
min 50% max
age train 20.0 46.0 69.0
age prod 45.0 62.0 75.0
income train 31584.0 74920.0 129352.0
income prod 60000.0 136500.0 199000.0
creditScore train 501.0 629.0 791.0
creditScore prod 601.0 704.0 815.0
PASSED
age: KS statistic 0.52, p = 1e-06 XFAIL
income: KS statistic 0.60, p = 7e-09 XFAIL
creditScore: KS statistic 0.42, p = 0.0002 XFAIL
age: 18% of production outside the training range 20-69 XFAIL
income: 60% of production outside the training range 31584-129352 XFAIL
creditScore: 16% of production outside the training range 501-791 XFAIL
22% of production applications come from a city in the training data XFAIL
Read the result
The training data does not represent production, on every feature:
- Production applicants are older. Median 62 versus 46; nobody under 45. 18% are older than anyone in the training data.
- They earn more. Median $136,500 versus $74,920, and 60% earn more than the richest applicant the model ever saw. For those, the model is extrapolating.
- They have better credit scores, and 16% are above the training maximum.
- 78% live in a city the model has never seen. Boston, Miami, Denver and Seattle do not exist in the training data (lesson 38 found the same with a constraint).
The KS statistics of 0.42 to 0.60 are large: the distributions barely overlap. The p-values say this is not chance.
What does it mean? Every metric from module 4 was measured on data like the training data. For the population in production, nobody knows how good the model is. Worse, the practice model has a penalty for ages over 55 (lesson 35), and 62% of production applicants are over 55. The mismatch and the bias reinforce each other.
What to do: collect labelled data from the production population and test the model on it; retrain with representative data; and until then, treat decisions for applicants outside the training range with suspicion (for example, route them to a person).
Exercise
- The city test compares only “seen or not seen”. Write a chi-squared test that compares the city proportions of training and production, for the cities they share. Use
scipy.stats.chi2_contingency. - The training data has 14 approvals and 36 rejections. Is that a representativeness problem? What would you compare it with?
Show suggested answer
Build a contingency table of counts per city and dataset, for the shared cities (only New York here, which shows how little overlap there is), or for “known city” versus “unknown city”:
from scipy.stats import chi2_contingency def test_city_proportions(training, production): known = {c.removeprefix("city_") for c in training.columns if c.startswith("city_")} table = [ [len(training), 0], # training: all in known cities [production["city"].isin(known).sum(), (~production["city"].isin(known)).sum()], ] chi2, p_value, _, _ = chi2_contingency(table) assert p_value < 0.05 # the proportions differWith more overlap between the cities you would put one column per city in the table.
It is class imbalance: 28% approvals. Whether it is a problem depends on the real approval rate in the target population. Compare it with the bank’s historic approval rate for the population the model will serve. If the real rate is about 28%, the data is representative and the imbalance is just reality (but use precision and recall, not accuracy, lesson 18). If the real rate is 50%, the data under-represents approvals.
Exam-style questions
1. Which statistical test is suitable for checking whether a numeric feature has the same distribution in the training data and in the operational data?
- A. Cohen’s kappa
- B. Kolmogorov-Smirnov
- C. F1-score
- D. Neuron coverage
Show answer
2. What is the first step in testing for data representativeness?
- A. Run a Kolmogorov-Smirnov test
- B. Define the target population: use cases, users, expected distributions and edge cases
- C. Retrain the model
- D. Remove outliers
Show answer
3. When should data representativeness be tested?
- A. Only after deployment
- B. Before training; after deployment it is continued as drift monitoring
- C. Only when the model fails in production
- D. Never for supervised learning
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-6/
├── test_dataset_constraints.py
├── test_bias.py
└── test_representativeness.py new in this lesson
The finished version is in the example repository: module-6/test_representativeness.py.