Sub topic 7
Detecting drift with PSI and the KS test
This chapter assumes you know NumPy basics, what a histogram and a cumulative distribution are, and the data drift idea from earlier chapters: the inputs a model sees in production no longer look like its training data. Here you will turn that idea into two numbers you can compute, and then into a signal your trigger policy can use.
What the two statistics measure
Both statistics compare two samples of one feature:
- The reference sample is what the model was trained on, or a validated recent window.
- The current sample is a recent window of production data.
The Population Stability Index (PSI) splits the feature into bins, then measures how much the share of rows in each bin changed. The two-sample Kolmogorov-Smirnov (KS) test compares the two empirical cumulative distribution functions (CDFs). Its statistic is the largest vertical gap between them, and it comes with a p-value.
| Property | PSI | KS test |
|---|---|---|
| Output | One non-negative score | A statistic from 0 to 1 and a p-value |
| Needs binning | Yes | No |
| Feature types | Numeric and categorical | Numeric (ordered) only |
| Sensitivity to sample size | Low, apart from noisy sparse bins | High, because tiny shifts become "significant" |
| Typical use | Threshold on the score | Threshold on the statistic, or on the p-value |
Computing PSI
For each bin i, with reference share ri and current share ci:
PSI = sum over bins of (ci − ri) × ln(ci / ri)
Each term is zero or positive, so the total is zero for identical distributions and grows as they diverge. 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. The trigger policy later in this tutorial uses 0.2 as its example threshold. Tune the value on your own history.
Three implementation choices matter:
- Bin edges come from the reference only. Quantile bins of the reference give each bin about the same reference share, so no bin is nearly empty by construction.
- The outer edges are infinite. Production values outside the reference range still land in the first or last bin instead of disappearing.
- Shares are clipped to a small floor. An empty bin would make the logarithm undefined, so a floor of 1e-6 keeps the sum finite.
Computing both statistics
import numpy as np
from scipy.stats import ks_2samp
def psi(reference, current, bins=10):
"""Population Stability Index of one numeric feature."""
reference = np.asarray(reference, dtype=float)
current = np.asarray(current, dtype=float)
edges = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1)))
edges[0], edges[-1] = -np.inf, np.inf
ref_pct = np.histogram(reference, bins=edges)[0] / len(reference)
cur_pct = np.histogram(current, bins=edges)[0] / len(current)
ref_pct = np.clip(ref_pct, 1e-6, None)
cur_pct = np.clip(cur_pct, 1e-6, None)
return float(np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)))
rng = np.random.default_rng(0)
reference = rng.normal(0.0, 1.0, 10_000)
current = rng.normal(0.5, 1.0, 10_000)
print("PSI:", round(psi(reference, current), 3))
result = ks_2samp(reference, current)
print("KS statistic:", round(result.statistic, 3), "p-value:", result.pvalue)The current sample has its mean shifted by half a standard deviation. Expect a PSI of roughly 0.25, which is at the boundary of a major shift. Expect a KS statistic of roughly 0.2 and a p-value that is effectively zero.
np.unique on the quantile edges handles features with many repeated values. If a feature is mostly one constant, several quantiles coincide and the function uses fewer bins instead of producing empty ones.
Reading the KS result correctly
The KS statistic is the effect size: how far apart the distributions are. The p-value only answers whether a gap this large could come from two samples of the same distribution. With 10,000 rows per window, even a trivial shift gives p < 0.001, and the test fires on changes that do not hurt the model.
For triggers, use the statistic as the primary signal and the p-value as a confirmation. A rule such as "KS statistic ≥ 0.1 and p < 0.01" is more stable than a p-value alone.
From single features to a trigger signal
A model has many features, and checking each one at a 1% significance level means false alarms add up. With 100 features, you expect about one false alarm per check even when nothing changed. Two common fixes are a Bonferroni correction (divide alpha by the number of features) and reducing the report to one number, such as the maximum PSI. The should_retrain function in the trigger policy chapter takes that maximum as max_feature_psi.
Add this below the previous listing:
def drift_report(reference, current, psi_threshold=0.2, alpha=0.01):
"""reference, current: dicts mapping feature name to a 1-D array."""
corrected_alpha = alpha / len(reference)
report = {}
for name in reference:
score = psi(reference[name], current[name])
ks = ks_2samp(reference[name], current[name])
report[name] = {
"psi": round(score, 3),
"ks": round(float(ks.statistic), 3),
"drifted": score >= psi_threshold and ks.pvalue < corrected_alpha,
}
return report
rng = np.random.default_rng(1)
ref = {"age": rng.normal(40, 10, 8_000), "income": rng.lognormal(10, 0.5, 8_000)}
cur = {"age": rng.normal(46, 10, 8_000), "income": rng.lognormal(10, 0.5, 8_000)}
report = drift_report(ref, cur)
print(report)
print("max PSI:", max(r["psi"] for r in report.values()))Here age shifts by 0.6 standard deviations and income does not, so only age should be flagged. Requiring both PSI and the corrected KS test to agree makes the flag harder to trip by chance.
Common errors
- Re-binning on the current data. If edges come from the current window, the current shares are always roughly uniform and PSI hides the shift. Compute edges from the reference once and store them with the model version.
- A stale reference. If the reference is last year's data, seasonal change reads as drift every month. Choose a reference that matches the model's training window, and compare windows of the same length and weekday mix.
- Windows that are too small. With a few hundred rows, PSI is noisy because each bin holds only about 20 rows. Check that the window has enough rows per bin before computing.
- KS on categorical or encoded features. KS assumes an ordering. For categories, run PSI on category frequencies, or use a chi-squared test.
- Missing values.
np.quantilereturns NaN if the data contains NaN. Track the missing rate as a separate feature and drop NaNs before computing PSI. - Drift without harm. A feature can drift without hurting accuracy, and the model can degrade with no input drift at all (concept drift). Treat these statistics as an early warning that supports performance triggers. Do not use them as a replacement.
Exercise
A feature has 2,000 reference rows and 2,000 current rows. The KS test gives p = 0.03 and PSI is 0.04. Your threshold is PSI ≥ 0.2 and corrected p < 0.01 across 20 features. Is the feature flagged? What happens to the p-value if the same shift is measured on 200,000 rows per window, and what should you rely on?
Show answer
It is not flagged. PSI 0.04 is below 0.2, and 0.03 is above the corrected alpha of 0.01 / 20 = 0.0005. With 200,000 rows per window, the same small shift would give a much smaller p-value and pass the significance check, because the p-value shrinks as sample size grows. The PSI (the effect size) stays about the same, so the PSI threshold is the signal to rely on. This is why a trigger needs an effect-size threshold as well as the p-value.