Data Drift: PSI, KS and Friends
A model is trained on a snapshot of the world, and the world keeps moving. Months after release the inputs that arrive at the service look different: a marketing campaign brings younger customers, a partner bank changes how it reports income, a sensor is replaced. Labels for those inputs may take weeks to arrive, so you cannot wait for the accuracy to drop. What you can do on day one is compare today's inputs with the inputs the model was trained on. That comparison is data drift monitoring, and this lesson builds its three workhorses, the population stability index (PSI), the Kolmogorov-Smirnov (KS) test and the chi-square test, and shows where each one misleads.
Distribution shift explained what shift does to a model's evaluation and how to correct for it offline. Here the question is operational: a statistic per feature, per day, and a rule that decides when to wake someone up.
What can change
Write the joint distribution of inputs and labels as , or the other way round as .
- Covariate shift: changes, stays. The rule is the same, the inputs move. This is what input monitors see.
- Prior (label) shift: changes, stays: more defaults in a recession, but a defaulter still looks like a defaulter. It also moves , so input monitors see it indirectly.
- Concept drift: changes. Inputs can stay exactly the same, so input monitors are blind to it. That is the next lesson.
A drift alarm on an input says "the data is not what the model was trained on". It does not say the model is wrong: covariate shift into a region where the model is accurate costs nothing, and the lab below shows a case where it even lowers the error. Treat input drift as a reason to look, not as proof of damage.
PSI: binned, with a rule of thumb
Split the reference data (usually the training set, or a stable recent month) into bins. Let be the share of reference values in bin and the share of live values. The population stability index is
Each term is non-negative, because and always have the same sign, and PSI is 0 only when every share matches. It is the symmetrised KL divergence of the two binned distributions, . Three choices define it in practice:
- Bins at the reference quantiles. With edges at the reference deciles, every , so no bin is nearly empty on the reference side and the tails get as much attention as the middle. Equal-width bins put most of the reference into two or three bins and waste the rest.
- An epsilon for empty bins. If a live bin is empty, is . Implementations replace a zero share by a small (here ). The PSI then depends on that arbitrary , which matters with small windows, as the code below shows.
- Thresholds. The industry rule of thumb, from credit scoring, reads PSI below 0.1 as stable, 0.1 to 0.25 as a moderate shift worth a look, above 0.25 as a major shift. These are conventions, not laws: PSI has no built-in notion of sampling noise, so the same true distribution gives larger PSI values on smaller windows.
KS: the largest gap between two CDFs
The two-sample Kolmogorov-Smirnov statistic compares the empirical cumulative distribution functions of reference (size ) and live window (size ):
It needs no bins and is sensitive to a change anywhere: location, spread or shape. Under the null hypothesis that both samples come from the same continuous distribution, has a known distribution, and for large samples the 5 % test rejects when
So KS comes with a p-value, which PSI does not. That is its strength and, as we will see, its weakness.
Categorical features: chi-square, and two distances
A category (channel, country, device) has no order, so there is no CDF. Count each category in the reference and the live window, put the counts in a table, and run the chi-square test of independence: if both rows come from the same distribution, the statistic follows a chi-square distribution with degrees of freedom. PSI works on categories too, with one bin per category.
Two distances are also common in drift tools. The Jensen-Shannon distance is the square root of a symmetrised, smoothed KL divergence; with base-2 logarithms it lies between 0 and 1 and never hits . The Wasserstein-1 distance (earth mover's distance) for one numeric feature is the area between the two CDFs, , measured in the units of the feature: "the live incomes moved by about 3,000 on average" is easier to act on than a p-value.
The lab: a monitor over 60 days
The lab watches one feature for 60 days. The reference is 1,000 training values from ; each day new values arrive, drawn from where follows the chosen drift pattern. The bottom plot is the statistic per day, with the threshold as a horizontal line; red dots are false alarms (before the drift starts, or with no drift at all), orange dots are alarms after the onset. PSI uses 10 bins at the reference deciles, drawn as thin lines on the histogram.
Start with a sudden shift of half a standard deviation on day 31, PSI, threshold 0.2:
Before the change PSI hovers well below the threshold (0.064 on day 30). On day 31 it jumps to 0.334, so the first alarm is on day 31: a detection delay of 0 days and no false alarms. The status box shows "Days in alarm" as 28, not 30: on two days after the shift, sampling noise pulled the PSI back under 0.2 (day 45 reads 0.169). A real alert rule therefore usually asks for the condition to hold on several consecutive days, or uses a smoothed statistic, so that it does not flap. Switch the statistic to KS D: on day 31, , against a 5 % critical value of 0.105 for against , shown in the status box. Then try a smaller shift: at PSI only crosses 0.2 once, on day 55.
Now take the drift away and shrink the window. With no drift every alarm is false, and the only thing that changes PSI is sampling noise:
With 50 values per day, 33 of the 60 days raise a (false) alarm, and on day 60 the PSI is 0.960, far above any "major shift" level, from data drawn from the reference distribution itself. Five values per expected bin are too few: a bin that happens to get none is counted as , and its term alone adds about 0.69. Move up: 100 values per day give 3 false-alarm days, 200 give none. A PSI threshold is only meaningful together with the window size it was set for. Raising the threshold to 0.25 at still leaves 24 false-alarm days.
Finally, a pattern that is not a fault at all:
Here , a 20-day cycle like a monthly pay day or a weekly rhythm stretched out. PSI against a fixed reference is in alarm on 25 of the 60 days, and the readout calls them "n/a (recurring)": they are neither true nor false in the usual sense. The reference was simply not representative of a whole cycle. The fixes are a reference that covers full cycles (a year of training data for yearly seasons), or a seasonal reference (compare this Monday with past Mondays), not a tighter threshold.
From scratch: PSI and KS in NumPy
Both statistics in a few lines. The reference is 5,000 values from , each live window 1,000 values; the code also shows the empty-bin effect with a window that lands far from the reference.
import numpy as np
rng = np.random.default_rng(0)
ref = rng.normal(0, 1, 5000)
def psi(ref, live, bins=10, eps=1e-4):
"""PSI with bins at the reference quantiles; empty shares become eps."""
edges = np.quantile(ref, np.linspace(0, 1, bins + 1)[1:-1]) # 9 inner edges
e = np.bincount(np.searchsorted(edges, ref, side="right"), minlength=bins) / len(ref)
a = np.bincount(np.searchsorted(edges, live, side="right"), minlength=bins) / len(live)
e, a = np.maximum(e, eps), np.maximum(a, eps)
return float(np.sum((a - e) * np.log(a / e)))
def ks_d(ref, live):
"""Two-sample KS statistic: largest gap between the empirical CDFs."""
grid = np.concatenate([ref, live])
F_ref = np.searchsorted(np.sort(ref), grid, side="right") / len(ref)
F_live = np.searchsorted(np.sort(live), grid, side="right") / len(live)
return float(np.max(np.abs(F_ref - F_live)))
n = 1000
crit = 1.358 * np.sqrt((len(ref) + n) / (len(ref) * n))
print(f"KS 5% critical D, n={n} vs m={len(ref)}: {crit:.3f}")
for shift in (0.0, 0.1, 0.25, 0.5, 1.0):
live = rng.normal(shift, 1, n)
print(f"mean shift {shift:4.2f}: PSI {psi(ref, live):.3f} KS D {ks_d(ref, live):.3f}")
live = rng.normal(0, 1.5, n)
print(f"sd 1.0 -> 1.5 : PSI {psi(ref, live):.3f} KS D {ks_d(ref, live):.3f}")
far = rng.normal(3, 1, 200) # most reference bins get no live value at all
for eps in (1e-2, 1e-4, 1e-6):
print(f"window at mean 3, eps={eps:g}: PSI {psi(ref, far, eps=eps):.2f}")KS 5% critical D, n=1000 vs m=5000: 0.047
mean shift 0.00: PSI 0.010 KS D 0.031
mean shift 0.10: PSI 0.019 KS D 0.070
mean shift 0.25: PSI 0.072 KS D 0.113
mean shift 0.50: PSI 0.331 KS D 0.231
mean shift 1.00: PSI 0.984 KS D 0.401
sd 1.0 -> 1.5 : PSI 0.229 KS D 0.117
window at mean 3, eps=0.01: PSI 3.78
window at mean 3, eps=0.0001: PSI 7.24
window at mean 3, eps=1e-06: PSI 10.46
Read the rows against the rules of thumb. With no shift PSI is 0.010, the sampling noise floor for 1,000 values. A shift of 0.25 SD gives PSI 0.072, still "stable" by the 0.1 rule, while KS already rejects at 5 % ( against a critical value of 0.047): the two statistics answer different questions, "how big is the change?" and "is there any change?". Half a standard deviation gives 0.331, a "major shift". A change in spread with the mean unchanged (standard deviation 1.0 to 1.5) is caught by both, PSI 0.229 and , because values move into the outer deciles. The last three lines are the warning about : the same window, far from the reference, scores 3.78, 7.24 or 10.46 depending only on the value chosen for empty bins. Beyond about 1, a PSI value tells you "completely different", and its exact size means nothing.
With SciPy: tests, categories and distances
scipy.stats.ks_2samp gives and a p-value, chi2_contingency tests a table of category counts, and jensenshannon and wasserstein_distance give the two distances. The categorical feature is a sales channel whose mix changes.
import numpy as np
from scipy import stats
from scipy.spatial.distance import jensenshannon
rng = np.random.default_rng(1)
ref = rng.normal(0, 1, 5000)
live = rng.normal(0.25, 1, 1000)
r = stats.ks_2samp(ref, live)
print(f"ks_2samp: D = {r.statistic:.3f}, p = {r.pvalue:.1e}")
print(f"Wasserstein-1 = {stats.wasserstein_distance(ref, live):.3f} (feature units)")
channels = ["web", "app", "branch"]
ref_c = rng.choice(channels, 5000, p=[0.50, 0.40, 0.10])
live_c = rng.choice(channels, 1000, p=[0.45, 0.50, 0.05])
table = np.array([[np.sum(ref_c == ch) for ch in channels],
[np.sum(live_c == ch) for ch in channels]])
chi2, p, dof, expected = stats.chi2_contingency(table)
print("counts (rows: reference, live):", table.tolist())
print(f"chi-square = {chi2:.1f}, dof = {dof}, p = {p:.1e}")
shares = table / table.sum(axis=1, keepdims=True)
psi_cat = float(np.sum((shares[1] - shares[0]) * np.log(shares[1] / shares[0])))
print(f"PSI over the 3 categories = {psi_cat:.3f}")
print(f"Jensen-Shannon distance (base 2) = {jensenshannon(shares[0], shares[1], base=2):.3f}")ks_2samp: D = 0.139, p = 1.9e-14
Wasserstein-1 = 0.290 (feature units)
counts (rows: reference, live): [[2480, 1993, 527], [449, 506, 45]]
chi-square = 58.7, dof = 2, p = 1.8e-13
PSI over the 3 categories = 0.082
Jensen-Shannon distance (base 2) = 0.120
The numeric feature moved by 0.25 SD, and the Wasserstein distance reads 0.290 in the feature's own units, close to that shift, which is why it is a useful number to put in an alert message. For the channel mix, the chi-square test is overwhelmingly significant ( around ) while PSI over the three categories is 0.082, below the 0.1 "stable" line, and the Jensen-Shannon distance is 0.120. Is a drop of branch customers from 10.5 % (527 of 5,000) to 4.5 % (45 of 1,000) a problem? The test cannot say; only the business context (is the model worse on app users?) can.
Pitfall: big samples make everything significant
A p-value answers "could this difference be sampling noise?", and with enough data the answer is always no, even for differences nobody cares about. The same tiny shift of 0.03 standard deviations, tested with growing samples, and then a second classic trap: running many tests every day.
import numpy as np
from scipy import stats
rng = np.random.default_rng(2)
print("mean shift 0.03 SD, equal sample sizes:")
for n in (500, 5000, 50000):
r = stats.ks_2samp(rng.normal(0, 1, n), rng.normal(0.03, 1, n))
print(f" n = {n:6d}: D = {r.statistic:.3f}, p = {r.pvalue:.1e}")
features, days, n_ref, n_live = 8, 30, 1000, 200
p_values = np.array([[stats.ks_2samp(rng.normal(size=n_ref), rng.normal(size=n_live)).pvalue
for f in range(features)] for d in range(days)])
tests = features * days
print(f"no drift at all, {features} features x {days} days = {tests} tests")
print(f" p < 0.05: {int((p_values < 0.05).sum())} alarms (expected about {0.05 * tests:.0f})")
print(f" days with at least one alarm: {int((p_values < 0.05).any(axis=1).sum())} of {days}")
print(f" Bonferroni, p < 0.05/{features}: {int((p_values < 0.05 / features).sum())} alarms")mean shift 0.03 SD, equal sample sizes:
n = 500: D = 0.078, p = 9.5e-02
n = 5000: D = 0.020, p = 2.6e-01
n = 50000: D = 0.018, p = 4.1e-07
no drift at all, 8 features x 30 days = 240 tests
p < 0.05: 13 alarms (expected about 12)
days with at least one alarm: 12 of 30
Bonferroni, p < 0.05/8: 3 alarms
With 500 values per side the 0.03 SD shift is invisible (); with 50,000 the same shift gives , although itself fell from 0.078 to 0.018, closer to the true, tiny gap. Nothing about the shift changed, only . In the second half nothing drifted at all, yet 13 of 240 tests came out "significant", close to the 12 that a 5 % level promises, and 12 of the 30 days had at least one alarm. Dividing the level by the number of features (Bonferroni) left 3.
The practical consequences:
- Use an effect size for the decision. Alarm on "PSI above 0.2" or "Wasserstein above 5 % of the feature's range", which do not grow with , and use p-values, if at all, only to rule out noise on small windows.
- Correct for many tests. With dozens of features checked daily, plain guarantees a stream of false alarms. Bonferroni ( for tests) is simple and conservative; controlling the false discovery rate (Benjamini-Hochberg) is less strict. Better still, monitor a few features that matter (the most important ones by error analysis or feature importance) and the model's score distribution, and keep the rest on a weekly report.
- Choose the window on purpose. A short window (an hour) reacts fast but is noisy and sees daily rhythms as drift; a long window (a month) is stable but slow and averages a sudden break with weeks of normal data. Many teams run two: a daily window for alerts and a weekly one for trends. The reference matters as much as the window: training data, a fixed "golden" month, or a sliding previous period (which detects change but slowly absorbs gradual drift into the reference).
Other pitfalls
- Univariate monitors miss joint changes. Two features can keep their marginals while their correlation flips. A domain classifier (train a model to tell reference from live rows; AUC near 0.5 means no detectable shift) catches multivariate shift; the distribution shift lesson builds one.
- Pipeline bugs look like drift. A unit change (cents instead of euros), a default value filling a broken column, a renamed category: most "drift" alarms in practice are data quality problems. Check missing rates and value ranges first (data validation).
- Drift is not damage. Prioritise alarms on features the model relies on, and confirm with the score distribution and, when labels arrive, the error.
Practice
- In the first lab, set the drift size to 0.3 and find the smallest threshold that gives no false alarms with . What are the detection delay and the number of days in alarm at that threshold?
- Why does putting PSI bins at the reference deciles make the expected shares all 0.1, and why does that help?
- A team alarms on
ks_2samp(...).pvalue < 0.01for 40 features, with a reference of 1 million rows and hourly windows of 20,000 rows. Predict what happens, and propose a better rule.
Answers
- With seed 1, threshold 0.16 still has one false alarm (day 9, before the onset); 0.17 is the smallest value with none. Its first alarm is on day 31, a delay of 0 days, but only 12 of the 60 days are in alarm: a shift of 0.3 SD sits close to PSI's noise floor at , so many post-onset days fall back below the line. At 0.2 the first alarm only comes on day 40 (delay 9).
- Each decile holds exactly a tenth of the reference, so for every bin. No bin is nearly empty on the reference side, where a tiny would make explode, and every part of the distribution, tails included, carries the same weight.
- With such large samples, almost every hour shows a "significant" difference on some feature, as in the third example where gave a 0.03 SD shift , and 40 tests per hour multiply the false alarms. Use an effect size (PSI or Wasserstein) with a threshold chosen on historical stable periods, apply it to a daily window, require the condition on several consecutive windows, and limit paging to the important features.
Test yourself
Why does PSI need an epsilon?
- To make it symmetric
- Because an empty live or reference bin would give
- To convert it to a p-value
- Because the bins are at deciles
In the lab with no drift and values per day, PSI with threshold 0.2 raised 33 false-alarm days. What is the best fix?
- Lower the threshold
- Use larger windows (or recalibrate the threshold for the window size)
- Use equal-width bins
- Add more features
With 50,000 values per side, ks_2samp reports a tiny p-value for a mean shift of 0.03 SD. What should the monitor conclude?
- The model is broken
- The shift is real but may be far too small to matter; decide with an effect size
- KS is the wrong test for numeric data
- The reference is corrupted
Which change can an input-drift monitor not see at all?
- Covariate shift
- Prior shift
- Concept drift with unchanged inputs
- A unit change in one column