This is Module 5 of the Machine Learning Engineer path. A model that scored well when you shipped it can quietly get worse as the world changes: new customers, a new product, a changed field upstream. This module builds the monitoring that tells you, and a rule for what to do about it.

You’ll build: one script that checks a deployed model’s inputs, outputs and accuracy over three simulated weeks, with alarm thresholds calibrated on your own data.

You need: the model and data from Module 4 (run make_data.py and train.py), plus SciPy (pip install scipy).

Three things to watch

What Question When you can check it
Inputs Do this week’s features look like the training data? Immediately
Outputs Is the share of customers predicted to churn moving? Immediately
Accuracy Is the model still ranking customers well? Only once labels arrive, often weeks later

The first two are cheap and fast but indirect; the third is what you care about but arrives late. How fast you need to know is a product question; Google’s Rules of Machine Learning (Rule #8) puts it as “Know the freshness requirements of your system. How much does performance degrade if you have a model that is a day old? A week old? A quarter old?”

The experiment

The script simulates three weeks of new customers: a normal week; a week where customers open more support tickets (an input drift); and a week where tickets stop predicting churn (a concept drift: the relationship the model learned has changed). Save it as monitor.py:

# Watch inputs, outputs and (when labels arrive) accuracy, for three simulated production weeks.
import joblib
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
from sklearn.metrics import roc_auc_score

model = joblib.load("churn-2026-11-30.1.joblib")
train = pd.read_csv("customers.csv")
NUMERIC = ["tenure_months", "support_tickets", "monthly_spend"]
rng = np.random.default_rng(1)


def week(n=500, extra_tickets=0.0, ticket_effect=0.45):
    """A week of new customers. extra_tickets shifts an input; ticket_effect changes how tickets relate to churn."""
    plan = rng.choice(["basic", "pro", "team"], size=n, p=[0.5, 0.35, 0.15])
    tenure = rng.integers(1, 60, size=n)
    tickets = rng.poisson(1.5 + extra_tickets, size=n)
    spend = np.round(np.select([plan == "basic", plan == "pro"], [19, 49], 99) * rng.uniform(0.8, 1.2, n), 2)
    logit = -1.0 + ticket_effect * tickets - 0.05 * tenure + np.where(plan == "basic", 0.8, 0.0)
    churned = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    return pd.DataFrame({"plan": plan, "tenure_months": tenure, "support_tickets": tickets,
                         "monthly_spend": spend, "churned": churned})


# 1. Calibrate the alarm: how large does the KS statistic get for a week drawn from the training data itself?
null = [max(ks_2samp(train[c].dropna(), train.sample(500, random_state=i)[c].dropna()).statistic for c in NUMERIC)
        for i in range(200)]
alarm = np.quantile(null, 0.99)
print(f"input alarm: largest KS statistic above {alarm:.3f} (99th percentile of 200 no-change weeks)\n")

# The same for accuracy: how low does ROC AUC fall on normal weeks, just from chance?
auc_null = [roc_auc_score(w["churned"], model.predict_proba(w)[:, 1]) for w in (week() for _ in range(200))]
auc_alarm = np.quantile(auc_null, 0.01)
print(f"accuracy alarm: ROC AUC below {auc_alarm:.3f} (1st percentile of 200 normal weeks)\n")

base_rate = model.predict_proba(train)[:, 1].mean()
weeks = {"normal week": week(), "more tickets (input drift)": week(extra_tickets=1.0),
         "tickets matter less (concept drift)": week(ticket_effect=0.0)}
for name, w in weeks.items():
    ks = {c: ks_2samp(train[c].dropna(), w[c].dropna()).statistic for c in NUMERIC}
    worst = max(ks, key=ks.get)
    p = model.predict_proba(w)[:, 1]
    auc = roc_auc_score(w["churned"], p)
    flag = "ALERT" if ks[worst] > alarm else "ok"
    acc = "ALERT" if auc < auc_alarm else "ok"
    print(f"{name}\n  inputs:  {flag:5} largest shift {worst} (KS {ks[worst]:.3f})"
          f"\n  outputs: mean predicted churn {p.mean():.1%} (training {base_rate:.1%})"
          f"\n  labels:  {acc:5} ROC AUC {auc:.3f}\n")

Running it prints:

input alarm: largest KS statistic above 0.063 (99th percentile of 200 no-change weeks)

accuracy alarm: ROC AUC below 0.710 (1st percentile of 200 normal weeks)

normal week
  inputs:  ok    largest shift tenure_months (KS 0.031)
  outputs: mean predicted churn 24.0% (training 23.7%)
  labels:  ok    ROC AUC 0.757

more tickets (input drift)
  inputs:  ALERT largest shift support_tickets (KS 0.295)
  outputs: mean predicted churn 31.4% (training 23.7%)
  labels:  ok    ROC AUC 0.780

tickets matter less (concept drift)
  inputs:  ok    largest shift monthly_spend (KS 0.062)
  outputs: mean predicted churn 24.6% (training 23.7%)
  labels:  ALERT ROC AUC 0.681

What the results show

Calibrate alarms on your own data. The script measures how much each check moves on 200 weeks with no change at all, then sets the alarm at the 1% tail. That gives you a threshold with a known false-alarm rate, instead of a number copied from a blog. It also handles a technical wrinkle: the two-sample Kolmogorov-Smirnov test “compares the underlying continuous distributions” of two samples, and ticket counts aren’t continuous. Calibrating its statistic by simulation makes it usable for counts anyway.

Input drift was loud and harmless here. When customers opened more tickets, the input alarm fired (KS 0.295 against an alarm at 0.063) and predicted churn rose from 23.7% to 31.4%. But accuracy was fine, ROC AUC 0.780: the model’s learned relationship still held, so it correctly ranked the newly at-risk customers higher. An input alarm means look, not automatically retrain.

Concept drift was silent until labels arrived. When tickets stopped predicting churn, the inputs looked normal and predicted churn barely moved (24.6%). Only accuracy caught it: ROC AUC 0.681, below the alarm at 0.710. This is the case that hurts in practice, and the reason labels must keep flowing back into monitoring even when everything else looks fine.

A retraining rule to write down

Decide in advance, and put it in the model’s record from Module 4:

  1. Input or output alarm: investigate within a day. Find the cause (a real change in customers, or a broken upstream field?). Fix pipelines before touching the model.
  2. Accuracy alarm on labelled data: retrain on recent data, compare the new model with the current one on the same held-out recent weeks, and ship it only if it’s better.
  3. No alarms: retrain on a fixed schedule anyway (for example quarterly), so the model never drifts far from current data unnoticed.
  4. Every retrain: a new version number, a new record, the golden-record and API tests from Module 4, and a note of why it happened.

Project

Run the script with your own Module 2 pipeline. Add a fourth week that combines both drifts, and a check on monthly_spend missing more often than in training (a typical upstream bug). Then write your retraining rule in your model’s record file, with the alarm thresholds your calibration produced.

Next: Module 6: Reproducibility and Experiment Tracking, making every model reproducible from a single command.