Sub topic 6
Checking Distributions Against a Reference Dataset
Prerequisites and scope
This chapter assumes you can write pytest tests and use pandas and NumPy. It also assumes you have read the earlier chapter on schema, range, and missing-value validation. Familiarity with scipy.stats helps but is not required.
Validation asks whether each value is legal. A distribution check asks whether the data as a whole still looks like the data the model was built on. This chapter covers how to run that check as an automated test, which statistics to use, and why drift checks need more care than ordinary assertions.
Why valid data can still be wrong
A column can pass every schema and range check and still be broken. Suppose income is stored as a float and stays in an allowed range. An upstream change then switches the unit from dollars to thousands of dollars. Every value is still valid, but the model sees numbers about 1000 times smaller than anything it trained on.
Other changes that slip past validation:
- A sensor is recalibrated and shifts a feature by a constant.
- A join starts dropping one customer segment, so the mix of rows changes.
- A default value silently replaces nulls, so a spike appears at one number.
- A new data source covers a different population.
A distribution check compares a current dataset (the new training data, or a fresh sample) with a reference dataset. Drift here means the two datasets are unlikely to come from the same distribution, or differ by more than you accept.
Choosing and storing a reference
The reference is the dataset the current production model was trained on, or a representative sample of it. Treat it as a versioned artifact.
- Commit a small sample (a few thousand rows) if it is not sensitive. It is simple and reviewable.
- Commit summary statistics (quantile edges and category frequencies per column) if the raw rows are sensitive or too large. The PSI function below only needs bin edges and fractions.
- Pull a pinned version from data versioning (covered in a later chapter) for the heavy scheduled checks.
Update the reference deliberately, in a pull request, when you retrain on new data. If the reference updates itself on every run, the check compares the data with itself and can never fail.
Two statistics for numeric columns
Two-sample Kolmogorov-Smirnov test
The two-sample KS test measures the largest gap between the empirical cumulative distribution functions of two samples. It returns a statistic between 0 and 1 and a p-value. It makes no assumption about the shape of the distribution, and scipy implements it.
Population Stability Index
The Population Stability Index (PSI) bins the reference by its own quantiles, then compares the share of rows that fall in each bin. For bin fractions r_i (reference) and c_i (current), PSI is the sum of (c_i - r_i) * ln(c_i / r_i). A common rule of thumb reads below 0.1 as stable, 0.1 to 0.25 as a moderate shift, and above 0.25 as a major shift. These cutoffs are conventions from credit scoring, not laws. Check them against your own data.
The following code implements both statistics and combines them in one function that returns a list of problems, matching the style of validate_training_data.
import numpy as np
import pandas as pd
from scipy import stats
def population_stability_index(reference, current, bins: int = 10,
eps: float = 1e-4) -> float:
ref = np.asarray(reference, dtype=float)
cur = np.asarray(current, dtype=float)
ref = ref[~np.isnan(ref)]
cur = cur[~np.isnan(cur)]
edges = np.unique(np.quantile(ref, np.linspace(0, 1, bins + 1)))
if len(edges) < 2:
raise ValueError("reference column is constant; PSI is undefined")
edges[0], edges[-1] = -np.inf, np.inf
ref_frac = np.histogram(ref, bins=edges)[0] / len(ref)
cur_frac = np.histogram(cur, bins=edges)[0] / len(cur)
ref_frac = np.clip(ref_frac, eps, None)
cur_frac = np.clip(cur_frac, eps, None)
return float(np.sum((cur_frac - ref_frac) * np.log(cur_frac / ref_frac)))
def check_drift(reference: pd.DataFrame, current: pd.DataFrame,
columns: list[str], alpha: float = 0.001,
min_ks: float = 0.1, max_psi: float = 0.25) -> list[str]:
problems = []
for col in columns:
if col not in reference.columns or col not in current.columns:
problems.append(f"{col}: missing from reference or current data")
continue
ref = reference[col].dropna()
cur = current[col].dropna()
if len(ref) == 0 or len(cur) == 0:
problems.append(f"{col}: no non-missing values to compare")
continue
ks = stats.ks_2samp(ref, cur)
if ks.pvalue < alpha and ks.statistic > min_ks:
problems.append(
f"{col}: KS statistic {ks.statistic:.3f} "
f"(p={ks.pvalue:.2g}) exceeds {min_ks}"
)
psi = population_stability_index(ref, cur)
if psi > max_psi:
problems.append(f"{col}: PSI {psi:.3f} exceeds {max_psi}")
return problemsThe KS check flags a column only when both conditions hold: the p-value is small and the statistic is large. The next section explains why.
Statistical significance is not the same as importance
A p-value answers "could this gap be chance?" With 5 million rows, even a tiny and harmless difference is very unlikely to be chance. A p-value-only test then fails on every run. With 50 rows, a large and harmful shift can still give a p-value above your threshold.
For this reason check_drift pairs the p-value with an effect size: the KS statistic itself. The p-value says the difference is real, and the statistic says whether it is big enough to care about. Choose min_ks by looking at how much the statistic varies between past training sets that you knew were fine.
Keep two more points in mind:
- Multiple comparisons. If you test 40 columns at
alpha = 0.05, you expect about two false alarms on identical data. Use a small alpha such as 0.001, and use the effect-size condition as a second filter. - Missing values. Compare the missing-value rate with the validation check from the previous chapter. The code above drops nulls before testing, so a column that goes from 1% null to 30% null passes the distribution check unless validation catches it.
Categorical columns
KS and PSI as written need numeric input. For a categorical column, compare category frequencies instead:
- Compute the share of each category in the reference and in the current data.
- Flag any category whose share changed by more than a set amount, such as 0.10 in absolute terms.
- Flag any category that appears in the current data but never in the reference. A model trained without that category has no basis for handling it.
A chi-square test works too, but it has the same sample-size problem as the KS p-value, so keep an effect-size condition.
Testing the drift check itself
A drift check that never fires is worse than none, because it gives false confidence. Test it with synthetic data whose answer you know. Seed the random generator so the test is deterministic. This follows the reproducibility rules from earlier in this tutorial.
import numpy as np
import pandas as pd
def make_frame(mean: float, seed: int, n: int = 5000) -> pd.DataFrame:
rng = np.random.default_rng(seed)
return pd.DataFrame({"income": rng.normal(mean, 1.0, size=n)})
def test_no_drift_on_same_distribution():
ref = make_frame(0.0, seed=1)
cur = make_frame(0.0, seed=2)
assert check_drift(ref, cur, ["income"]) == []
def test_drift_detected_on_mean_shift():
ref = make_frame(0.0, seed=1)
cur = make_frame(1.0, seed=2)
problems = check_drift(ref, cur, ["income"])
assert any("PSI" in p for p in problems)
assert any("KS" in p for p in problems)
def test_unit_change_is_detected():
ref = make_frame(50.0, seed=1)
cur = ref * 1000
assert check_drift(ref, cur, ["income"]) != []Put population_stability_index and check_drift in the module under test, and import them in the test file. The tests then belong with the data tests in tests/data.
Where drift checks run in CI
The flow below shows how the pieces connect.
Where the check runs depends on what "current" means:
| Situation | Current data | Where to run |
|---|---|---|
| Pull request changes a data-prep step | Small committed sample passed through the new code | Every pull request, with the fast data tests |
| New training snapshot arrives | The full new snapshot | On demand, or in the retraining pipeline |
| Production data may have changed | A recent sample of production inputs | Scheduled job, such as nightly |
On a pull request, the drift check on a small committed sample mostly catches code changes that alter feature values, such as a unit conversion or a changed fill value. It cannot tell you about real-world drift, because the sample is frozen. Real-world drift needs the scheduled job and fresh data.
Common errors
| Error | Consequence | Fix |
|---|---|---|
| Reference updates automatically on every run | The check can never fail | Change the reference only in a reviewed pull request |
| Alerting on p-value alone | Constant failures on large data | Add an effect-size condition |
| Testing many columns at a loose alpha | Random false alarms | Use a small alpha and an effect-size filter |
| Unseeded synthetic data in tests | Flaky tests | Use `np.random.default_rng(seed)` |
| Sample too small | Real drift goes unnoticed | Use at least a few hundred rows per column |
| Dropping nulls without a separate null-rate check | Missing-value drift is invisible | Keep the missing-fraction check in validation |
| Treating PSI cutoffs as universal | Wrong sensitivity | Calibrate on your own past data |
Exercises
Exercise
A team runs ks_2samp on a column with 4 million rows and fails the build whenever the p-value is below 0.05. The build now fails on almost every run, even though plots of the two samples look identical. What is wrong, and what is a better rule?
Show answer
With millions of rows, the test detects differences that are real but negligibly small, so the p-value is almost always below 0.05. A better rule requires both a small p-value (with a stricter alpha such as 0.001) and an effect-size condition, such as a KS statistic above a threshold calibrated on past good datasets, as in check_drift.
Exercise
Why does population_stability_index build its bin edges from the reference data only, and why does it clip the fractions to a small positive number?
Show answer
Bin edges from the reference give a fixed yardstick, so the current data is measured against the training distribution rather than against its own shape. The outer edges are set to minus and plus infinity, so current values outside the reference range still land in a bin. Clipping avoids dividing by zero and taking the log of zero when a bin is empty in one of the datasets.
Exercise
Write the test condition for a categorical column plan that fails when a category appears in the current data that does not exist in the reference. Describe it in one or two sentences, or write a short pandas expression.
Show answer
Compute the set difference of the categories: set(current["plan"].dropna().unique()) - set(reference["plan"].dropna().unique()). If the result is not empty, the test fails and reports the unseen categories, because the model was never trained on them.