Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 07 · 40 minutes

Detect data drift in production and decide what to do

After this lesson you can
  • Measure drift of a feature with a population stability index and a two-sample test
  • Turn the measures into alert rules and a monitoring report
  • Choose between keeping, holding, retraining and rolling back
Lab files of this lesson (30)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Three weeks after the launch, a customer service agent says: "The model flags far too many logins." The model has not changed, and no error appears in the logs. Your lead asks: "Is the world different from what the model learned, and how would we have known on day one?" You have a sample of the data from training and samples of live data. You build the check that compares them, and rules that say what to do.

Recall

Lesson 6: which two evaluation gates does a release need, and why two?

Accuracy and recall. A model can pass the accuracy gate and still miss attacks (version 3 of lesson 6: 0.92 accuracy, 0.83 recall). The second number catches what the first one hides.

Lesson 6: how do you go back to the previous model, and what does the script change?

python release.py rollback. It removes the last version from the history, makes the one before it current, copies its files into models/current, and writes the registry.

The idea

A model is tested on data from the past, and it runs on data from today. Drift means that the data of today differs from the data that the model learned from. It has two kinds. Data drift is a change in what comes in: more failed logins, new devices, a column that is suddenly empty. Concept drift is a change in what the inputs mean: the same login pattern is now an attack, and before it was not. Concept drift needs fresh labels (the true answers), and labels come late. Data drift you see at once, so you watch it first.

You compare a reference sample (the training data) with a live sample (what came in lately), one feature at a time, with two measures:

MeasureWhat it doesReads as
Population stability index (PSI)Cuts the values into bins. For each bin it compares the share in the live sample with the share in the reference sample, and adds up (live - ref) * ln(live / ref).0 is no change. A common rule of thumb says 0.10 and above is a small shift, and 0.25 and above is a big one.
Two-sample Kolmogorov-Smirnov (KS) testFinds the largest gap D between the two cumulative curves of the samples, and a p-value.D near 0 is the same shape. The p-value is the chance of a gap this large if both samples came from the same source. A p-value below 0.01 says "probably not the same".

The thresholds are common practice, not a standard. Set yours from your own data and the cost of a false alarm.

This lesson works on sample files, because the service and the gateway log no inputs, on purpose (lessons 2 and 3). Keeping live inputs for drift is a privacy choice: keep the minimum (here three numbers and no identity), set a retention time, and write it in the architecture file.

From samples to an action
Reference, live sampleCompareAlert ruleReportActionbins, gaps, p-valuesPSI and KS for each featureok, warn or alertkeep, hold, retrain or roll backReference, live sampleCompareAlert ruleReportAction1234
  1. Reference, live sample → Compare: bins, gaps, p-values
  2. Compare → Alert rule: PSI and KS for each feature
  3. Alert rule → Report: ok, warn or alert
  4. Report → Action: keep, hold, retrain or roll back

Worked example

1. Make the fixed samples

make_samples.py writes five files of 1000 events. reference is the training data. live-a is a normal day. live-b has four more failed logins on every event. live-c has lost the km column (every value is 0), as when an upstream system stops sending it. live-d has two more failed logins on one event in five.

make_samples.py

"""make_samples.py: write fixed samples of login events for the drift lesson."""
import json
from pathlib import Path

from data import make_events

Path("samples").mkdir(exist_ok=True)
SAMPLES = {
    "reference": make_events(1, 1000),                    # what the model was trained on
    "live-a": make_events(2, 1000),                       # a normal day
    "live-b": make_events(3, 1000, shift=4),              # four more failed logins on every event
    "live-c": [{**e, "km": 0} for e in make_events(4, 1000)],   # the km column is lost upstream
    "live-d": [{**e, "failed": e["failed"] + (2 if i % 5 == 0 else 0)} for i, e in enumerate(make_events(5, 1000))],   # a few more failures
}
for name, events in SAMPLES.items():
    Path("samples", name + ".json").write_text(json.dumps(events))
    print(name, len(events), "events")
python make_samples.py
reference 1000 events
live-a 1000 events
live-b 1000 events
live-c 1000 events
live-d 1000 events

2. Save the drift check

psi applies the formula. It puts a floor of 0.0001 on every share, so that an empty bin does not cause a division by zero. ks is the two-sample test: it walks over every value in either sample and keeps the largest gap, then turns it into a p-value with the Kolmogorov distribution. status applies the alert rule. report collects the results for all three features, and advise is the decision rule of step 5.

drift.py

"""drift.py: compare live data with the training sample. Two measures for each feature, an alert rule and a report.

    python3 drift.py samples/reference.json samples/live-a.json [--out report.json] [--today 2026-11-21]
Exit code: 0 for ok or warn, 1 for alert.
"""
import json
import math
import sys
from bisect import bisect_right
from datetime import date

from data import FEATURES

EDGES = {"failed": [1, 2, 4, 7, 10], "new_device": [1], "km": [10, 50, 100, 200, 300]}   # bin borders, fixed
WARN_PSI, ALERT_PSI, ALPHA = 0.10, 0.25, 0.01


def psi(expected, actual, edges):
    """Population stability index: the sum over bins of (live share - training share) * ln(live share / training share)."""
    def shares(values):
        counts = [0] * (len(edges) + 1)
        for v in values:
            counts[bisect_right(edges, v)] += 1
        return [max(c / len(values), 0.0001) for c in counts]   # a floor, so that an empty bin does not divide by zero
    return sum((a - e) * math.log(a / e) for e, a in zip(shares(expected), shares(actual)))


def ks(a, b):
    """Two-sample Kolmogorov-Smirnov test. Return the largest gap between the two cumulative curves, and its p-value."""
    a, b = sorted(a), sorted(b)
    d = max(abs(bisect_right(a, v) / len(a) - bisect_right(b, v) / len(b)) for v in set(a) | set(b))
    x = d * math.sqrt(len(a) * len(b) / (len(a) + len(b)))
    p = 2 * sum((-1) ** (k - 1) * math.exp(-2 * k * k * x * x) for k in range(1, 101))
    return d, min(max(p, 0.0), 1.0)


def status(p_index, p_value):
    if p_index >= ALERT_PSI:
        return "alert"
    return "warn" if p_index >= WARN_PSI or p_value < ALPHA else "ok"


def report(reference, live, today):
    features = {}
    for name in FEATURES:
        ref, now = [e[name] for e in reference], [e[name] for e in live]
        index, (d, p) = psi(ref, now, EDGES[name]), ks(ref, now)
        features[name] = {"psi": round(index, 2), "ks": round(d, 2), "p": round(p, 4), "status": status(index, p)}
    worst = max((f["status"] for f in features.values()), key=["ok", "warn", "alert"].index)
    return {"date": today, "samples": [len(reference), len(live)], "status": worst, "features": features}


def advise(drift_status, promoted_recently, accuracy_fell):
    """What to do. Roll back when a new release came directly before the drift, retrain when labels show a loss, else hold."""
    if drift_status == "ok":
        return "keep"
    if drift_status == "alert" and promoted_recently:
        return "roll back"
    if drift_status == "alert" and accuracy_fell:
        return "retrain"
    return "hold"


if __name__ == "__main__":
    args = sys.argv[1:]
    out = args.pop(args.index("--out") + 1) if "--out" in args else None
    today = args.pop(args.index("--today") + 1) if "--today" in args else date.today().isoformat()
    args = [a for a in args if a not in ("--out", "--today")]
    with open(args[0]) as f, open(args[1]) as g:
        result = report(json.load(f), json.load(g), today)
    print("feature      psi    ks      p  status")
    for name, f in result["features"].items():
        print(f"{name:11} {f['psi']:5.2f} {f['ks']:5.2f} {f['p']:6.4f}  {f['status']}")
    print("overall:", result["status"])
    if out:
        with open(out, "w") as f:
            json.dump(result, f, indent=1)
    sys.exit(1 if result["status"] == "alert" else 0)

3. Look at the bins, then run the check

bisect_right(edges, v) gives the number of the bin that a value falls in. The bin borders of failed are 1, 2, 4, 7 and 10, so there are six bins. The first command prints the share of events in each bin for three samples. The loop runs the check on four live samples. Each line of its table has five parts:

A line of the drift table (live-b)
failedthe feature4.92PSI: above 0.25 is a big shift0.57KS gap D0.0000p-value of the KS testalertthe statusfailedthe feature4.92PSI: above 0.25 is a big shift0.57KS gap D0.0000p-value of the KS testalertthe status
python - <<'EOT'
import json
from bisect import bisect_right
from drift import EDGES
edges = EDGES["failed"]
for name in ("reference", "live-a", "live-b"):
    counts = [0] * 6
    for e in json.load(open(f"samples/{name}.json")):
        counts[bisect_right(edges, e["failed"])] += 1
    print(name.ljust(10), [round(c / 1000, 2) for c in counts])
EOT
for s in a b c d; do echo "== live-$s"; python drift.py samples/reference.json samples/live-$s.json; echo "exit code $?"; done
reference  [0.29, 0.13, 0.15, 0.19, 0.14, 0.09]
live-a     [0.29, 0.11, 0.18, 0.19, 0.15, 0.08]
live-b     [0.0, 0.0, 0.0, 0.49, 0.2, 0.3]
== live-a
feature      psi    ks      p  status
failed       0.01  0.02 0.9999  ok
new_device   0.00  0.01 1.0000  ok
km           0.02  0.03 0.7226  ok
overall: ok
exit code 0
== live-b
feature      psi    ks      p  status
failed       4.92  0.57 0.0000  alert
new_device   0.00  0.01 1.0000  ok
km           0.02  0.05 0.1205  ok
overall: alert
exit code 1
== live-c
feature      psi    ks      p  status
failed       0.01  0.02 0.9995  ok
new_device   0.00  0.03 0.8593  ok
km           7.93  0.95 0.0000  alert
overall: alert
exit code 1
== live-d
feature      psi    ks      p  status
failed       0.05  0.09 0.0005  warn
new_device   0.00  0.00 1.0000  ok
km           0.01  0.04 0.2877  ok
overall: warn
exit code 0

In live-b the first three bins are empty and the last three hold all the events. live-c shows the lost column: only km shifts. live-d is the interesting one: the PSI of failed is only 0.05, below any alert, but the KS test sees the shift (p of 0.0005) and the status is warn. The two measures catch different things, which is why you use both.

Largest PSI of each live sample
live-a (km)0.02live-b (failed)4.92live-c (km)7.93live-d (failed)0.05live-a (km)0.02live-b (failed)4.92live-c (km)7.93live-d (failed)0.05

4. Check the test against a library

SciPy (pinned in your environment) has the same test. The gaps D must agree. The lesson uses the formula for large samples. SciPy works out the exact p-value when the samples are not very large, so the two p-values agree to about two digits (0.0005). The login counts are whole numbers with many ties, and the KS test is then conservative: its p-value is a little too high.

python - <<'EOT'
import json
from scipy.stats import ks_2samp
from drift import ks
ref = [e["failed"] for e in json.load(open("samples/reference.json"))]
now = [e["failed"] for e in json.load(open("samples/live-d.json"))]
print(round(ks(ref, now)[0], 3), round(float(ks_2samp(ref, now).statistic), 3))
EOT
0.091 0.091

5. Write the report and choose an action

--out saves the report as a JSON file, and lesson 10 reads that file. The report is the evidence: it holds the date, the sizes of both samples and the numbers.

python drift.py samples/reference.json samples/live-b.json --out drift-report.json --today 2026-11-21 > /dev/null
head -9 drift-report.json
python - <<'EOT'
import drift
for case in [("ok", False, False), ("warn", False, False), ("alert", False, True), ("alert", True, True)]:
    print(case, "->", drift.advise(*case))
EOT
{
 "date": "2026-11-21",
 "samples": [
  1000,
  1000
 ],
 "status": "alert",
 "features": {
  "failed": {
('ok', False, False) -> keep
('warn', False, False) -> hold
('alert', False, True) -> retrain
('alert', True, True) -> roll back

advise takes the status, whether a new model was promoted directly before the drift, and whether labels show that the accuracy has fallen. A drift that starts right after a release is more likely a fault of the release than a change in the world, so it rolls back first. A drift with a measured loss means retrain. Anything else is a hold: watch, and look for the cause.

Your turn

A small test file holds one reference sample and two live samples of the km feature, 20 values each. Save it.

small-samples.json

{"reference": [5, 12, 30, 45, 60, 75, 90, 110, 130, 150, 170, 190, 210, 230, 250, 270, 290, 310, 350, 390],
 "live-1": [8, 15, 22, 35, 48, 52, 66, 80, 95, 105, 120, 140, 160, 185, 205, 240, 260, 330, 380, 395],
 "live-2": [3, 9, 14, 20, 26, 31, 38, 44, 49, 55, 61, 68, 74, 82, 88, 96, 104, 115, 125, 135]}

Use drift.psi, drift.ks and drift.status with the bin borders drift.EDGES["km"] to judge live-1 and live-2 against reference. Round the PSI and D to two decimals. Then give drift.psi no bin border at all ([], so one bin) for live-2, and say in one sentence why the choice of bins is a security decision (the answer is in Check yourself). Last, ask drift.advise what to do with an alert, no new release and a measured loss.

Check yourself

The PSI of live-d is small and the KS test warns. What does that tell you about using only one measure?

A binned measure can miss a small shift that happens inside a bin or in a part of the data, and a test on whole curves can miss a change that moves values between bins in a balanced way. Use two measures that fail in different ways, and look at the data when they disagree.

Why is the choice of bins a security decision?

Bins that are too coarse hide a shift: with one bin the PSI is 0.0 whatever the data. An attacker who knows the borders can move inputs inside a bin and stay unseen. Choose the borders from the quantiles of the reference sample, and review them like code.

With a large sample, almost any small difference gets a tiny p-value. What do you do about it?

Do not alarm on the p-value alone. The rule of this lesson warns on it but alerts only on the PSI, which measures the size of the change. Also watch the effect on the model: the share of "suspicious" answers per day, and the accuracy on the labels that arrive later.

Why compare a live sample with the training data and not with yesterday's data?

Yesterday's data can already have drifted, and a slow drift never shows between two neighbouring days. Compare with the reference that the model learned from, and also keep a short window (a week against the week before) to see sudden changes.

Field notes

  • Watch the output as well as the inputs: the share of suspicious answers, the score distribution, and the rate of errors and refusals. A change there is the first sign when labels are late.
  • Alert on a trend over several samples, not on one. A single odd hour should be a warn at most.
  • Write down the response to each alert before the night it happens: who is called, who may roll back, and who decides to retrain. A rollback that needs a meeting is too slow.
  • Treat distribution shift as a normal event, not an accident. The aim is to see it early and have a rehearsed response. The NIST AI Risk Management Framework 1.0 puts monitoring of a deployed system in its Manage function.