Detect feature drift with the Population Stability Index

EasyMLOps

A model trained on last year's data can quietly degrade when inputs shift. PSI compares a feature's distribution in production against training.

Write psi(expected, actual, bins). Use bin edges from the quantiles of `expected`: np.quantile(expected, np.linspace(0, 1, bins + 1)), then set the first edge to -inf and the last to +inf. Count both samples per bin (np.histogram with those edges), turn counts into fractions, replace any fraction below 1e-6 with 1e-6, and return sum((a - e) * ln(a / e)).

Signaturedef psi(expected, actual, bins)

Understand the idea

The Population Stability Index measures how much a feature's distribution in production has shifted from training. Cut the training values into bins of equal population using quantiles, make the first and last bins open-ended so out-of-range production values are still counted, then compare the share of each sample in each bin. Like checking whether this year's class has the same mix of marks as last year's. Worked example with 4 bins: training shares are [0.25, 0.25, 0.25, 0.25], production shares [0.1, 0.2, 0.3, 0.4]. Terms (a - e) ln(a / e): (-0.15)(ln 0.4 = -0.916) = 0.137; (-0.05)(ln 0.8 = -0.223) = 0.011; (0.05)(ln 1.2 = 0.182) = 0.009; (0.15)(ln 1.6 = 0.470) = 0.071. PSI = 0.228. A common rule of thumb reads under 0.1 as stable and above 0.25 as a big shift. Replace any share below 1e-6 with 1e-6 so the log is defined. Rule: PSI = sum over bins of (a - e) ln(a / e). Model monitoring dashboards track PSI per feature.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: no driftpsi(_tr, _same, 10)
  • Sample 2: driftpsi(_tr, _shift, 10)
  • Test 3: out-of-range values still countedpsi([1.0, 2.0, 3.0, 4.0], [10.0, 11.0, 12.0, 13.0], 2)