Skip to content

MLDay 50 of 50ML in Production

Project 5

Ship and Monitor the Credit Model

12 min read

The Day 28 credit model scores a test PR-AUC of 0.551 on a laptop. That helps no one yet. The bank's app can't ask it about a client, nobody else can rebuild it, and nobody would notice if it started to fail.

The idea

A model is production-ready when it passes four tests:

  1. Reproducible. The same code, settings and data give the same model, and every training run is logged (Day 44).
  2. Served. Other programs can ask it for a prediction over HTTP, and bad requests are refused (Day 46).
  3. Monitored. A drift check compares new inputs and new scores with the training data (Day 47).
  4. Documented. A model card says what the model is for, how good it is and where it can fail (Day 48).

This project builds each piece for the Day 28 model, in six small files in one folder. Everything they write goes into an artifacts/ folder next to them.

The formula

The population stability index (PSI) measures how far one column of new data has moved from the training data. Cut the column into bins, then compare each bin's share of rows.

PSI=∑i(pi−qi)ln⁡piqi\text{PSI} = \sum_{i} (p_i - q_i) \ln\frac{p_i}{q_i}
Symbol Meaning
ii one bin, cut at the training data's deciles (fewer bins when values repeat)
pip_i the share of training rows in bin ii
qiq_i the share of new rows in bin ii
ln⁡\ln the natural log

Worked: in the shifted batch below, the share of clients one month late (PAY_0 = 1) grows from 0.125 in training to 0.370. That bin alone adds (0.125−0.370)ln⁡0.1250.370=(−0.245)(−1.085)≈0.27(0.125 - 0.370) \ln\frac{0.125}{0.370} = (-0.245)(-1.085) \approx 0.27. A common rule of thumb: under 0.1 is stable, 0.1 to 0.2 is worth watching, 0.2 or more raises an alert (Day 47's rule).

In code

The six files run in this order and take under a minute in all.

Step 1: the shared module. The Day 28 split and cleaning live in features.py, which training and serving both import. This matters: joblib saves a reference to features.clean, not its code, so the server must be able to import the same file.

# script_id: day_050_project_ship_and_monitor/features
import os
from pathlib import Path

import pandas as pd
from sklearn.model_selection import train_test_split

CSV = Path(os.environ.get("ML_DATA", "datasets")) / "credit_default" / "default_of_credit_card_clients.csv"
OUT = Path(os.environ.get("ML_MODEL_DIR", Path(__file__).parent / "artifacts"))   # every file we write
PAY = ["PAY_0", "PAY_2", "PAY_3", "PAY_4", "PAY_5", "PAY_6"]


def load_split():
    df = pd.read_csv(CSV).drop(columns="ID").rename(columns={"default payment next month": "default"})
    X, y = df.drop(columns="default"), df["default"]
    return train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)


def clean(X):
    X = X.copy()
    X["EDUCATION"] = X["EDUCATION"].replace({0: 4, 5: 4, 6: 4})   # unknown codes -> 4, "others"
    X["MARRIAGE"] = X["MARRIAGE"].replace({0: 3})                  # unknown code -> 3, "others"
    return X.astype(float)

Step 2: train twice, and track both runs. train.py logs each run to a local MLflow store (a SQLite file): its settings, a hash of the data file, its test scores and the saved pipeline.

# script_id: day_050_project_ship_and_monitor/train
import hashlib
import os

import joblib

os.environ.setdefault("MLFLOW_DISABLE_AGENT_HINT", "1")  # silence an install hint
import mlflow  # noqa: E402
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer

from features import CSV, OUT, clean, load_split

CONFIG = {"split_seed": 42, "test_size": 0.2, "model": "HistGradientBoostingClassifier", "model_seed": 42}
OUT.mkdir(parents=True, exist_ok=True)
mlflow.set_tracking_uri(f"sqlite:///{OUT / 'mlflow.db'}")
if mlflow.get_experiment_by_name("credit-default") is None:
    mlflow.create_experiment("credit-default", artifact_location=(OUT / "mlartifacts").as_uri())
mlflow.set_experiment("credit-default")

X_train, X_test, y_train, y_test = load_split()
data_hash = hashlib.sha256(CSV.read_bytes()).hexdigest()[:12]
for attempt in [1, 2]:                                      # same inputs twice: same model?
    with mlflow.start_run(run_name=f"train-{attempt}"):
        model = make_pipeline(FunctionTransformer(clean), HistGradientBoostingClassifier(random_state=42))
        p = model.fit(X_train, y_train).predict_proba(X_test)[:, 1]
        mlflow.log_params(CONFIG | {"data_sha256": data_hash})
        mlflow.log_metrics({"test_pr_auc": average_precision_score(y_test, p),
                            "test_roc_auc": roc_auc_score(y_test, p), "trees": model[-1].n_iter_})
        joblib.dump(model, OUT / "model.joblib")            # the whole pipeline: cleaning + model
        mlflow.log_artifact(str(OUT / "model.joblib"))

runs = mlflow.search_runs(experiment_names=["credit-default"], max_results=2, order_by=["start_time DESC"])
cols = {"tags.mlflow.runName": "run", "params.data_sha256": "data hash", "metrics.test_pr_auc": "PR-AUC",
        "metrics.test_roc_auc": "ROC AUC", "metrics.trees": "trees"}
print(runs[list(cols)].rename(columns=cols).round(4).to_string(index=False))
    run    data hash  PR-AUC  ROC AUC  trees
train-2 4edce6da569b  0.5507   0.7808   65.0
train-1 4edce6da569b  0.5507   0.7808   65.0

Both runs match to four decimals, and match Day 28: PR-AUC 0.551, ROC AUC 0.781, 65 trees.

Step 3: the API. api.py loads the pipeline once at startup (FastAPI's lifespan). It checks every request with a Pydantic model: one rule per input column. create_model builds it, so the 23 rules fit in a few lines. A request that breaks a rule gets an HTTP 422 error instead of a guess.

# script_id: day_050_project_ship_and_monitor/api
from contextlib import asynccontextmanager

import joblib
import pandas as pd
from fastapi import FastAPI
from pydantic import ConfigDict, Field, create_model

from features import OUT, PAY

Client = create_model(                                      # fields in training order; extra fields refused
    "Client", __config__=ConfigDict(extra="forbid"),
    LIMIT_BAL=(float, Field(gt=0)), SEX=(int, Field(ge=1, le=2)), EDUCATION=(int, Field(ge=0, le=6)),
    MARRIAGE=(int, Field(ge=0, le=3)), AGE=(int, Field(ge=18, le=100)),
    **{c: (int, Field(ge=-2, le=9)) for c in PAY},
    **{f"BILL_AMT{i}": (float, ...) for i in range(1, 7)},  # can be negative: overpaid
    **{f"PAY_AMT{i}": (float, Field(ge=0)) for i in range(1, 7)},
)
model = {}


@asynccontextmanager
async def lifespan(app):
    model["v1"] = joblib.load(OUT / "model.joblib")   # our own file: never load a pickle you didn't make
    yield


app = FastAPI(lifespan=lifespan)


@app.post("/predict")
def predict(client: Client):
    row = pd.DataFrame([client.model_dump()])
    return {"default_probability": round(float(model["v1"].predict_proba(row)[0, 1]), 3)}

Step 4: call it and time it (p50 and p95, Day 46). FastAPI's TestClient calls the app in-process, with no server to start. check_api.py checks that the API gives the same answer as the pipeline, sends one bad request, then times 200 calls.

# script_id: day_050_project_ship_and_monitor/check_api
import json
import time

import joblib
import numpy as np
from fastapi.testclient import TestClient

from api import app
from features import OUT, load_split

_, X_test, _, _ = load_split()
rows = X_test.head(200).to_dict(orient="records")           # 200 test clients as JSON
print("pipeline:", round(float(joblib.load(OUT / "model.joblib").predict_proba(X_test.head(1))[0, 1]), 3))
with TestClient(app) as client:                             # "with" runs the lifespan: the model loads once
    print("API:     ", client.post("/predict", json=rows[0]).json())
    bad = client.post("/predict", json=rows[0] | {"AGE": -5})
    print("AGE = -5:", bad.status_code, bad.json()["detail"][0]["msg"])
    ms = []
    for row in rows:
        start = time.perf_counter()
        client.post("/predict", json=row)
        ms.append(1000 * (time.perf_counter() - start))
p50, p95 = np.percentile(ms, [50, 95], method="inverted_cdf")   # nearest rank, as in Day 46
print(f"{len(ms)} calls: p50 {p50:.1f} ms, p95 {p95:.1f} ms")
(OUT / "api_check.json").write_text(json.dumps({"bad_status": bad.status_code, "p95_ms": p95}))
pipeline: 0.113
API:      {'default_probability': 0.113}
AGE = -5: 422 Input should be greater than or equal to 18
200 calls: p50 11.2 ms, p95 18.8 ms

Same answer both ways, so serving uses exactly the trained cleaning. Your timings will differ, from run to run too.

Step 5: watch for drift. monitor.py compares two batches of 2,000 test clients with the training rows. The fresh batch is as it is. The shifted batch simulates a downturn: 40% of clients slip a month (those paying on time become one month late, the rest one month later), and every credit limit is cut by 30%. It checks every input column and the model's scores.

# script_id: day_050_project_ship_and_monitor/monitor
import json

import joblib
import numpy as np
import pandas as pd

from features import OUT, load_split


def psi(ref, new, bins=10):
    cuts = np.unique(np.quantile(ref, np.linspace(0, 1, bins + 1)))[1:-1]   # bin edges from training data
    p = np.bincount(np.searchsorted(cuts, ref, side="right"), minlength=len(cuts) + 1) / len(ref)
    q = np.bincount(np.searchsorted(cuts, new, side="right"), minlength=len(cuts) + 1) / len(new)
    p, q = np.clip(p, 1e-4, None), np.clip(q, 1e-4, None)                    # avoid log(0)
    return float(np.sum((p - q) * np.log(p / q)))


X_train, X_test, _, _ = load_split()
model = joblib.load(OUT / "model.joblib")
fresh = X_test.sample(2000, random_state=42)                 # new clients from the same world
shifted = fresh.copy()                                       # a downturn, simulated:
behind = np.random.default_rng(42).random(len(shifted)) < 0.4
shifted.loc[behind, "PAY_0"] = (shifted.loc[behind, "PAY_0"].clip(lower=0) + 1).clip(upper=8)  # 40% slip a month
shifted["LIMIT_BAL"] = shifted["LIMIT_BAL"] * 0.7             # every limit cut by 30%

train_scores = model.predict_proba(X_train)[:, 1]
psis = pd.DataFrame({
    name: {c: psi(X_train[c], batch[c]) for c in X_train.columns}
    | {"model score": psi(train_scores, model.predict_proba(batch)[:, 1])}
    for name, batch in [("fresh", fresh), ("shifted", shifted)]})
print(psis.sort_values("shifted", ascending=False).head(4).round(3).to_string())
worst = psis.max()
status = np.select([worst >= 0.2, worst > 0.1], ["ALERT: investigate, retrain", "watch"], "ok")
print(pd.DataFrame({"worst PSI": worst.round(3), "status": status}).to_string())
(OUT / "drift.json").write_text(json.dumps(worst.round(3).to_dict()))
             fresh  shifted
LIMIT_BAL    0.003    0.521
PAY_0        0.003    0.421
model score  0.006    0.161
PAY_AMT1     0.007    0.007
         worst PSI                       status
fresh        0.007                           ok
shifted      0.521  ALERT: investigate, retrain

The fresh batch stays under 0.01 everywhere. The shifted batch trips the alarm on the two columns that moved, and nowhere else. Its scores moved less (0.161) than its inputs did, so a score check alone would only say "watch". Real labels arrive a month later, when clients pay or don't, so input and score drift are the early warning.

Step 6: the model card and the checklist. report.py writes the model card from the tracked run, so its numbers can't drift from the logged ones. Then it ticks the four tests from the saved results.

# script_id: day_050_project_ship_and_monitor/report
import json
import os

import joblib

os.environ.setdefault("MLFLOW_DISABLE_AGENT_HINT", "1")  # silence an install hint
import mlflow  # noqa: E402
from sklearn.metrics import average_precision_score

from features import OUT, load_split

mlflow.set_tracking_uri(f"sqlite:///{OUT / 'mlflow.db'}")
runs = mlflow.search_runs(experiment_names=["credit-default"], max_results=2, order_by=["start_time DESC"])
run = runs.iloc[0]
api, drift = (json.loads((OUT / name).read_text()) for name in ["api_check.json", "drift.json"])
_, X_test, _, y_test = load_split()
scores = joblib.load(OUT / "model.joblib").predict_proba(X_test)[:, 1]
by_sex = [average_precision_score(y_test[X_test["SEX"] == s], scores[X_test["SEX"] == s]) for s in [1, 2]]

card = f"""# Model card: credit default v1
- Use: rank card clients by their risk of missing next month's payment, so staff call the riskiest first.
  Not for refusing credit automatically.
- Data: UCI Default of Credit Card Clients (Taiwan), 24,000 training rows, file hash {run['params.data_sha256']}.
- Model: Day 28 cleaning + HistGradientBoostingClassifier(random_state=42), {run['metrics.trees']:.0f} trees.
- Test, 6,000 clients: PR-AUC {run['metrics.test_pr_auc']:.3f} (random ranking 0.221), ROC AUC {run['metrics.test_roc_auc']:.3f}.
- PR-AUC by SEX code: {by_sex[0]:.3f} (1) and {by_sex[1]:.3f} (2).
- Limits: one country; some category codes are undocumented; investigate when any PSI reaches 0.2."""
(OUT / "model_card.md").write_text(card)
print(card + "\n")

checks = {
    "reproducible: two runs, identical PR-AUC": runs["metrics.test_pr_auc"].nunique() == 1,
    "served: a bad request gets a 422": api["bad_status"] == 422,
    "fast: p95 latency under 100 ms": api["p95_ms"] < 100,
    "monitored: fresh batch ok, shifted batch alerts": drift["fresh"] < 0.1 and drift["shifted"] >= 0.2,
    "documented: model card saved": (OUT / "model_card.md").exists(),
}
for name, ok in checks.items():
    print("[x]" if ok else "[ ]", name)
# Model card: credit default v1
- Use: rank card clients by their risk of missing next month's payment, so staff call the riskiest first.
  Not for refusing credit automatically.
- Data: UCI Default of Credit Card Clients (Taiwan), 24,000 training rows, file hash 4edce6da569b.
- Model: Day 28 cleaning + HistGradientBoostingClassifier(random_state=42), 65 trees.
- Test, 6,000 clients: PR-AUC 0.551 (random ranking 0.221), ROC AUC 0.781.
- PR-AUC by SEX code: 0.542 (1) and 0.559 (2).
- Limits: one country; some category codes are undocumented; investigate when any PSI reaches 0.2.

[x] reproducible: two runs, identical PR-AUC
[x] served: a bad request gets a 422
[x] fast: p95 latency under 100 ms
[x] monitored: fresh batch ok, shifted batch alerts
[x] documented: model card saved

The 100 ms budget is this project's choice; a real team agrees one with the app's owners. Before you ship any model, make sure you can tick each one:

  • Reproducible: one command retrains it, and the run, its settings and its data hash are logged.
  • Served: the whole pipeline sits behind an API that refuses bad input.
  • Fast enough: p95 latency is inside the agreed budget.
  • Monitored: inputs and scores are checked for drift, with a threshold that triggers action.
  • Documented: a model card states its use, its scores, how it does for each group, and its limits.

Quick check

Quick check

1. Both training runs logged the same data hash and PR-AUC 0.5507. What does that show?

2. In the shifted batch, LIMIT_BAL has PSI 0.52 but the model's scores only 0.16. What should the team do?

3. 200 calls give p50 11.2 ms and p95 18.8 ms. What does the p95 tell you?

Next

That's the course: for your next model, sketch the system as in Day 49, then ship it with this checklist.

Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).

← Previous: Day 49 · Design an ML System
Not tapped yet