Detect drift in a categorical feature with a chi-square statistic

MediumMLOpsPro

Why it matters Categorical drift checks run on every batch in feature monitoring jobs, where new category values appear all the time.

For categorical features (country, device, plan) drift checks compare today's category counts with what the training distribution predicts. New categories must not cause a division by zero.

Write chi_square_drift(ref_counts, cur_counts). Both are dicts from category to count. Let cats be the sorted union of keys and K = len(cats). Reference shares use add-one smoothing: share_c = (ref_c + 1) / (N_ref + K), where missing counts are 0. Expected current count e_c = share_c * N_cur. Return (chi2, dof) where chi2 = sum over cats of (cur_c - e_c) ** 2 / e_c as a float and dof = K - 1.

Signaturedef chi_square_drift(ref_counts, cur_counts)

Example

chi_square_drift({"a": 3, "b": 1}, {"a": 2, "b": 2}) gives (0.5, 1).

Understand the idea

A chi-square test asks: if nothing changed, how surprising are today's counts? We compute what we would expect from the training mix and add up the squared gaps, each scaled by its expected size so big categories do not dominate.

Example: training saw a 3 and b 1. With add-one smoothing the shares are (3 + 1) / 6 = 0.667 and (1 + 1) / 6 = 0.333. Today there are 4 rows, so we expect 2.67 and 1.33 but see 2 and 2. Chi-square = 0.44 / 2.67 + 0.44 / 1.33 = 0.167 + 0.333 = 0.5 with 1 degree of freedom, a small change.

Rules: share_c = (ref_c + 1) / (N_ref + K); e_c = share_c * N_cur; chi2 = sum (o_c - e_c)^2 / e_c; dof = K - 1.

Larger chi2 for its dof means stronger evidence of drift; monitoring jobs compare it with a threshold or a p-value.

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

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

  • Sample 1: examplechi_square_drift({'a': 3, 'b': 1}, {'a': 2, 'b': 2})
  • Sample 2: new categorychi_square_drift({'IN': 80, 'US': 20}, {'IN': 40, 'US': 10, 'BR': 10})