A ticket router used to predict refunds more often than shipping questions. This week those proportions are reversed and a third label appears. Raw counts can exaggerate a change if traffic also grew. Jensen–Shannon divergence compares the proportions instead, including labels that were absent from either window. It measures a shift in predictions, not a drop in accuracy.
Compare windows on a shared label set
Use Python 3 with no third-party packages. Save the example as drift.py. It accepts mappings from string labels to nonnegative integer counts. Each window is normalized independently. A label not present in a mapping gets probability zero in that window, while an entirely empty window is rejected.
from math import isclose, log2
def divergence(before, after):
labels = sorted(before.keys() | after.keys())
for counts in (before, after):
if any(type(n) is not int or n < 0 for n in counts.values()):
raise ValueError("expected nonnegative integer counts")
totals = sum(before.values()), sum(after.values())
if 0 in totals:
raise ValueError("empty observation window")
result = 0.0
for label in labels:
p = before.get(label, 0) / totals[0]
q = after.get(label, 0) / totals[1]
m = (p + q) / 2
if p:
result += p * log2(p / m) / 2
if q:
result += q * log2(q / m) / 2
return result
before = {"refund": 8, "shipping": 2}
after = {"refund": 2, "shipping": 6, "other": 2}
value = divergence(before, after)
assert isclose(value, divergence(after, before))
assert divergence(before, {"refund": 80, "shipping": 20}) == 0
assert divergence({"x": 1}, {"y": 1}) == 1
try:
divergence({}, before)
except ValueError:
pass
else:
raise AssertionError("empty window accepted")
print(f"{value:.6f} bits")Run python3 drift.py. Expected output:
0.314525 bitsWhy a new label does not break the calculation
For each label, the midpoint is the average of the two probabilities. A positive probability always has a positive midpoint, so its ratio is defined. A zero-probability term contributes zero and is skipped. With base-2 logarithms the divergence is measured in bits. Identical proportions give zero, and distributions with no overlap give one. SciPy's similarly named function returns the square root, which is a distance rather than the divergence printed here.
Troubleshoot a large shift
Put the counts next to the metric. A shift observed across a handful of predictions is not equivalent evidence to the same shift across thousands. Check that both windows use the same label taxonomy and counting rules. A renamed label may look like one label disappearing and another appearing even though the routing policy is unchanged. Compare the same channel or locale across periods if a changing traffic mix could explain the difference. Use a reviewed sample with ground-truth labels before interpreting drift as a quality regression, and do not turn the example value into a universal alert threshold.
Primary references and related tutorials: Lin's paper on divergence measures · SciPy distance reference · Java Samples AI tutorials.