Sub topic 14
Detection: comparing distributions with PSI and the KS test
This chapter assumes you can read pandas and NumPy code, and that you know what a histogram and a quantile are. It also assumes your serving system already logs the features the model received, which the previous chapter covers. Here you turn those logs into a number that tells you whether a feature looks the same in production as it did in training.
What the comparison tells you
You have two samples of one feature. The reference sample is the training data, or a validation set drawn from the same pipeline. The comparison sample is a window of logged serving values. A distribution metric answers one question: how different are these two samples?
A large difference does not name the cause. It could be skew (the pipeline computes the feature differently), drift (the real world changed), or a plain traffic change such as a new market launch. The metric tells you where to look. The earlier chapter on skew versus drift covers how to tell the causes apart.
Compare per feature, not on the model's score alone. A score distribution can stay stable while two features move in opposite directions.
Population Stability Index (PSI)
PSI splits the range of a feature into bins. For each bin it compares the share of reference rows with the share of serving rows:
PSI = sum over bins of (ai − ei) × ln(ai / ei)
Here ei is the expected (training) share in bin i, and ai is the actual (serving) share. Each term is zero or positive, so PSI is zero only when every share matches. The value does not depend on the units of the feature.
The common rule of thumb is:
| PSI | Usual reading |
|---|---|
| below 0.1 | No meaningful change |
| 0.1 to 0.25 | Moderate change, investigate |
| above 0.25 | Large change, act |
These thresholds come from credit-scoring practice. Treat them as starting points and tune them on your own history of false alarms.
Choosing the bins
Take the bin edges from the reference sample only, and reuse the same edges for every serving window. If you recompute edges from each window, the bins move with the data and hide the shift you want to see.
Quantile bins from the training data give each bin about 10% of the reference rows. The outer edges are set to negative and positive infinity, so serving values outside the training range land in the first or last bin instead of disappearing.
import numpy as np
def psi(expected, actual, bins=10):
"""Population Stability Index of `actual` relative to `expected`."""
edges = np.unique(np.quantile(expected, np.linspace(0, 1, bins + 1)))
edges[0], edges[-1] = -np.inf, np.inf
e = np.histogram(expected, edges)[0] / len(expected)
a = np.histogram(actual, edges)[0] / len(actual)
e = np.clip(e, 1e-6, None)
a = np.clip(a, 1e-6, None)
return float(np.sum((a - e) * np.log(a / e)))
rng = np.random.default_rng(0)
train_values = rng.normal(40, 10, 5000)
mild_shift = rng.normal(42, 10, 5000) # real-world change, small
fill_bug = rng.normal(0, 1, 5000) # serving fills missing ages with 0
print("mild shift:", round(psi(train_values, mild_shift), 3))
print("fill bug: ", round(psi(train_values, fill_bug), 3))The mild shift gives a small PSI, well under 0.1. The fill-with-zero bug puts almost every serving row in the first bin, so PSI is far above 0.25.
The np.clip call matters. A bin with zero rows would make np.log(a / e) infinite or undefined. Clipping to a tiny positive share keeps the result finite and still large for an empty bin.
Categorical features
For a categorical feature, each category is a bin. Add a bucket for values never seen in training, and one for missing values, because a surge of unseen categories or nulls is often the first visible sign of a schema problem.
import numpy as np
import pandas as pd
def psi_categorical(expected: pd.Series, actual: pd.Series) -> float:
"""PSI over category shares, with explicit buckets for nulls and unseen values."""
known = set(expected.dropna().unique())
def shares(s: pd.Series) -> pd.Series:
labels = s.where(s.isin(known), "__unseen__").where(s.notna(), "__null__")
return labels.value_counts(normalize=True)
e, a = shares(expected), shares(actual)
idx = e.index.union(a.index)
e = e.reindex(idx, fill_value=0).clip(lower=1e-6)
a = a.reindex(idx, fill_value=0).clip(lower=1e-6)
return float(((a - e) * np.log(a / e)).sum())
train_country = pd.Series(["US"] * 60 + ["DE"] * 30 + ["FR"] * 10)
serve_country = pd.Series(["US"] * 40 + ["DE"] * 20 + ["FR"] * 5 + ["BR"] * 25 + [None] * 10)
print(round(psi_categorical(train_country, serve_country), 3))The two-sample Kolmogorov-Smirnov test
The Kolmogorov-Smirnov (KS) test works on numeric values without binning. It compares the two empirical cumulative distribution functions (the fraction of values at or below each x). The KS statistic is the largest vertical gap between them, from 0 (identical) to 1 (no overlap). The test also returns a p-value, the probability of a gap at least this large if both samples came from the same distribution.
import numpy as np
from scipy.stats import ks_2samp
rng = np.random.default_rng(0)
train_values = rng.normal(40, 10, 5000)
serving_values = rng.normal(42, 10, 5000)
result = ks_2samp(train_values, serving_values)
if result.pvalue < 0.01:
print(f"Possible skew: KS statistic={result.statistic:.3f}, p={result.pvalue:.2g}")With 5,000 rows on each side, even the mild shift of 2 units (0.2 standard deviations) gives a p-value far below 0.01. The statistic is only about 0.08, though.
Choosing between PSI and KS
The two metrics fail in different ways, so the choice depends on volume and on the feature type.
| Question | PSI | KS test |
|---|---|---|
| Feature types | Numeric (binned) and categorical | Numeric only |
| Output | One effect-size score | Statistic plus p-value |
| Sensitivity to sample size | Low, apart from noise in sparse bins | High: large samples flag trivial shifts |
| Where it is sensitive | Bins you chose, so tails need care | Middle of the distribution, where the CDFs differ most |
| Fixed thresholds | Conventional (0.1, 0.25) | Better to threshold on the statistic than on p |
Two practical consequences follow.
- Alert on effect size. With millions of logged rows, a p-value below 0.01 is almost guaranteed for some feature every day. Alert when the KS statistic exceeds a chosen value (for example 0.1), or use the p-value only as a second condition.
- Use both when you can. PSI covers categorical features and gives a comparable score across features. KS needs no bin decisions for numeric ones.
Neither metric sees every problem. A feature whose values are shuffled between rows, or whose relationship to another feature breaks, can keep an identical distribution. Single-feature checks also miss that. Parity tests on a sample of rows catch these cases.
Running the check
The check is a scheduled job that runs the same steps every time.
A few details decide whether the job is useful:
- Store the reference with the model version. Save the bin edges and reference shares next to the model artifact. If the model is retrained, the reference changes with it.
- Use fixed windows. Compare, for example, the last 24 hours against the reference, and keep each day's score. A trend is more informative than one value.
- Check null rates and category counts separately. A feature that becomes 30% null may still pass a numeric PSI if nulls are dropped before binning.
- Rank the alerts. Sort features by score, and weight by feature importance if you have it. A large shift on an unimportant feature matters less than a moderate shift on the top feature.
Common errors
- Recomputing bin edges per window. The bins follow the shift, so PSI stays near zero.
- Comparing against the wrong reference. Using the full historical table when the model was trained on a filtered subset produces a permanent false alarm.
- Ignoring seasonality. A weekday reference compared to weekend traffic shows a shift that is not a defect. Compare same-weekday windows if traffic is cyclical.
- Treating the score as a diagnosis. A high PSI says "different". Tracing it to duplicated code, a changed source, or real drift is the next step.
Exercise
A daily job compares 2 million logged serving rows with the training data using ks_2samp and alerts when p < 0.01. It fires every day for most numeric features, though model accuracy is stable. Why, and what two changes would you make?
Show answer
With millions of rows, the KS test detects tiny differences, so p-values are almost always small even when the shift is harmless. Alert on the effect size instead, using the KS statistic with a threshold chosen from your history (for example 0.1), or use PSI with the 0.1 and 0.25 levels. You can also compare a random sample or a shorter window, and rank features by score and importance so only the largest shifts page anyone.
Exercise
A categorical feature "country" has the same PSI of 0.02 on every day, but the serving log shows 15% of values are "null" after a schema change. Using the psi_categorical function above, what went wrong in your monitor, and how would you fix it?
Show answer
If nulls are dropped before the comparison (for example by calling dropna on both series), the null surge disappears from the shares and PSI stays low. Keep nulls as their own bucket, as psicategorical does with "null_", and also track the null rate per feature as a separate metric with its own alert.