Skip to content

44. ML in production basics — Mini-project

The churn model of the lesson has been in production for a month. The head of customer care asks one question every month: “Can we still trust the churn scores?” You build the script that answers it. It loads the model bundle, checks it, validates the new month’s customer records, scores them, measures feature drift and prediction drift, computes the live ROC-AUC once the churn labels are known and ends with a clear decision: keep the model, investigate or retrain. It writes the result as a JSON report that a dashboard or a chat bot can read.

One design choice makes the job robust: the bundle stores a reference profile, a compact summary of the training data (the decile edges and bin shares of each numeric feature, the category shares of each categorical feature and the score distribution). The monitoring job then needs only the bundle, not the training data, which may be large, private or deleted.

  • data/customers.csv: the 5,000 churn customers (data dictionary). The training rows come from the same split as the lesson (25% test, stratified, random_state=42).
  • The “new month” is simulated from the 1,250 test customers, as in Example 7 of the lesson: prices rise by 8%, logins fall by about a quarter and 40% of one-year contracts become month-to-month. Then 15 records are corrupted the way real feeds break: a capitalized plan, a negative charge and a missing region.
  • The true churn labels of the new month are the test labels. In real life they arrive a month later.
  • churn_model.py and app.py from the lesson’s snippet folder python/snippets/m44/. Copy them into your project folder. The job reuses their feature lists, pipeline and request model, so training, serving and monitoring share one definition.
  1. Train the pipeline and save a bundle models/churn_monitored.joblib with metadata: version, fixed training date, scikit-learn version, features, data hash, threshold, test ROC-AUC, training flag rate and the reference profile. Save a JSON sidecar with the bundle’s SHA-256 next to it.
  2. Before you unpickle the bundle, check its sidecar: refuse it (raise) when the scikit-learn version, the feature list or the file hash differs.
  3. Validate every new record with the lesson’s Customer model. Count the rejected records by field and error type. Score only the valid records.
  4. Compute the PSI of every feature against the stored profile, the PSI of the churn scores and the flag rate.
  5. Compute the live ROC-AUC on the valid records with their labels.
  6. Decide with explicit rules: retrain when the live ROC-AUC is more than 0.03 below the test ROC-AUC; investigate when any PSI is above 0.1, the flag rate changes by more than 25% (relative) or more than 1% of records are rejected; keep otherwise. List every reason. These thresholds are choices; justify yours.
  7. Write the report to output/health_report.json and print a short summary.
  8. No warnings and no absolute paths in the output. Every random step uses seed 42.
  1. Write numeric_profile() and categorical_profile() that turn a training column into plain lists (JSON-friendly). Store them in the metadata.
  2. Write psi_from_profile() that bins new values with the stored edges, or counts the stored categories, and applies the PSI formula with a floor of 0.0001.
  3. Train, save and reload the bundle with the lesson’s save_bundle() and load_bundle(), which check the sidecar before unpickling.
  4. Build the new month, corrupt 15 records and validate them.
  5. Score, measure drift and performance.
  6. Apply the decision rules, write the JSON report and print the summary.
Criterion Excellent Acceptable Needs work
Bundle Pipeline, metadata and profile in one file, plus a sidecar with its hash; version, features and hash checked before unpickling Metadata saved and checked, but only after unpickling Pipeline only
Validation Every record validated with the shared request model; rejections counted by field and type Validation with hand-written checks Bad records crash the job or are scored
Drift PSI for every feature and the scores from the stored profile; categorical features handled Numeric features only, or bins from the new data No drift measure
Performance Live ROC-AUC compared with the training metric ROC-AUC without comparison None
Decision Explicit thresholds, every reason listed, one clear status A status without reasons No decision
Reproducibility Seeds, fixed dates, data hash; same report on every run Mostly fixed Output changes between runs
  • Add the KS test for each numeric feature. Store a sample of 1,000 training values in the profile for it, and discuss the trade-off between profile size and test power.
  • Run the job twice: once on an unchanged copy of the test rows and once on the drifted month. Check that the unchanged month gives the status keep.
  • Expose the report through a FastAPI endpoint GET /health/model and test it with TestClient.
  • Log each monthly report to MLflow as a run, with the PSI values as metrics, so that you can plot the drift over months.
Reference solution

Step 1 — Profiles of the training data. Plain lists, so the profile also fits into JSON.

import json
from pathlib import Path
import numpy as np
import pandas as pd
import sklearn
from pydantic import ValidationError
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from app import Customer
from churn_model import (
CATEGORICAL, FEATURES, NUMERIC, TARGET, build_pipeline, file_sha256, load_bundle,
save_bundle,
)
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
SEED = 42
DATA = Path("data/customers.csv")
BUNDLE = Path("models/churn_monitored.joblib")
FLOOR = 1e-4
def numeric_profile(values: pd.Series, bins: int = 10) -> dict[str, list[float]]:
ref = values.dropna().to_numpy(dtype=float)
edges = np.unique(np.quantile(ref, np.linspace(0, 1, bins + 1))[1:-1])
counts = np.bincount(np.searchsorted(edges, ref, side="right"),
minlength=len(edges) + 1)
return {"edges": edges.tolist(), "shares": (counts / len(ref)).tolist()}
def categorical_profile(values: pd.Series) -> dict[str, list]:
shares = values.value_counts(normalize=True).sort_index()
return {"categories": shares.index.tolist(), "shares": shares.tolist()}
demo = numeric_profile(pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), bins=4)
print(demo)
print(categorical_profile(pd.Series(["a", "b", "b", "c"])))
Output
{'edges': [3.25, 5.5, 7.75], 'shares': [0.3, 0.2, 0.2, 0.3]}
{'categories': ['a', 'b', 'c'], 'shares': [0.25, 0.5, 0.25]}

The edges are the inner quantiles; the outer bins are open, so new values outside the training range still land in a bin. The shares of each profile sum to 1.

Step 2 — PSI from a stored profile.

def psi_from_profile(profile: dict, current: pd.Series) -> float:
if "edges" in profile:
cur = current.dropna().to_numpy(dtype=float)
counts = np.bincount(np.searchsorted(profile["edges"], cur, side="right"),
minlength=len(profile["shares"]))
cur_share = counts / len(cur)
else:
shares = current.value_counts(normalize=True)
cur_share = shares.reindex(profile["categories"], fill_value=0).to_numpy()
ref = np.clip(np.asarray(profile["shares"]), FLOOR, None)
cur = np.clip(cur_share, FLOOR, None)
return float(np.sum((cur - ref) * np.log(cur / ref)))
same = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(round(psi_from_profile(demo, same), 6))
print(round(psi_from_profile(demo, same + 5), 3))
Output
0.0
4.411

The same data gives a PSI of 0; data shifted by half its range gives a large PSI. A category that the training data never had is not in profile["categories"], so it adds nothing here; the request model rejects it before scoring anyway.

Step 3 — Train, save and reload the bundle.

customers = pd.read_csv(DATA)
X_train, X_test, y_train, y_test = train_test_split(
customers[FEATURES], customers[TARGET], test_size=0.25,
stratify=customers[TARGET], random_state=SEED,
)
pipeline = build_pipeline().fit(X_train, y_train)
train_scores = pd.Series(pipeline.predict_proba(X_train)[:, 1])
test_auc = roc_auc_score(y_test, pipeline.predict_proba(X_test)[:, 1])
profile = {c: numeric_profile(X_train[c]) for c in NUMERIC}
profile |= {c: categorical_profile(X_train[c]) for c in CATEGORICAL}
profile["churn_score"] = numeric_profile(train_scores)
metadata = {
"model_version": "1.0.0",
"trained_at": "2025-01-06",
"sklearn_version": sklearn.__version__,
"features": FEATURES,
"data_sha256": file_sha256(DATA),
"threshold": 0.35,
"test_roc_auc": round(float(test_auc), 4),
"flag_rate": round(float((train_scores >= 0.35).mean()), 4),
"profile": profile,
}
save_bundle(pipeline, metadata, BUNDLE) # also writes churn_monitored.json
bundle = load_bundle(BUNDLE) # checks the sidecar first, then unpickles
meta = bundle["metadata"]
print(meta["model_version"], meta["test_roc_auc"], meta["flag_rate"])
profile_json = json.dumps(meta["profile"])
print(f"profile: {len(meta['profile'])} entries, {len(profile_json)} chars")
Output
1.0.0 0.8131 0.1893
profile: 13 entries, 2765 chars

save_bundle() from the lesson writes the bundle and its sidecar models/churn_monitored.json; load_bundle() checks the version, the features and the hash before it unpickles. The whole profile is under 3,000 characters of JSON: 13 entries (12 features and the score), small enough to keep inside the bundle and to print in a log.

Step 4 — Build, corrupt and validate the new month.

rng = np.random.default_rng(SEED)
new_month = X_test.copy()
new_month["monthly_charges"] = (new_month["monthly_charges"] * 1.08).round(2)
new_month["logins_last_30d"] = rng.binomial(new_month["logins_last_30d"], 0.75)
switch = (new_month["contract"] == "one-year") & (rng.random(len(new_month)) < 0.4)
new_month.loc[switch, "contract"] = "month-to-month"
records = new_month.astype(object).where(new_month.notna(), None).to_dict("records")
for i, row in enumerate(rng.choice(len(records), size=15, replace=False)):
if i % 3 == 0:
records[row]["plan"] = "Premium"
elif i % 3 == 1:
records[row]["monthly_charges"] = -records[row]["monthly_charges"]
else:
records[row]["region"] = None
valid_rows, valid_index, rejected = [], [], []
for i, record in enumerate(records):
try:
valid_rows.append(Customer.model_validate(record).model_dump())
valid_index.append(i)
except ValidationError as exc:
first = exc.errors()[0]
rejected.append({"field": first["loc"][0], "type": first["type"]})
rejected_counts = pd.DataFrame(rejected).value_counts().sort_index()
print(f"{len(valid_rows)} valid, {len(rejected)} rejected")
print(rejected_counts)
Output
1235 valid, 15 rejected
field type
monthly_charges greater_than 5
plan literal_error 5
region literal_error 5
Name: count, dtype: int64

Each corruption is caught by the same request model that guards the API: "Premium" and a missing region fail the Literal checks, a negative charge fails gt=0. The job keeps going and counts the problems.

Step 5 — Score, drift and live performance.

current = pd.DataFrame(valid_rows, columns=FEATURES)
current["has_autopay"] = current["has_autopay"].astype(int)
scores = pd.Series(pipeline.predict_proba(current)[:, 1])
labels = y_test.to_numpy()[valid_index]
drift = pd.Series(
{c: psi_from_profile(meta["profile"][c], current[c]) for c in FEATURES}
)
drift["churn_score"] = psi_from_profile(meta["profile"]["churn_score"], scores)
flag_rate = float((scores >= meta["threshold"]).mean())
live_auc = roc_auc_score(labels, scores)
print(drift.sort_values(ascending=False).round(3).head(5))
print(f"flag rate {meta['flag_rate']:.3f} -> {flag_rate:.3f}")
print(f"ROC-AUC {meta['test_roc_auc']:.3f} -> {live_auc:.3f}")
Output
monthly_charges 0.361
logins_last_30d 0.176
contract 0.068
churn_score 0.063
tenure_months 0.015
dtype: float64
flag rate 0.189 -> 0.253
ROC-AUC 0.813 -> 0.809

The drifts of the lesson appear again, now measured against the stored profile instead of the training data: a major shift in charges, a moderate one in logins. The flag rate rises from 18.9% to 25.3%. The live ROC-AUC, computed once the labels arrived, falls only from 0.813 to 0.809: the model still ranks customers well. The drift moved the scores up more than it scrambled their order.

Step 6 — Decide, report and summarize.

reject_rate = len(rejected) / len(records)
reasons = []
status = "keep"
auc_drop = meta["test_roc_auc"] - live_auc
flag_change = flag_rate / meta["flag_rate"] - 1
if auc_drop > 0.03:
reasons.append(f"ROC-AUC dropped by {auc_drop:.3f}")
status = "retrain"
for level, low, high in [("major", 0.25, np.inf), ("moderate", 0.1, 0.25)]:
hit = drift[(drift > low) & (drift <= high)]
if len(hit):
reasons.append(f"{level} drift: {', '.join(hit.index)}")
if abs(flag_change) > 0.25:
reasons.append(f"flag rate changed by {flag_change:+.0%}")
if reject_rate > 0.01:
reasons.append(f"{reject_rate:.1%} of records rejected")
if status == "keep" and reasons:
status = "investigate"
report = {
"model_version": meta["model_version"],
"status": status,
"reasons": reasons,
"records": len(records),
"rejected": {f"{f}/{t}": int(n) for (f, t), n in rejected_counts.items()},
"psi": drift.round(4).to_dict(),
"flag_rate": round(flag_rate, 4),
"live_roc_auc": round(float(live_auc), 4),
}
Path("output").mkdir(exist_ok=True)
Path("output/health_report.json").write_text(json.dumps(report, indent=2))
print(f"model {report['model_version']}: {status.upper()}")
for reason in reasons:
print(" -", reason)
saved = json.loads(Path("output/health_report.json").read_text())
assert saved["status"] == status and len(saved["psi"]) == 13
Output
model 1.0.0: INVESTIGATE
- major drift: monthly_charges
- moderate drift: logins_last_30d
- flag rate changed by +34%
- 1.2% of records rejected

The status is investigate, with every reason listed. The inputs moved a lot, but the live ROC-AUC fell by only 0.004: the model still ranks customers well, so retraining is not yet justified. The real questions are for people. Should the threshold of 0.35 stay, now that it flags about a third more customers? And who fixes the feed? The rules retrain only when performance drops, as the lesson advises: drift is a reason to look, not a reason to retrain. The report holds everything a reader needs: the counts, every PSI, the flag rate and the live score. A dashboard reads the JSON file; a person reads the summary. Fix the data feed that sends a capitalized plan and missing regions first: retraining cannot repair broken input.