Measure feature drift with smoothed KL divergence on quantile bins

MediumMLOpsPro

Why it matters Feature drift monitors in production ML pipelines compute exactly this kind of binned divergence on a schedule.

A monitoring job compares today's feature values with the training data. Binning by the reference quantiles and comparing bin shares with KL divergence gives one drift number, but empty bins must be smoothed or the score becomes infinite.

Write kl_drift(ref, cur, n_bins, eps=1e-4).
- Interior edges: np.quantile(ref, np.linspace(0, 1, n_bins + 1))[1:-1].
- Bin index of a value: np.searchsorted(edges, x, side="right"), giving 0 to n_bins - 1.
- p = share of ref values per bin, q = share of cur values per bin. Add eps to every bin of both and renormalise each to sum to 1.
- Return KL(p || q) = sum p * log(p / q) as a float.

Signaturedef kl_drift(ref, cur, n_bins, eps=1e-4)

Example

kl_drift([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 1, 2, 2, 2, 7, 8], 4) gives 3.6376.

Understand the idea

Data drift means the inputs a model sees in production no longer look like its training data. A simple monitor buckets a feature into bins and compares how much of the data falls in each bin, then and now. Using reference quantiles as bin edges gives every bin the same share of training data, so differences stand out.

Example: training values 1 to 8 in 4 bins hold 25% each. Today's values pile up at 1 and 2, so the shares are [75%, 0, 0, 25%]. Two bins are empty; with a tiny eps they get about 0.0001 each instead of 0, and KL comes out around 3.64, a clear alarm.

Rule: KL(p || q) = sum_i p_i * log(p_i / q_i), with p, q smoothed by eps and renormalised.

Teams usually alert above a threshold tuned on past weeks, alongside PSI or KS checks.

Shapes and data flow

ref: (N,), cur: (M,) -> edges: (B - 1,) -> p, q: (B,) -> scalar
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplekl_drift([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 1, 2, 2, 2, 7, 8], 4)
  • Sample 2: no driftkl_drift(_a, _a[::-1], 5)