Population stability index (drift monitoring)
Problem
expected_counts and actual_counts are histogram counts over the same bins. Convert each to proportions, clip each proportion below at eps, and return PSI = Σ (a − e)·ln(a/e).
Signature
def psi(expected_counts: list[int], actual_counts: list[int], eps: float = 1e-6) -> float: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(psi([50, 50], [50, 50]), 0.0)
True
>>> close(psi([100, 100], [150, 50]), 0.274653)
TrueHints
Normalise counts to proportions; clip each below at eps.
PSI = sum (a - e) * ln(a/e).
Guard empty bins with eps; know the rule-of-thumb bands.
Reference solution
import math
def psi(expected_counts, actual_counts, eps=1e-6):
E = sum(expected_counts); A = sum(actual_counts)
tot = 0.0
for e, a in zip(expected_counts, actual_counts):
pe = max(e / E, eps); pa = max(a / A, eps)
tot += (pa - pe) * math.log(pa / pe)
return totWhat a strong solution covers
- Normalises counts.
- Smooths empty bins with eps.
- Knows the rule-of-thumb bands (<0.1 stable, 0.1–0.25 moderate, >0.25 significant) and their limits.
- Discusses binning on reference quantiles, KS/Chebyshev alternatives, and per-segment monitoring.
Common mistakes
- log of zero for empty bins
- computing on raw counts with different totals.