Drift testing
Why This Matters
A model is a snapshot of the world at the time its training data was collected. The world moves on: customers change, fraudsters invent new tricks, a new law changes what a good loan looks like. The model does not notice. Its accuracy slips week by week, without an error, until someone asks why so many loans default. Drift testing is the early warning.
What you will learn
- The difference between data drift and concept drift
- Dynamic drift testing, with feedback as ground truth
- Static drift testing, with statistical comparison of distributions
- How to implement both for the loan model
Syllabus: AI-6.1.7.
Two kinds of drift
- Data drift: the statistics of the inputs change. A spam filter starts receiving new kinds of phishing it has never seen; a loan model starts receiving older, richer applicants. The relationship between input and correct answer may be the same; the model just sees inputs from regions it was not trained on.
- Concept drift: the relationship between inputs and the correct output changes. A transaction type that was low-risk becomes high-risk after a change in regulation; an applicant who would have repaid last year cannot after interest rates double. The inputs can look exactly the same; the right answer is different.
Both make a once-good model worse. Data drift is visible in the inputs; concept drift is only visible when you know the right answers.
Dynamic drift testing
Uses feedback from users as ground truth:
- direct feedback: a rating, a “this is not spam” click, a loan that was or was not repaid
- indirect feedback: behaviour, such as what a user watched after a recommendation
Compare the feedback with the model’s output, over time, against an agreed threshold. If agreement drops below it, raise an alarm. Dynamic drift testing catches both kinds of drift, but feedback can arrive late (you know whether a loan was repaid only after months).
Static drift testing
Needs no ground truth. Compare the distributions of the inputs, and of the outputs, between a reference period (training, or the first months in production) and now, with a statistical test such as Kolmogorov-Smirnov (lesson 37). A significant difference signals drift. Static testing is fast and works without labels, but it sees only data drift, and only that something changed, not whether the model got worse.
Hands-on
You continue in the practice project. Create module-7/test_drift.py. Static drift: the reference period is the test set (applicants like the training population), the current period is the production dataset:
"""Lesson "Drift testing": static drift (distributions) and dynamic drift (feedback) for the loan model."""
import numpy as np
import pytest
from scipy import stats
NEUTRAL = {"name": "Applicant", "gender": "Unknown", "employmentYears": 4, "zipCode": "60601"}
def predict(api, applicants, model="v1"):
predictions = []
for start in range(0, len(applicants), 100):
response = api.post(f"{api.base}/predict/batch", timeout=10,
json={"applicants": applicants[start:start + 100], "model": model, "seed": 1})
response.raise_for_status()
predictions += response.json()["predictions"]
return predictions
def as_applicants(rows):
"""Keep age, income and credit score; fill the rest with the same neutral values for every dataset."""
return [{**NEUTRAL, "age": r["age"], "income": r["income"], "creditScore": r["creditScore"]} for r in rows]
@pytest.fixture(scope="module")
def reference_and_current(api):
reference = as_applicants(api.get(f"{api.base}/test-set", timeout=10).json()["data"])
current = as_applicants(api.get(f"{api.base}/datasets/loans-production", timeout=10).json()["data"])
return reference, current
@pytest.mark.xfail(strict=True, reason="data drift: production inputs differ from the reference period")
@pytest.mark.parametrize("feature", ["age", "income", "creditScore"])
def test_static_drift_in_the_inputs(reference_and_current, feature):
reference, current = reference_and_current
result = stats.ks_2samp([a[feature] for a in reference], [a[feature] for a in current])
print(f"\n {feature}: KS {result.statistic:.2f}, p = {result.pvalue:.1g}", end="")
assert result.pvalue >= 0.05
@pytest.mark.xfail(strict=True, reason="the model's output has drifted too")
def test_static_drift_in_the_output(api, reference_and_current):
reference, current = reference_and_current
ref, cur = predict(api, reference), predict(api, current)
result = stats.ks_2samp([p["score"] for p in ref], [p["score"] for p in cur])
print(f"\n approval rate {np.mean([p['approved'] for p in ref]):.0%} -> {np.mean([p['approved'] for p in cur]):.0%};"
f" score KS {result.statistic:.2f}, p = {result.pvalue:.2g}")
assert result.pvalue >= 0.05
The production data has no gender, name, employment or zip code, so both datasets get the same neutral values for those: only age, income and credit score differ.
Dynamic drift needs feedback over time, which the practice API does not have. The test simulates it: eight weeks of applicants, and whether each one repaid. From week 5 a new affordability rule applies, so repayment needs an income above $70,000 instead of $45,000. That is concept drift: the applicants look the same, the right answer changed.
def simulated_weeks(weeks=8, per_week=60, regulation_from_week=5):
"""A stream of applicants with feedback (did they repay?). From week 5, a new affordability rule
means applicants need an income above $70,000 instead of $45,000 to repay: concept drift."""
rng = np.random.default_rng(7)
for week in range(1, weeks + 1):
applicants = [{**NEUTRAL, "age": int(rng.integers(25, 55)), "income": int(rng.integers(30000, 120000)),
"creditScore": int(rng.integers(540, 800)), "employmentYears": int(rng.integers(0, 15))}
for _ in range(per_week)]
income_needed = 45000 if week < regulation_from_week else 70000
repaid = [a["creditScore"] > 640 and a["income"] > income_needed for a in applicants]
yield week, applicants, repaid
def test_dynamic_drift_alarm(api):
"""Compare predictions with feedback per week; raise the alarm when accuracy drops 10 points below the baseline."""
accuracy = {}
for week, applicants, repaid in simulated_weeks():
approved = [p["approved"] for p in predict(api, applicants)]
accuracy[week] = np.mean(np.array(approved) == np.array(repaid))
baseline = np.mean([accuracy[w] for w in (1, 2, 3, 4)])
alarms = [w for w, a in accuracy.items() if a < baseline - 0.10]
print("\n " + " ".join(f"week {w}: {a:.2f}" for w, a in accuracy.items()))
print(f" baseline {baseline:.2f}, alarm below {baseline - 0.10:.2f}: alarm in weeks {alarms}")
assert alarms and min(alarms) == 5
Run it
pytest module-7/test_drift.py -v -s
age: KS 0.46, p = 0.0001 XFAIL
income: KS 0.72, p = 2e-11 XFAIL
creditScore: KS 0.36, p = 0.005 XFAIL
approval rate 65% -> 96%; score KS 0.31, p = 0.022
XFAIL
week 1: 0.68 week 2: 0.75 week 3: 0.77 week 4: 0.72 week 5: 0.45 week 6: 0.60 week 7: 0.55 week 8: 0.45
baseline 0.73, alarm below 0.63: alarm in weeks [5, 6, 7, 8]
PASSED
Read the result
Static: all three inputs have drifted significantly, income most of all (KS 0.72). And the output drifted with them: the model now approves 96% of applicants instead of 65%. Nobody changed the model. The richer production population pushes scores up, and the model, never trained on such incomes, approves almost everyone. Whether that is right, static testing cannot say; it says look here.
Dynamic: accuracy against feedback is stable around 0.73 for four weeks, then drops to 0.45 the week the new rule applies, and stays low. The alarm fires in week 5, the first week of the drift. Static testing would have missed this entirely: the applicants of week 5 look just like those of week 4.
Choosing the threshold is a trade-off. A 10-point drop catches this drift at once; with a 5-point threshold, normal week-to-week variation (0.68 to 0.77 in the stable weeks) would cause false alarms. Agree the threshold with the business, and base it on the variation you see in stable periods.
Exercise
- Which of the two drift tests would detect each situation: (a) a new competitor attracts all young customers, so your applicants get older; (b) after a recession, applicants with the same income and credit score default more often; (c) a bug in the website sends all incomes in thousands instead of euros?
- Feedback about loan repayment arrives only after 12 months. What does that mean for dynamic drift testing, and what would you do in the meantime?
Show suggested answer
(a) Static (data drift: the age distribution changes) and possibly dynamic, if accuracy changes for the new mix. (b) Dynamic only: concept drift, the inputs look the same. (c) Static: the income distribution changes dramatically overnight. This is not real-world drift but a pipeline defect; drift monitoring often catches those too (lesson 36).
A 12-month delay means concept drift is detected a year late. In the meantime: monitor static drift on inputs and outputs; use early proxy feedback (missed first payments after 1 to 3 months, which correlate with defaults); and watch external signals that predict concept drift (interest rates, unemployment, new regulation).
Exam-style questions
1. After a change in regulation, transactions that were low-risk become high-risk, although the transactions themselves look the same. What type of drift is this?
- A. Data drift
- B. Concept drift
- C. Overfitting
- D. Adversarial drift
Show answer
2. Which drift testing approach does not need ground truth?
- A. Dynamic drift testing with direct user feedback
- B. Static drift testing, comparing input and output distributions statistically
- C. A/B testing
- D. Label correctness testing
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-7/
├── test_functional_performance.py
├── test_adversarial.py
├── test_metamorphic.py
└── test_drift.py new in this lesson
The finished version is in the example repository: module-7/test_drift.py.