Sub topic 7
Testing one feature at a time: KS and chi-square
This chapter assumes you know basic Python and NumPy, can read a p-value, and have already chosen a reference window and a current window (covered in the previous chapter). Here you compare one feature at a time between those two windows. You use the two-sample Kolmogorov-Smirnov (KS) test for numeric features and the chi-square test for categorical features.
The question a univariate test answers
A univariate drift test asks one question about one column: could the reference values and the current values plausibly come from the same distribution? The null hypothesis is that they do. A small p-value means the data is hard to explain under that hypothesis, so you flag the feature as drifted.
You run the test once per feature and collect the results in a table. That table tells you which features moved. It does not tell you whether the model got worse. That is a separate question, covered later in the tutorial.
The two-sample KS test for numeric features
The KS test compares the empirical cumulative distribution functions (ECDFs) of the two samples. An ECDF at value x is the fraction of observations at or below x. The KS statistic is the largest vertical gap between the two ECDFs. It ranges from 0 (identical ECDFs) to 1 (no overlap at all).
Properties that matter in practice:
- It makes no assumption about the shape of the distribution, so it works on skewed features such as order amounts.
- It is sensitive to shifts in location and spread, and less sensitive to differences deep in the tails, because the ECDF gap there is small.
- It assumes continuous data. On features with many ties, such as integer counts or values rounded to the nearest 10, the p-value is only approximate. For discrete numeric features with few distinct values, treat them as categorical.
- The statistic is a distance you can interpret directly: 0.12 means the ECDFs differ by up to 12 percentage points.
import numpy as np
from scipy.stats import ks_2samp
rng = np.random.default_rng(0)
reference = rng.normal(loc=0.0, scale=1.0, size=5000)
current = rng.normal(loc=0.3, scale=1.0, size=5000)
result = ks_2samp(reference, current)
print(f"KS statistic={result.statistic:.3f}, p-value={result.pvalue:.2e}")A 0.3 standard deviation shift with 5,000 rows per window gives a statistic of roughly 0.12 and a p-value far below 0.001. Both windows are large, so even a modest shift is easy to detect.
The chi-square test for categorical features
For a categorical feature, count how many rows fall into each category in each window. Stack the counts into a 2 x k table (two windows, k categories). The chi-square test of independence compares the observed counts with the counts you would expect if the category mix did not depend on the window.
import numpy as np
from scipy.stats import chi2_contingency
# Category counts for one categorical feature (rows: reference, current)
reference_counts = np.array([500, 300, 200])
current_counts = np.array([400, 300, 300])
chi2, p_value, dof, _ = chi2_contingency(np.vstack([reference_counts, current_counts]))
print(f"chi2={chi2:.2f}, dof={dof}, p-value={p_value:.2e}")The expected counts here are 450, 300 and 250 per window. The statistic works out to about 31.1 with 2 degrees of freedom (k - 1), and the p-value is on the order of 1e-7. The middle category did not change, and the shift came from the first and third.
Handling real categorical data
In production you start from raw values, not counts. Two details cause most bugs:
- Categories that appear in only one window. A new category in the current window has a count of zero in the reference. Build the category list from the union of both windows so the table has no all-zero columns.
- Small expected counts. The chi-square approximation is unreliable when expected counts fall below about 5. Merge rare categories into an "other" bucket before testing.
import numpy as np
from scipy.stats import chi2_contingency
def chi2_drift(reference, current, min_expected=5):
reference = np.asarray(reference)
current = np.asarray(current)
categories = np.unique(np.concatenate([reference, current]))
table = np.array([
[(reference == c).sum() for c in categories],
[(current == c).sum() for c in categories],
])
chi2, p_value, dof, expected = chi2_contingency(table)
n_total = table.sum()
# With two rows, Cramer's V reduces to sqrt(chi2 / n_total)
cramers_v = float(np.sqrt(chi2 / n_total))
return {
"chi2": float(chi2),
"p_value": float(p_value),
"cramers_v": cramers_v,
"new_categories": [c for c, r in zip(categories, table[0]) if r == 0],
"small_expected": bool((expected < min_expected).any()),
}
ref = ["web"] * 500 + ["app"] * 300 + ["store"] * 200
cur = ["web"] * 400 + ["app"] * 300 + ["store"] * 290 + ["kiosk"] * 10
print(chi2_drift(ref, cur))The function returns Cramér's V, an effect size between 0 and 1, and it lists categories that never appeared in the reference. A new category is often a data pipeline change and deserves its own alert regardless of the p-value.
Why p-values alone mislead in monitoring
Hypothesis tests were designed to answer "is there any difference?" Monitoring usually needs "is the difference big enough to care about?" The p-value depends heavily on sample size, so the two questions diverge.
The following sketch holds a tiny shift fixed and grows the window size:
import numpy as np
from scipy.stats import ks_2samp
rng = np.random.default_rng(1)
for n in (200, 2_000, 20_000, 200_000):
reference = rng.normal(0.0, 1.0, size=n)
current = rng.normal(0.03, 1.0, size=n)
result = ks_2samp(reference, current)
print(f"n={n:>7} KS={result.statistic:.4f} p={result.pvalue:.3g}")The true shift is 0.03 standard deviations, which is far too small to affect most models. The KS statistic stays small at every size, but the p-value shrinks as n grows. At a large enough n, the test flags drift that has no practical meaning.
The reverse also happens. With 200 rows per window, a large shift may not reach p < 0.05, because the test lacks power.
| Situation | p-value | Statistic or effect size | Reading |
|---|---|---|---|
| Large windows, tiny shift | Very small | Small | Statistically real, practically negligible |
| Small windows, large shift | Moderate | Large | Possibly real, collect more data |
| Large windows, large shift | Very small | Large | Drift worth investigating |
| Any size, no shift | Large | Near zero | No evidence of drift |
The multiple-testing problem
If a model has 100 features and you test each at a 0.05 significance level, you expect about 5 false alarms per window even when nothing changed. Running the check daily makes this worse.
Common ways to deal with it:
- Lower the per-feature p-value cutoff (for example 0.001), or apply a Bonferroni correction by dividing 0.05 by the number of tests.
- Alert on the effect size, which does not inflate with the number of tests in the same way.
- Alert only when several features drift together, or when a high-importance feature drifts.
- Require the signal to persist for several consecutive windows before alerting.
The chapter on alert thresholds returns to these options. For now, remember that the number of features you test is part of the false alarm rate.
Edge cases and common errors
- Using a p-value from a one-sample test.
ks_2sampcompares two samples.kstestcompares one sample with a theoretical distribution. Using the wrong one gives meaningless results. - Missing values.
ks_2sampdoes not handle NaN the way you want. Drop or handle nulls first, and monitor the null rate as a data quality check instead. - Very different window sizes. The tests handle unequal sizes, but a tiny current window gives low power. Wait until you have enough rows, or widen the window.
- Correlated rows. Tests assume independent observations. If one user contributes hundreds of rows, the effective sample size is much smaller than the row count, and p-values are too optimistic. Aggregate or sample per entity if this applies.
- High-cardinality categoricals. A feature with thousands of IDs gives a sparse table. Group rare values, or monitor a derived feature such as the share of known IDs.
- Chi-square on continuous data. Do not bin a numeric feature just to use chi-square when KS fits. Binning throws away information and makes results depend on bin edges.
Putting it together
A practical per-feature report has one row per feature with these columns: feature name, type, test used, statistic or effect size, p-value, and a drift flag. Sort by effect size, not by p-value, so the biggest movers are at the top.
Exercise
Your model has 80 features. You run a KS or chi-square test on each one every day at significance level 0.05, and each window holds 500,000 rows. Every day you get several drift alerts, but model accuracy has not changed. Give two reasons for the alerts and one change that would reduce them.
Show answer
First, with 500,000 rows the tests have so much power that tiny, harmless shifts produce very small p-values. Second, with 80 features at level 0.05 you expect about 4 false positives per day from multiple testing alone. A fix is to require an effect size threshold (for example KS statistic above 0.1 or Cramér's V above 0.1) in addition to a small p-value. Lowering the p-value cutoff with a Bonferroni correction, or requiring drift to persist across several windows, also helps.
Exercise
A categorical feature "device" has 3 values in the reference window. In the current window a fourth value, "tv", appears in 2% of rows. If you build the count table only from the reference categories, what goes wrong, and how does the union-of-categories approach fix it?
Show answer
Building the table only from reference categories drops the "tv" rows, so the test never sees the new category and can miss an important change. If you instead include "tv" with a reference count of zero, the table is correct only if you build the categories from both windows. Using the union of categories from both windows keeps every row in the table, and the zero reference count makes the new category show up as drift. You can also report new categories separately as a data quality alert.