Sub topic 6
Checking Distributions Against a Reference Dataset
Assume you know Python, pandas, pytest, and basic model evaluation. This chapter shows how to detect data drift: a change in the distribution of incoming data compared with a trusted reference dataset.
Why compare distributions?
A schema check can confirm that a column exists and has the expected type. It cannot tell you that customer ages have shifted from a typical range of 20–70 to mostly 80–90. The data may still pass validation while becoming unsuitable for the model.
Use a reference dataset that represents data used during training or a known-good production period. Compare new data with that reference on:
- Numeric distributions, such as age or income.
- Categorical proportions, such as country or device type.
- Missing-value rates.
- Important summary statistics.
A distribution check is an alert, not automatic proof that a model is broken. Seasonal changes can be valid. A large change in a low-value feature may not matter, while a small change in a critical feature may require investigation.
A simple comparison strategy
For numeric columns, divide both datasets into the same bins and compare the fraction of rows in each bin. Shared bins are important. If each dataset chooses its own bins, their results are difficult to compare.
For categorical columns, compare the proportion assigned to each category. Include categories that occur in either dataset so that newly appearing or disappearing values are visible.
| Check | Example signal | Possible response |
|---|---|---|
| Numeric bin proportions | Income moved toward higher values | Investigate population or product changes |
| Category proportions | A new device type appeared | Confirm support and retraining needs |
| Missing-value rate | A source field became mostly empty | Check the upstream data source |
| Reference coverage | New values fall outside old ranges | Review feature assumptions |
The following function reports the largest absolute difference between corresponding proportions.
import numpy as np
import pandas as pd
def numeric_distribution_change(
reference: pd.Series,
current: pd.Series,
bins: int = 10,
) -> float:
"""Return the largest bin-proportion difference."""
reference = reference.dropna().to_numpy()
current = current.dropna().to_numpy()
if len(reference) == 0 or len(current) == 0:
raise ValueError("both series need at least one non-null value")
edges = np.histogram_bin_edges(reference, bins=bins)
if edges[0] == edges[-1]:
return 0.0
reference_counts, _ = np.histogram(reference, bins=edges)
current_counts, _ = np.histogram(current, bins=edges)
reference_rates = reference_counts / len(reference)
current_rates = current_counts / len(current)
return float(np.abs(reference_rates - current_rates).max())
def categorical_distribution_change(
reference: pd.Series,
current: pd.Series,
) -> float:
"""Return the largest category-proportion difference."""
categories = reference.dropna().astype(str).unique()
categories = np.union1d(
categories,
current.dropna().astype(str).unique(),
)
if len(categories) == 0:
raise ValueError("both series need at least one non-null value")
reference_rates = (
reference.astype(str).value_counts(normalize=True)
.reindex(categories, fill_value=0)
)
current_rates = (
current.astype(str).value_counts(normalize=True)
.reindex(categories, fill_value=0)
)
return float(np.abs(reference_rates - current_rates).max())
reference = pd.Series([20, 22, 25, 30, 35, 40])
current = pd.Series([30, 35, 40, 45, 50, 55])
change = numeric_distribution_change(reference, current)
print(f"largest bin change: {change:.3f}")The returned value is between zero and one. Zero means that every compared bin or category has the same proportion. A value of 0.20 means that at least one proportion differs by 20 percentage points.
Choosing thresholds and handling failures
A CI check should compare a committed reference sample with a test fixture or a generated sample. It should fail when a meaningful change exceeds the agreed threshold, but it should not fail randomly because of sampling noise.
Use separate thresholds for different features. For example, a small change in a fraud-related feature may deserve attention, while a larger change in an optional marketing field may not. Record the reference dataset version and the check results as build artifacts so a failure can be investigated later.
Exercise
Why must numeric comparisons use the same bin edges for the reference and current datasets?
Show answer
Shared bin edges measure both datasets over the same value ranges. Separate edges can hide or exaggerate differences because the bins no longer represent the same parts of the distribution.