Skip to content

44. ML in production basics — Exercises

These exercises practice every idea of the ML in production lesson. They use the churn customers, house sales and daily sales of the course data. The data dictionary describes every column.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block below into the top of a script (for example exercise.py). Then copy the starter code under it and replace each to-do comment with your code.
  3. Run the script with python exercise.py from your project folder, the folder that holds data/. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code: they prove that the numbers are right, not only that they look right.

Every exercise starts with this block. It loads the churn data and defines four helpers from the lesson: the feature lists, the churn pipeline, the psi() function and the Customer request model.

import hashlib
import json
import zlib
from pathlib import Path
from typing import Literal
import numpy as np
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
CATEGORICAL = ["region", "plan", "contract", "payment_method"]
NUMERIC = ["age", "has_autopay", "tenure_months", "monthly_charges", "total_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes"]
FEATURES = CATEGORICAL + NUMERIC
def build_churn_pipeline(C: float = 1.0) -> Pipeline:
preprocess = ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
NUMERIC),
])
return Pipeline([("prep", preprocess),
("model", LogisticRegression(C=C, max_iter=1000))])
def psi(reference: pd.Series, current: pd.Series, bins: int = 10) -> float:
"""Population stability index of current against reference (decile bins)."""
ref = reference.dropna().to_numpy(dtype=float)
cur = current.dropna().to_numpy(dtype=float)
inner_edges = np.unique(np.quantile(ref, np.linspace(0, 1, bins + 1))[1:-1])
n_bins = len(inner_edges) + 1
ref_share = np.bincount(np.searchsorted(inner_edges, ref, side="right"),
minlength=n_bins) / len(ref)
cur_share = np.bincount(np.searchsorted(inner_edges, cur, side="right"),
minlength=n_bins) / len(cur)
ref_share = np.clip(ref_share, 1e-4, None)
cur_share = np.clip(cur_share, 1e-4, None)
return float(np.sum((cur_share - ref_share) * np.log(cur_share / ref_share)))
PaymentMethod = Literal["electronic_check", "credit_card", "bank_transfer", "paypal"]
class Customer(BaseModel):
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
age: int = Field(ge=18, le=100)
region: Literal["East", "North", "South", "West"]
plan: Literal["basic", "standard", "premium"]
contract: Literal["month-to-month", "one-year", "two-year"]
payment_method: PaymentMethod
has_autopay: bool
tenure_months: int = Field(ge=0, le=120)
monthly_charges: float = Field(gt=0, le=1000)
total_charges: float | None = Field(default=None, ge=0, le=120_000)
support_tickets: int = Field(ge=0, le=100)
logins_last_30d: int = Field(ge=0, le=1000)
avg_session_minutes: float = Field(ge=0, le=1440)
Warm-up

Build a dictionary versions that maps the distribution names numpy, pandas, scikit-learn and scipy to their installed versions, with importlib.metadata.version(). Print it as JSON with sorted keys and an indent of 2. This dictionary goes into every model’s metadata.

Expected output
{
"numpy": "2.5.4",
"pandas": "3.1.1",
"scikit-learn": "1.9.1",
"scipy": "1.18.1"
}
Starter
from importlib.metadata import version
names = ["numpy", "pandas", "scikit-learn", "scipy"]
# TODO: build versions = {name: installed version}
# TODO: print it with json.dumps(..., indent=2, sort_keys=True)
Hint 1

A dictionary comprehension: {name: version(name) for name in names}.

Hint 2

version() takes the name you use with pip install (scikit-learn), not the import name (sklearn).

Solution
from importlib.metadata import version
import scipy
import sklearn
names = ["numpy", "pandas", "scikit-learn", "scipy"]
versions = {name: version(name) for name in names}
print(json.dumps(versions, indent=2, sort_keys=True))
assert versions["pandas"] == pd.__version__
assert versions["scikit-learn"] == sklearn.__version__
assert versions["scipy"] == scipy.__version__
Output
{
"numpy": "2.5.4",
"pandas": "3.1.1",
"scikit-learn": "1.9.1",
"scipy": "1.18.1"
}

How it works:

  1. importlib.metadata.version() reads the version from the installed package’s metadata, without importing the package.
  2. json.dumps(..., sort_keys=True) gives the same text for the same versions, whatever the order of the list. Stable text is easy to compare and to hash.
  3. The asserts check that the metadata agrees with each library’s own __version__.

Alternative: read module.__version__ after importing each library. It works for these four, but not every package has a __version__ attribute, and you must know the import name.

Warm-up

Compute the SHA-256 hash of data/stores.csv in two ways: read all bytes at once, and read the file in chunks of 1,024 bytes with hashlib.sha256().update(). Print the first 16 hex characters of each, the length of the full hex digest and whether both are equal.

Expected output
0ca4294e9a1ab317 0ca4294e9a1ab317
64 True
Starter
path = Path("data/stores.csv")
# TODO: hash all bytes at once with hashlib.sha256(...).hexdigest()
# TODO: hash in chunks: digest = hashlib.sha256(); update() per chunk
# TODO: print both prefixes, the length and the comparison
Hint 1

hashlib.sha256(path.read_bytes()).hexdigest() gives the one-shot hash.

Hint 2

Open the file with path.open("rb") and loop with while chunk := f.read(1024):.

Solution
path = Path("data/stores.csv")
one_shot = hashlib.sha256(path.read_bytes()).hexdigest()
digest = hashlib.sha256()
with path.open("rb") as f:
while chunk := f.read(1024):
digest.update(chunk)
chunked = digest.hexdigest()
print(one_shot[:16], chunked[:16])
print(len(chunked), one_shot == chunked)
assert one_shot == chunked
assert len(chunked) == 64
Output
0ca4294e9a1ab317 0ca4294e9a1ab317
64 True

How it works:

  1. SHA-256 produces 256 bits, written as 64 hexadecimal characters (4 bits each).
  2. update() feeds the hash piece by piece. The result depends only on the bytes, not on how you cut them, so both ways agree.
  3. Chunked reading keeps memory use small, so the same function works for a 50 GB file.

Alternative: Python 3.11+ has hashlib.file_digest(f, "sha256"), which does the chunked loop for you.

M44-W03 · Predict the output: seeded generators

Section titled “M44-W03 · Predict the output: seeded generators”
Warm-up

Predict the output: the code draws three integers several times. Write down the four True/False values before you run it.

Acceptance criteria:

  • Write your prediction for all four lines.
  • Run the code. Your prediction matches the Output in the solution.
  • Explain why the last line differs from the first.
Starter
a = np.random.default_rng(42).integers(0, 100, size=3)
b = np.random.default_rng(42).integers(0, 100, size=3)
c = np.random.default_rng(7).integers(0, 100, size=3)
rng = np.random.default_rng(42)
first = rng.integers(0, 100, size=3)
second = rng.integers(0, 100, size=3)
print(np.array_equal(a, b))
print(np.array_equal(a, c))
print(np.array_equal(a, first))
print(np.array_equal(first, second))
Hint 1

A new generator with the same seed starts at the same place in the same sequence.

Hint 2

One generator moves forward after each draw. Its second draw continues the sequence; it does not restart.

Solution
a = np.random.default_rng(42).integers(0, 100, size=3)
b = np.random.default_rng(42).integers(0, 100, size=3)
c = np.random.default_rng(7).integers(0, 100, size=3)
rng = np.random.default_rng(42)
first = rng.integers(0, 100, size=3)
second = rng.integers(0, 100, size=3)
print(np.array_equal(a, b))
print(np.array_equal(a, c))
print(np.array_equal(a, first))
print(np.array_equal(first, second))
assert np.array_equal(a, b) and np.array_equal(a, first)
assert not np.array_equal(first, second)
Output
True
False
True
False

How it works:

  1. a, b and first each come from a fresh generator with seed 42, so they are the same three numbers.
  2. Seed 7 starts another sequence, so c differs.
  3. second is the next part of the sequence of rng, so it differs from first. This is why a training script creates its generator once, at the top, from one recorded seed: the whole run then follows one reproducible sequence.

M44-W04 · Assign stable buckets to customer ids

Section titled “M44-W04 · Assign stable buckets to customer ids”
Warm-up

Write bucket(customer_id, n_buckets=10) that returns zlib.crc32 of the UTF-8 encoded id modulo n_buckets. Print the buckets of C00001 to C00005. Then count how many of the 5,000 customers fall in each of the 10 buckets and print the smallest and the largest count.

Expected output
{'C00001': 7, 'C00002': 1, 'C00003': 3, 'C00004': 0, 'C00005': 8}
10 467 531
Starter
def bucket(customer_id: str, n_buckets: int = 10) -> int:
# TODO: crc32 of the encoded id, modulo n_buckets
...
# TODO: print the buckets of C00001..C00005
# TODO: count customers per bucket; print min and max
Hint 1

zlib.crc32("C00001".encode("utf-8")) returns a non-negative integer.

Hint 2

customers["customer_id"].map(bucket).value_counts() counts per bucket.

Solution
def bucket(customer_id: str, n_buckets: int = 10) -> int:
return zlib.crc32(customer_id.encode("utf-8")) % n_buckets
ids = [f"C{i:05d}" for i in range(1, 6)]
print({cid: bucket(cid) for cid in ids})
counts = customers["customer_id"].map(bucket).value_counts()
print(len(counts), counts.min(), counts.max())
assert all(bucket(cid) == bucket(cid) for cid in ids)
assert counts.sum() == 5000 and len(counts) == 10
Output
{'C00001': 7, 'C00002': 1, 'C00003': 3, 'C00004': 0, 'C00005': 8}
10 467 531

How it works:

  1. CRC32 depends only on the bytes, so a customer gets the same bucket on every machine and in every Python process.
  2. The modulo maps the 32-bit value to 0–9.
  3. The counts are close to 500 each: the hash spreads the ids evenly, like a random assignment, but a fixed one.

M44-W05 · Fix the bug: a split that changes every run

Section titled “M44-W05 · Fix the bug: a split that changes every run”
Warm-up

Fix the bug: a teammate wrote the function below. The test set changes every time they restart Python. Prove the problem by running hash("C00001") % 100 in three new Python processes with PYTHONHASHSEED set to 1, 2 and 3. Then rewrite is_test() with hashlib.sha256 (use the first 8 hex characters as a base-16 integer) and print the test share over all customers.

Buggy code
def is_test(customer_id: str) -> bool:
return hash(customer_id) % 100 < 20
Expected output
built-in hash differs between processes: True
test share 0.201
Starter
import os
import subprocess
import sys
code = "print(hash('C00001') % 100)"
# TODO: run code with sys.executable for PYTHONHASHSEED in "1", "2", "3"
# TODO: print whether the three results differ
# TODO: rewrite is_test with hashlib.sha256 and print the test share
Hint 1

subprocess.run([sys.executable, "-c", code], env=os.environ | {"PYTHONHASHSEED": seed}, capture_output=True, text=True).stdout gives the printed text.

Hint 2

int(hashlib.sha256(customer_id.encode()).hexdigest()[:8], 16) turns the first 32 bits of the digest into an integer.

Solution
import os
import subprocess
import sys
code = "print(hash('C00001') % 100)"
results = {
subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
env=os.environ | {"PYTHONHASHSEED": seed}).stdout.strip()
for seed in ["1", "2", "3"]
}
print("built-in hash differs between processes:", len(results) > 1)
def is_test(customer_id: str) -> bool:
digest = hashlib.sha256(customer_id.encode("utf-8")).hexdigest()
return int(digest[:8], 16) % 100 < 20
share = customers["customer_id"].map(is_test).mean()
print(f"test share {share:.3f}")
assert len(results) > 1
assert 0.18 < share < 0.22
Output
built-in hash differs between processes: True
test share 0.201

How it works:

  1. Python adds a random salt to the hash of every str and bytes value, chosen when the process starts. This protects web servers against attacks that flood a dictionary with colliding keys. PYTHONHASHSEED fixes the salt, which shows that the value depends on it.
  2. hashlib functions have no salt: the same bytes give the same digest everywhere.
  3. The first 8 hex characters are 32 bits, plenty for a bucket from 0 to 99.

Alternative: zlib.crc32 (exercise W04) is faster than SHA-256 and good enough for splitting.

M44-W06 · Field constraints for an order line

Section titled “M44-W06 · Field constraints for an order line”
Warm-up

Write a pydantic model OrderLine for one line of data/sales.csv: product_id matches P plus three digits, quantity is an integer from 1 to 50, unit_price is above 0 and discount is between 0 and 0.5 with a default of 0. Validate the four records in the starter. Print ok and the model for valid records, or the error types for invalid ones.

Expected output
ok product_id='P010' quantity=1 unit_price=69.99 discount=0.05
ok product_id='P014' quantity=2 unit_price=14.99 discount=0.0
invalid ['string_pattern_mismatch', 'greater_than_equal']
invalid ['greater_than', 'less_than_equal']
Starter
records = [
{"product_id": "P010", "quantity": 1, "unit_price": 69.99, "discount": 0.05},
{"product_id": "P014", "quantity": 2, "unit_price": 14.99},
{"product_id": "10", "quantity": 0, "unit_price": 14.99},
{"product_id": "P003", "quantity": 3, "unit_price": -1, "discount": 0.9},
]
# TODO: class OrderLine(BaseModel) with Field constraints
# TODO: validate each record; print "ok" and the model, or the error types
Hint 1

Field(pattern=r"^P\d{3}$"), Field(ge=1, le=50), Field(gt=0), Field(default=0.0, ge=0, le=0.5).

Hint 2

Catch ValidationError and print [e["type"] for e in exc.errors()].

Solution
class OrderLine(BaseModel):
product_id: str = Field(pattern=r"^P\d{3}$")
quantity: int = Field(ge=1, le=50)
unit_price: float = Field(gt=0)
discount: float = Field(default=0.0, ge=0, le=0.5)
records = [
{"product_id": "P010", "quantity": 1, "unit_price": 69.99, "discount": 0.05},
{"product_id": "P014", "quantity": 2, "unit_price": 14.99},
{"product_id": "10", "quantity": 0, "unit_price": 14.99},
{"product_id": "P003", "quantity": 3, "unit_price": -1, "discount": 0.9},
]
results = []
for record in records:
try:
line = OrderLine.model_validate(record)
print("ok", line)
results.append("ok")
except ValidationError as exc:
types = [error["type"] for error in exc.errors()]
print("invalid", types)
results.append(types)
assert results[:2] == ["ok", "ok"]
assert results[2] == ["string_pattern_mismatch", "greater_than_equal"]
Output
ok product_id='P010' quantity=1 unit_price=69.99 discount=0.05
ok product_id='P014' quantity=2 unit_price=14.99 discount=0.0
invalid ['string_pattern_mismatch', 'greater_than_equal']
invalid ['greater_than', 'less_than_equal']

How it works:

  1. pattern checks a string against a regular expression; ge, gt and le check numbers.
  2. The second record has no discount, so the default 0.0 fills it.
  3. pydantic collects every error of a record, not only the first. The fourth record has two problems and both are reported.

M44-W07 · Predict the output: Literal categories and lax mode

Section titled “M44-W07 · Predict the output: Literal categories and lax mode”
Warm-up

Predict the output: three records are validated against a small model. For each, predict ok (and the stored values) or the error types.

Acceptance criteria:

  • Write your prediction for the three records.
  • Run the code. Your prediction matches the Output in the solution.
  • Explain why "12" is accepted for an int field but 12.5 is not.
Starter
class Subscription(BaseModel):
plan: Literal["basic", "standard", "premium"]
has_autopay: bool
tenure_months: int
records = [
{"plan": "basic", "has_autopay": "yes", "tenure_months": "12"},
{"plan": "Basic", "has_autopay": 1, "tenure_months": 12},
{"plan": "premium", "has_autopay": "no", "tenure_months": 12.5},
]
for record in records:
try:
sub = Subscription.model_validate(record)
print("ok", sub.plan, sub.has_autopay, repr(sub.tenure_months))
except ValidationError as exc:
print("invalid", [error["type"] for error in exc.errors()])
Hint 1

Literal compares exactly, including upper and lower case.

Hint 2

Lax mode converts when no information is lost: "yes" and 1 are clear booleans, "12" is a clear integer.

Solution
class Subscription(BaseModel):
plan: Literal["basic", "standard", "premium"]
has_autopay: bool
tenure_months: int
records = [
{"plan": "basic", "has_autopay": "yes", "tenure_months": "12"},
{"plan": "Basic", "has_autopay": 1, "tenure_months": 12},
{"plan": "premium", "has_autopay": "no", "tenure_months": 12.5},
]
outcomes = []
for record in records:
try:
sub = Subscription.model_validate(record)
print("ok", sub.plan, sub.has_autopay, repr(sub.tenure_months))
outcomes.append("ok")
except ValidationError as exc:
print("invalid", [error["type"] for error in exc.errors()])
outcomes.append("invalid")
assert outcomes == ["ok", "invalid", "invalid"]
Output
ok basic True 12
invalid ['literal_error']
invalid ['int_from_float']

How it works:

  1. Record 1: "yes" becomes True and "12" becomes 12. Both conversions are exact.
  2. Record 2: "Basic" is not one of the three allowed strings. A capital letter is enough to fail. Normalize case on the client, or accept it explicitly.
  3. Record 3: 12.5 cannot become an int without losing the half month, so pydantic refuses it (int_from_float).

M44-W08 · PSI of a categorical feature by hand

Section titled “M44-W08 · PSI of a categorical feature by hand”
Warm-up

The contract mix of the training data and of a new month is given below. Compute the PSI term (ci−ri)ln⁡(ci/ri)(c_i - r_i)\ln(c_i / r_i) for each category and the total. Print the terms rounded to 4 decimals and the total rounded to 3.

Expected output
month-to-month 0.024
one-year 0.040
two-year 0.005
dtype: float64
PSI 0.069
Starter
train_share = pd.Series({"month-to-month": 0.55, "one-year": 0.25, "two-year": 0.20})
new_share = pd.Series({"month-to-month": 0.67, "one-year": 0.16, "two-year": 0.17})
# TODO: terms = (new - train) * log(new / train)
# TODO: print the terms and their sum
Hint 1

pandas aligns the two Series by label, so new_share - train_share subtracts category by category.

Hint 2

Use np.log() for the natural logarithm.

Solution
train_share = pd.Series({"month-to-month": 0.55, "one-year": 0.25, "two-year": 0.20})
new_share = pd.Series({"month-to-month": 0.67, "one-year": 0.16, "two-year": 0.17})
terms = (new_share - train_share) * np.log(new_share / train_share)
print(terms.round(4))
total = terms.sum()
print(f"PSI {total:.3f}")
assert (terms >= 0).all()
assert 0.05 < total < 0.1
Output
month-to-month 0.024
one-year 0.040
two-year 0.005
dtype: float64
PSI 0.069

How it works:

  1. Each category is one bin, so rir_i and cic_i are the category shares.
  2. Every term is positive: when a share grows, both factors are positive; when it shrinks, both are negative.
  3. The total is below 0.1, so by the rule of thumb the contract mix is still “stable”, even though month-to-month grew by 12 points. Rules of thumb are a start, not a law: a 12-point jump in the riskiest contract type deserves a look.

M44-W09 · Choose the method: batch or online inference

Section titled “M44-W09 · Choose the method: batch or online inference”
Warm-up

Choose the method and justify it: for each scenario, decide between "batch" (score many rows on a schedule) and "online" (score one request when it arrives). Store your choices in a dictionary and print one line per scenario with a one-sentence reason.

  1. Each night, email the retention team the 200 customers most likely to churn.
  2. Show a churn-risk badge when a call-center agent opens a customer’s page.
  3. Estimate the price of a house while a seller types its details into a web form.
  4. Compute next month’s demand forecast for each of the 30 products.
Expected output
nightly retention list batch all customers, once a day, nobody waits
agent risk badge online an agent waits for the page to load
price estimate in a form online the seller waits for the answer
monthly demand forecast batch 30 products on a schedule
Starter
choices = {
"nightly retention list": ..., # TODO: "batch" or "online"
"agent risk badge": ...,
"price estimate in a form": ...,
"monthly demand forecast": ...,
}
# TODO: print each scenario, the choice and a reason
Hint 1

Ask: does a person wait for the answer right now? If yes, it is online.

Solution
choices = {
"nightly retention list": ("batch", "all customers, once a day, nobody waits"),
"agent risk badge": ("online", "an agent waits for the page to load"),
"price estimate in a form": ("online", "the seller waits for the answer"),
"monthly demand forecast": ("batch", "30 products on a schedule"),
}
for scenario, (mode, reason) in choices.items():
print(f"{scenario:<26}{mode:<8}{reason}")
modes = [mode for mode, _ in choices.values()]
assert modes == ["batch", "online", "online", "batch"]
Output
nightly retention list batch all customers, once a day, nobody waits
agent risk badge online an agent waits for the page to load
price estimate in a form online the seller waits for the answer
monthly demand forecast batch 30 products on a schedule

How it works:

  1. Batch inference suits work on a schedule: it can take minutes, it scores all rows at once and it writes results to a table or a file.
  2. Online inference suits requests where a person or a program waits: latency matters, so the model is loaded once and each request scores one row.
  3. Many systems use both: a nightly batch for lists and an API for single lookups, from the same model bundle.
Core

Split customers (25% test, stratified, random_state=42), fit build_churn_pipeline() on the training rows and compute the test ROC-AUC. Save one bundle with joblib.dump to output/churn_bundle.joblib: a dictionary with the pipeline and a metadata dictionary (model_version "0.1.0", trained_at "2025-02-01", sklearn_version, features, test_roc_auc rounded to 4 decimals). Load it back, print the metadata without the feature list and check that the loaded pipeline gives the same probabilities.

Expected output
model_version 0.1.0
trained_at 2025-02-01
sklearn_version 1.9.1
test_roc_auc 0.8131
same predictions: True
Starter
import joblib
import sklearn
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
# TODO: split, fit, score
# TODO: build metadata and joblib.dump({"pipeline": ..., "metadata": ...}, path)
# TODO: load, print metadata (without "features"), compare predict_proba
Hint 1

Create the folder first: Path("output").mkdir(exist_ok=True).

Hint 2

Loop over metadata.items() and skip the key "features", a long list. np.array_equal() compares the two probability arrays.

Solution
import joblib
import sklearn
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
X, y = customers[FEATURES], customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
pipeline = build_churn_pipeline().fit(X_train, y_train)
auc = roc_auc_score(y_test, pipeline.predict_proba(X_test)[:, 1])
metadata = {
"model_version": "0.1.0",
"trained_at": "2025-02-01",
"sklearn_version": sklearn.__version__,
"features": FEATURES,
"test_roc_auc": round(float(auc), 4),
}
path = Path("output/churn_bundle.joblib")
path.parent.mkdir(exist_ok=True)
joblib.dump({"pipeline": pipeline, "metadata": metadata}, path)
loaded = joblib.load(path)
for key, value in loaded["metadata"].items():
if key != "features":
print(f"{key:<16}{value}")
same = np.array_equal(loaded["pipeline"].predict_proba(X_test),
pipeline.predict_proba(X_test))
print("same predictions:", same)
assert same and loaded["metadata"]["features"] == FEATURES
Output
model_version 0.1.0
trained_at 2025-02-01
sklearn_version 1.9.1
test_roc_auc 0.8131
same predictions: True

How it works:

  1. The bundle is a plain dictionary. joblib pickles the whole structure, so the pipeline and its metadata travel together in one file.
  2. round(float(auc), 4) stores a plain Python float. A NumPy float would also pickle, but plain types also convert to JSON, for an API or a log line.
  3. The loaded pipeline is a new object with the same learned values, so its probabilities are identical.

Alternative: also save the metadata as a JSON sidecar next to the bundle, with the bundle’s SHA-256, as the lesson’s save_bundle() does. A loader can then check the version, the features and the file hash before it unpickles anything, and tools that cannot unpickle (a dashboard, a shell script) can read it.

M44-C02 · Fix the bug: a loader that trusts any bundle

Section titled “M44-C02 · Fix the bug: a loader that trusts any bundle”
Core

Fix the bug: the loader below returns the pipeline of any bundle. Write load_checked(path, expected_features) that raises a ValueError with a clear message when the scikit-learn version differs or when the feature list differs, and returns the bundle otherwise. Test it on three bundles that the starter saves: a good one, one with an old version and one with the features in another order. Print the outcome of each.

Buggy code
def load_model(path):
return joblib.load(path)["pipeline"]
Expected output
good: loaded
refused: old.joblib: saved with scikit-learn 1.4.0, running 1.9.1
refused: swapped.joblib: features differ: ['logins_last_30d', 'tenure_months']
Starter
import joblib
import sklearn
from sklearn.linear_model import LogisticRegression
cols = ["tenure_months", "logins_last_30d"]
model = LogisticRegression().fit(customers[cols], customers["churned"])
good = {"sklearn_version": sklearn.__version__, "features": cols}
Path("output").mkdir(exist_ok=True)
for name, meta in [("good", good),
("old", good | {"sklearn_version": "1.4.0"}),
("swapped", good | {"features": cols[::-1]})]:
joblib.dump({"pipeline": model, "metadata": meta}, f"output/{name}.joblib")
def load_checked(path: Path, expected_features: list[str]) -> dict:
# TODO: load, check version and features, raise ValueError with a message
...
# TODO: try the three files and print "loaded" or the error message
Hint 1

Compare metadata["sklearn_version"] with sklearn.__version__, and metadata["features"] with expected_features. Lists compare element by element, so the order matters.

Hint 2

Wrap each call in try: / except ValueError as exc: and print exc.

Solution
import joblib
import sklearn
from sklearn.linear_model import LogisticRegression
cols = ["tenure_months", "logins_last_30d"]
model = LogisticRegression().fit(customers[cols], customers["churned"])
good = {"sklearn_version": sklearn.__version__, "features": cols}
Path("output").mkdir(exist_ok=True)
for name, meta in [("good", good),
("old", good | {"sklearn_version": "1.4.0"}),
("swapped", good | {"features": cols[::-1]})]:
joblib.dump({"pipeline": model, "metadata": meta}, f"output/{name}.joblib")
def load_checked(path: Path, expected_features: list[str]) -> dict:
bundle = joblib.load(path) # only for files you trust
meta = bundle["metadata"]
if meta["sklearn_version"] != sklearn.__version__:
raise ValueError(f"{path.name}: saved with scikit-learn "
f"{meta['sklearn_version']}, running {sklearn.__version__}")
if meta["features"] != expected_features:
raise ValueError(f"{path.name}: features differ: {meta['features']}")
return bundle
outcomes = {}
for name in ["good", "old", "swapped"]:
try:
load_checked(Path(f"output/{name}.joblib"), cols)
outcomes[name] = "loaded"
print(f"{name}: loaded")
except ValueError as exc:
outcomes[name] = "refused"
print(f"refused: {exc}")
assert outcomes == {"good": "loaded", "old": "refused", "swapped": "refused"}
Output
good: loaded
refused: old.joblib: saved with scikit-learn 1.4.0, running 1.9.1
refused: swapped.joblib: features differ: ['logins_last_30d', 'tenure_months']

How it works:

  1. The version check catches a model file that outlived a library upgrade.
  2. The feature check catches a subtle bug: with the columns swapped, a NumPy-based model would multiply tenure by the logins coefficient. No error, just wrong predictions.
  3. Raising at load time turns a silent wrong answer into a loud, early failure.
  4. These checks run after joblib.load(), so they protect against mistakes, not against a malicious file: unpickling has already run. For that, check a sidecar and the file’s hash before you load, as in Example 3 of the lesson.

M44-C03 · A hash split that survives new data

Section titled “M44-C03 · A hash split that survives new data”
Core

Write split_by_hash(df, id_column, test_percent=25) that returns (train, test) with a CRC32 bucket of the id. Apply it to the first 4,000 customers (“last month”) and to all 5,000 (“this month”). Print the sizes and test churn rates, and check that every test customer of last month is still in this month’s test set.

Expected output
2979 1021 3746 1254
test churn 0.107 -> 0.169
churn: first 4,000 0.123, newest 1,000 0.470
old test customers still in test: True
Starter
def split_by_hash(df: pd.DataFrame, id_column: str,
test_percent: int = 25) -> tuple[pd.DataFrame, pd.DataFrame]:
# TODO: bucket each id with zlib.crc32 % 100; test when bucket < test_percent
...
# TODO: split customers.iloc[:4000] and customers
# TODO: print sizes, test churn rates and the subset check
Hint 1

Build a Boolean mask with df[id_column].map(lambda cid: zlib.crc32(cid.encode()) % 100 < test_percent) and return df[~mask], df[mask].

Hint 2

set(a) <= set(b) tests that every element of a is in b.

Solution
def split_by_hash(df: pd.DataFrame, id_column: str,
test_percent: int = 25) -> tuple[pd.DataFrame, pd.DataFrame]:
buckets = df[id_column].map(lambda cid: zlib.crc32(cid.encode("utf-8")) % 100)
is_test = buckets < test_percent
return df[~is_test], df[is_test]
train_old, test_old = split_by_hash(customers.iloc[:4000], "customer_id")
train_new, test_new = split_by_hash(customers, "customer_id")
print(len(train_old), len(test_old), len(train_new), len(test_new))
old_rate, new_rate = test_old["churned"].mean(), test_new["churned"].mean()
print(f"test churn {old_rate:.3f} -> {new_rate:.3f}")
first, newest = customers.iloc[:4000], customers.iloc[4000:]
print(f"churn: first 4,000 {first['churned'].mean():.3f}, "
f"newest 1,000 {newest['churned'].mean():.3f}")
stable = set(test_old["customer_id"]) <= set(test_new["customer_id"])
print("old test customers still in test:", stable)
assert stable
assert not set(test_new["customer_id"]) & set(train_new["customer_id"])
Output
2979 1021 3746 1254
test churn 0.107 -> 0.169
churn: first 4,000 0.123, newest 1,000 0.470
old test customers still in test: True

How it works:

  1. The bucket of a customer depends only on its id, so adding 1,000 customers cannot move an old one.
  2. The second assert checks that no id is in both sets.
  3. The test churn rate jumps from 10.7% to 16.9%. The split did not change; the population did: the 1,000 newest customers have short tenures and churn far more (47% against 12.3% for the first 4,000). A stable split keeps old rows in place, but the test set still follows the data. Compare model versions on the same old test ids when you want a like-for-like comparison.

Alternative: sklearn.model_selection.GroupShuffleSplit keeps all rows of one customer together, but it is random, not stable when data grows.

M44-C04 · Interpret: why did the content hash change?

Section titled “M44-C04 · Interpret: why did the content hash change?”
Core

Interpret a result: a pipeline fingerprints its input DataFrame with pd.util.hash_pandas_object. After a database upgrade, the fingerprint changes, yet a colleague swears that the data is identical. Reproduce it: compare the fingerprint of customers with the fingerprint of the same rows in shuffled order. Then write stable_fingerprint(df, key) that sorts by the key first, and show that it gives the same value for both.

Expected output
plain: e1268048216e f299baedae66
stable: e1268048216e e1268048216e
Starter
def fingerprint(df: pd.DataFrame) -> str:
rows = pd.util.hash_pandas_object(df, index=False)
return hashlib.sha256(rows.to_numpy().tobytes()).hexdigest()[:12]
shuffled = customers.sample(frac=1, random_state=42)
# TODO: compare fingerprint(customers) and fingerprint(shuffled)
# TODO: write stable_fingerprint(df, key) that sorts by key first
Hint 1

The fingerprint hashes the row hashes in order. What changes when the rows come in another order?

Hint 2

df.sort_values(key, ignore_index=True) gives a canonical order.

Solution
def fingerprint(df: pd.DataFrame) -> str:
rows = pd.util.hash_pandas_object(df, index=False)
return hashlib.sha256(rows.to_numpy().tobytes()).hexdigest()[:12]
def stable_fingerprint(df: pd.DataFrame, key: str) -> str:
return fingerprint(df.sort_values(key, ignore_index=True))
shuffled = customers.sample(frac=1, random_state=42)
print("plain: ", fingerprint(customers), fingerprint(shuffled))
print("stable:", stable_fingerprint(customers, "customer_id"),
stable_fingerprint(shuffled, "customer_id"))
assert fingerprint(customers) != fingerprint(shuffled)
assert stable_fingerprint(customers, "customer_id") == stable_fingerprint(
shuffled, "customer_id")
Output
plain: e1268048216e f299baedae66
stable: e1268048216e e1268048216e

How it works:

  1. The row hashes are the same, but in another order, so the final SHA-256 differs. A SQL query without ORDER BY may return rows in any order; a database upgrade can change it.
  2. Sorting by a unique key gives one canonical order, so the fingerprint depends only on the content.
  3. Interpretation: the colleague is right that the data is the same set of rows. The fingerprint was too strict. Sort before you hash, or hash a sorted export.

M44-C05 · A request model for house prices

Section titled “M44-C05 · A request model for house prices”
Core

Write a pydantic model House for a price-estimate API: neighborhood (one of the 8 values in data/houses.csv), sqft (200–20,000), bedrooms (0–20), bathrooms (0–10, a multiple of 0.5), year_built (1800–2025), has_pool (bool) and school_rating (1–10 or None). Forbid extra fields. Validate the first three houses of the file (missing values become None), then the bad record in the starter, and print the result.

Expected output
Lakeview 2420 True 10
Maple Grove 1610 False 8
Cedar Park 1260 False 3
[('neighborhood', 'literal_error'), ('sqft', 'greater_than_equal'), ('bathrooms', 'multiple_of')]
Starter
houses = pd.read_csv("data/houses.csv")
fields = ["neighborhood", "sqft", "bedrooms", "bathrooms", "year_built",
"has_pool", "school_rating"]
bad = {"neighborhood": "Uptown", "sqft": 90, "bedrooms": 3, "bathrooms": 2.25,
"year_built": 2010, "has_pool": False, "school_rating": None}
# TODO: class House(BaseModel) with Literal, Field constraints and extra="forbid"
# TODO: validate houses[fields].head(3) records, then bad
Hint 1

sorted(houses["neighborhood"].unique()) lists the 8 values for the Literal. Field(multiple_of=0.5) checks the bathrooms.

Hint 2

df.astype(object).where(df.notna(), None).to_dict("records") turns NaN into None.

Solution
from typing import Literal
houses = pd.read_csv("data/houses.csv")
fields = ["neighborhood", "sqft", "bedrooms", "bathrooms", "year_built",
"has_pool", "school_rating"]
class House(BaseModel):
model_config = ConfigDict(extra="forbid")
neighborhood: Literal["Cedar Park", "Downtown", "Lakeview", "Maple Grove",
"Oak Hill", "Old Town", "Riverside", "Westfield"]
sqft: int = Field(ge=200, le=20_000)
bedrooms: int = Field(ge=0, le=20)
bathrooms: float = Field(ge=0, le=10, multiple_of=0.5)
year_built: int = Field(ge=1800, le=2025)
has_pool: bool
school_rating: int | None = Field(default=None, ge=1, le=10)
sample = houses[fields].head(3)
records = sample.astype(object).where(sample.notna(), None).to_dict("records")
for record in records:
house = House.model_validate(record)
print(house.neighborhood, house.sqft, house.has_pool, house.school_rating)
bad = {"neighborhood": "Uptown", "sqft": 90, "bedrooms": 3, "bathrooms": 2.25,
"year_built": 2010, "has_pool": False, "school_rating": None}
try:
House.model_validate(bad)
except ValidationError as exc:
errors = [(e["loc"][0], e["type"]) for e in exc.errors()]
print(errors)
assert [field for field, _ in errors] == ["neighborhood", "sqft", "bathrooms"]
Output
Lakeview 2420 True 10
Maple Grove 1610 False 8
Cedar Park 1260 False 3
[('neighborhood', 'literal_error'), ('sqft', 'greater_than_equal'), ('bathrooms', 'multiple_of')]

How it works:

  1. Literal with the 8 neighborhoods rejects "Uptown": the model never saw it, so its one-hot columns would all be 0.
  2. multiple_of=0.5 encodes a business rule: bathrooms come in halves.
  3. has_pool arrives as 0/1 from the CSV; lax mode turns it into a bool. school_rating may be None, which the pipeline’s imputer can fill.
Core

Build a FastAPI app with GET /health (returns {"status": "ok"}) and POST /charges/zscore. The second endpoint takes {"monthly_charges": <number above 0>} and returns the z-score of that charge against all customers (rounded to 3 decimals) and "unusual": true when the absolute z-score is above 2. Call /health, then /charges/zscore with 60, 140 and -5, and print each status code and body.

Expected output
200 {'status': 'ok'}
60 200 {'z': -0.036, 'unusual': False}
140 200 {'z': 3.452, 'unusual': True}
-5 422 Input should be greater than 0
Starter
from fastapi import FastAPI
from fastapi.testclient import TestClient
MEAN = customers["monthly_charges"].mean()
STD = customers["monthly_charges"].std()
app = FastAPI()
# TODO: request model ChargeIn and response model ZScoreOut
# TODO: @app.get("/health") and @app.post("/charges/zscore")
# TODO: call the endpoints with TestClient and print status and JSON
Hint 1

class ChargeIn(BaseModel): monthly_charges: float = Field(gt=0).

Hint 2

Declare the response model as the return type: def zscore(charge: ChargeIn) -> ZScoreOut:.

Solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
MEAN = customers["monthly_charges"].mean()
STD = customers["monthly_charges"].std()
app = FastAPI()
class ChargeIn(BaseModel):
monthly_charges: float = Field(gt=0)
class ZScoreOut(BaseModel):
z: float
unusual: bool
@app.get("/health")
def health() -> dict[str, str]:
return {"status": "ok"}
@app.post("/charges/zscore")
def zscore(charge: ChargeIn) -> ZScoreOut:
z = (charge.monthly_charges - MEAN) / STD
return ZScoreOut(z=round(z, 3), unusual=abs(z) > 2)
with TestClient(app) as client:
response = client.get("/health")
print(response.status_code, response.json())
codes = []
for value in [60, 140, -5]:
response = client.post("/charges/zscore", json={"monthly_charges": value})
codes.append(response.status_code)
body = response.json()
shown = body if response.status_code == 200 else body["detail"][0]["msg"]
print(value, response.status_code, shown)
assert codes == [200, 200, 422]
Output
200 {'status': 'ok'}
60 200 {'z': -0.036, 'unusual': False}
140 200 {'z': 3.452, 'unusual': True}
-5 422 Input should be greater than 0

How it works:

  1. FastAPI reads the type hint charge: ChargeIn and parses the JSON body into it. A body that fails the gt=0 constraint never reaches your function: FastAPI answers 422.
  2. The return type ZScoreOut is the response model: FastAPI validates the returned object and turns it into JSON.
  3. The mean and standard deviation are computed once, when the module loads, like a model loaded at start-up.

M44-C07 · Predict the output: which errors does FastAPI report?

Section titled “M44-C07 · Predict the output: which errors does FastAPI report?”
Core

Predict the output: the app below receives one request. Predict the status code, the number of errors and the location and type of each error, in order.

Acceptance criteria:

  • Write down the status code and the list of (field, type) pairs.
  • Run the code. Your prediction matches the Output in the solution.
  • Explain why "tenure_months": "12" causes no error.
Starter
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
class Signup(BaseModel):
model_config = ConfigDict(extra="forbid")
age: int = Field(ge=18)
plan: Literal["basic", "standard", "premium"]
tenure_months: int = Field(ge=0)
email: str = Field(pattern=r"^[^@]+@[^@]+$")
@app.post("/signup")
def signup(body: Signup) -> dict[str, str]:
return {"plan": body.plan}
request = {"age": 17, "plan": "standard", "tenure_months": "12",
"email": "ana.example.com", "coupon": "WELCOME"}
with TestClient(app) as client:
response = client.post("/signup", json=request)
print(response.status_code, len(response.json()["detail"]))
for error in response.json()["detail"]:
print(error["loc"][-1], error["type"])
Hint 1

pydantic checks the fields in the order of the class, then reports extra fields.

Hint 2

The email has no @.

Solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
class Signup(BaseModel):
model_config = ConfigDict(extra="forbid")
age: int = Field(ge=18)
plan: Literal["basic", "standard", "premium"]
tenure_months: int = Field(ge=0)
email: str = Field(pattern=r"^[^@]+@[^@]+$")
@app.post("/signup")
def signup(body: Signup) -> dict[str, str]:
return {"plan": body.plan}
request = {"age": 17, "plan": "standard", "tenure_months": "12",
"email": "ana.example.com", "coupon": "WELCOME"}
with TestClient(app) as client:
response = client.post("/signup", json=request)
print(response.status_code, len(response.json()["detail"]))
for error in response.json()["detail"]:
print(error["loc"][-1], error["type"])
fields = [error["loc"][-1] for error in response.json()["detail"]]
assert fields == ["age", "email", "coupon"]
Output
422 3
age greater_than_equal
email string_pattern_mismatch
coupon extra_forbidden

How it works:

  1. age 17 fails ge=18; plan is valid; "12" converts to 12 in lax mode, which is valid.
  2. The email fails the pattern, and the unknown coupon field fails extra="forbid".
  3. FastAPI returns all three errors in one 422 response, in field order and then the extras.

M44-C08 · Fix the bug: a KeyError in every test

Section titled “M44-C08 · Fix the bug: a KeyError in every test”
Core

Fix the bug: the app loads its “model” (here, the churn rate per contract) in a lifespan function. The test code below fails with KeyError: 'rates' on the first request. Explain why and fix it. Then print the status code and body of GET /rate/month-to-month and of GET /rate/weekly, which must return 404.

Buggy test code
client = TestClient(app)
response = client.get("/rate/month-to-month") # KeyError: 'rates'
Expected output
200 {'churn_rate': 0.296}
404 {'detail': "unknown contract 'weekly'"}
Starter
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
state: dict[str, dict[str, float]] = {}
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
state["rates"] = customers.groupby("contract")["churned"].mean().round(3).to_dict()
yield
state.clear()
app = FastAPI(lifespan=lifespan)
@app.get("/rate/{contract}")
def rate(contract: str) -> dict[str, float]:
rates = state["rates"]
if contract not in rates:
raise HTTPException(status_code=404, detail=f"unknown contract {contract!r}")
return {"churn_rate": rates[contract]}
# TODO: fix the test code so that the lifespan runs
Hint 1

When does the lifespan function run? Which object triggers it in a test?

Hint 2

TestClient runs the lifespan only inside a with block.

Solution
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
state: dict[str, dict[str, float]] = {}
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
state["rates"] = customers.groupby("contract")["churned"].mean().round(3).to_dict()
yield
state.clear()
app = FastAPI(lifespan=lifespan)
@app.get("/rate/{contract}")
def rate(contract: str) -> dict[str, float]:
rates = state["rates"]
if contract not in rates:
raise HTTPException(status_code=404, detail=f"unknown contract {contract!r}")
return {"churn_rate": rates[contract]}
with TestClient(app) as client:
ok = client.get("/rate/month-to-month")
missing = client.get("/rate/weekly")
print(ok.status_code, ok.json())
print(missing.status_code, missing.json())
assert ok.status_code == 200 and missing.status_code == 404
assert state == {}
Output
200 {'churn_rate': 0.296}
404 {'detail': "unknown contract 'weekly'"}

How it works:

  1. The lifespan runs when the server starts. TestClient(app) alone does not start anything, so state stays empty and state["rates"] raises KeyError.
  2. with TestClient(app) as client: runs the code before yield on entry and the code after yield on exit. The last assert shows that the cleanup ran.
  3. {contract} in the path is a path parameter: FastAPI passes that part of the URL to the function. HTTPException(status_code=404) turns an unknown contract into a proper “not found” response instead of a crash.

M44-C09 · Keep internal fields out of the response

Section titled “M44-C09 · Keep internal fields out of the response”
Core

An endpoint returns a dictionary that also holds internal fields: the raw feature row and a debug note. Write two versions: /v1/score with the return type dict and /v2/score with a response model PublicScore (churn_probability, model_version), using response_model=PublicScore in the decorator. Call both and print the sorted keys of each response.

Expected output
v1: ['churn_probability', 'debug', 'feature_row', 'model_version']
v2: ['churn_probability', 'model_version']
Starter
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
def internal_result() -> dict:
return {"churn_probability": 0.42, "model_version": "1.0.0",
"feature_row": {"tenure_months": 3, "plan": "premium"},
"debug": "threshold tuned on 2024-12 data"}
# TODO: /v1/score returns internal_result() as is
# TODO: class PublicScore(BaseModel) and /v2/score with response_model=PublicScore
Hint 1

@app.post("/v2/score", response_model=PublicScore) lets the function return a dictionary; FastAPI keeps only the fields of PublicScore.

Solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
def internal_result() -> dict:
return {"churn_probability": 0.42, "model_version": "1.0.0",
"feature_row": {"tenure_months": 3, "plan": "premium"},
"debug": "threshold tuned on 2024-12 data"}
class PublicScore(BaseModel):
churn_probability: float
model_version: str
@app.post("/v1/score")
def score_v1() -> dict:
return internal_result()
@app.post("/v2/score", response_model=PublicScore)
def score_v2() -> dict:
return internal_result()
with TestClient(app) as client:
v1 = client.post("/v1/score").json()
v2 = client.post("/v2/score").json()
print("v1:", sorted(v1))
print("v2:", sorted(v2))
assert set(v2) == {"churn_probability", "model_version"}
Output
v1: ['churn_probability', 'debug', 'feature_row', 'model_version']
v2: ['churn_probability', 'model_version']

How it works:

  1. Without a response model, FastAPI serializes whatever the function returns, internal fields included. That can leak data or details that clients start to depend on.
  2. With response_model=PublicScore, FastAPI validates the result against the model and drops the other keys. The documentation at /docs also shows only the public fields.
  3. Use the response_model= parameter when the function returns a dictionary or another type; use the return annotation when it returns the model itself.

M44-C10 · Drift in house sales between 2022 and 2024

Section titled “M44-C10 · Drift in house sales between 2022 and 2024”
Core

Use houses sold in 2022 as the reference and houses sold in 2024 as the current data. For sqft, distance_to_center_km, school_rating and price, compute the PSI (setup function) and the KS p-value (only for the continuous columns: school_rating has 10 values, so leave its p-value as NaN), add a status column (stable below 0.1, moderate up to 0.25, major above) and print the table. Also print the median price of both years. Does the PSI alarm catch what matters for a price model trained on 2022 sales?

Expected output
957 1002
psi ks_pvalue status
sqft 0.032 0.474 stable
distance_to_center_km 0.023 0.305 stable
school_rating 0.001 NaN stable
price 0.037 0.009 stable
median price 358,500 -> 395,250 (+10.3%)
Starter
from scipy.stats import ks_2samp
houses = pd.read_csv("data/houses.csv", parse_dates=["sold_date"])
reference = houses[houses["sold_date"].dt.year == 2022]
current = houses[houses["sold_date"].dt.year == 2024]
columns = ["sqft", "distance_to_center_km", "school_rating", "price"]
# TODO: one row per column with psi, ks_pvalue and status
Hint 1

ks_2samp(reference[col].dropna(), current[col].dropna()).pvalue. The KS test does not accept NaN.

Hint 2

pd.cut(report["psi"], [0, 0.1, 0.25, np.inf], labels=[...], include_lowest=True) makes the status column.

Solution
from scipy.stats import ks_2samp
houses = pd.read_csv("data/houses.csv", parse_dates=["sold_date"])
reference = houses[houses["sold_date"].dt.year == 2022]
current = houses[houses["sold_date"].dt.year == 2024]
columns = ["sqft", "distance_to_center_km", "school_rating", "price"]
report = pd.DataFrame(
{
"psi": [psi(reference[c], current[c]) for c in columns],
"ks_pvalue": [ks_2samp(reference[c].dropna(), current[c].dropna()).pvalue
if houses[c].nunique() > 20 else np.nan for c in columns],
},
index=columns,
)
report["status"] = pd.cut(report["psi"], [0, 0.1, 0.25, np.inf],
labels=["stable", "moderate", "major"], include_lowest=True)
print(len(reference), len(current))
print(report.round(3))
before, after = reference["price"].median(), current["price"].median()
print(f"median price {before:,.0f} -> {after:,.0f} ({after / before - 1:+.1%})")
assert (report["status"] == "stable").all()
assert report.loc["price", "ks_pvalue"] < 0.05
Output
957 1002
psi ks_pvalue status
sqft 0.032 0.474 stable
distance_to_center_km 0.023 0.305 stable
school_rating 0.001 NaN stable
price 0.037 0.009 stable
median price 358,500 -> 395,250 (+10.3%)

How it works:

  1. The houses themselves did not change: size, distance and school ratings have PSI near 0, and size and distance have large KS p-values. The KS test needs a continuous variable, so the 10-value school rating gets PSI only.
  2. PSI calls the price “stable” too, because prices spread over a wide, skewed range: a 10% level shift moves few rows across the decile edges. The KS test (p below 0.01) and the medians show the shift: the same kind of house sells for about 10% more, for example because of market-wide price growth. With stable inputs, a change in price for the same houses is concept drift.
  3. For a price model, a 10% bias is serious, so PSI alone is the wrong alarm here. Monitor the median of the target and the mean residual once sale prices arrive. Retrain on recent sales, or add the sale date (or a price index) as a feature.

M44-C11 · Interpret: the KS test and the sample size

Section titled “M44-C11 · Interpret: the KS test and the sample size”
Core

Interpret a result: simulate a 1% price increase. For n in 500, 5,000 and 100,000, draw two samples of n monthly charges from customers (with replacement, rng = np.random.default_rng(42)): a reference sample and a current sample that you multiply by 1.01. Print the PSI and the KS p-value for each n. Which measure would you use to raise an alert, and why?

Expected output
n psi ks_pvalue
500 0.034 5.09e-01
5000 0.016 2.98e-02
100000 0.004 9.38e-23
Starter
from scipy.stats import ks_2samp
rng = np.random.default_rng(42)
charges = customers["monthly_charges"].to_numpy()
for n in [500, 5_000, 100_000]:
# TODO: reference = a sample of size n; current = 1.01 * another sample
# TODO: print n, psi and the KS p-value
...
Hint 1

rng.choice(charges, size=n, replace=True) draws one sample. Wrap it in pd.Series for psi().

Solution
from scipy.stats import ks_2samp
rng = np.random.default_rng(42)
charges = customers["monthly_charges"].to_numpy()
rows = []
for n in [500, 5_000, 100_000]:
reference = pd.Series(rng.choice(charges, size=n, replace=True))
current = pd.Series(1.01 * rng.choice(charges, size=n, replace=True))
rows.append({"n": n, "psi": round(psi(reference, current), 4),
"ks_pvalue": ks_2samp(reference, current).pvalue})
result = pd.DataFrame(rows)
print(result.to_string(index=False, formatters={"ks_pvalue": "{:.2e}".format}))
assert (result["psi"] < 0.1).all()
assert result["ks_pvalue"].iloc[-1] < 0.001
Output
n psi ks_pvalue
500 0.034 5.09e-01
5000 0.016 2.98e-02
100000 0.004 9.38e-23

How it works:

  1. The shift is the same 1% in every row of the table. PSI stays small (well below 0.1) whatever the sample size.
  2. The KS p-value falls as n grows: with 100,000 rows per sample, the test detects the 1% shift with near certainty. Statistical significance is not practical importance. PSI is noisier with small samples: with 500 rows, a few rows more or less per bin move it.
  3. Interpretation: alert on PSI (or on the KS statistic DD), which measures the size of the shift. Use the p-value only to confirm that a large shift is not a small-sample accident.
Core

Track a small experiment. Use a fresh SQLite store mlflow_c12.db (delete the file first) and the experiment m44-c12. For a DecisionTreeClassifier(random_state=42) with max_depth 2, 4 and 8 on the 8 numeric churn features (missing values filled with 0), log the parameter max_depth and the metrics cv_auc (5-fold stratified CV ROC-AUC) and train_auc. Then query the runs, sorted by cv_auc, and print max_depth, cv_auc and train_auc.

Expected output
params.max_depth metrics.cv_auc metrics.train_auc
4 0.775 0.793
8 0.718 0.874
2 0.714 0.717
Starter
import logging
import mlflow
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
logging.getLogger("mlflow").setLevel(logging.WARNING)
Path("mlflow_c12.db").unlink(missing_ok=True)
# TODO: set the tracking URI and the experiment
# TODO: one run per max_depth: log_param, log_metrics
# TODO: search_runs ordered by metrics.cv_auc DESC; print three columns
Hint 1

mlflow.set_tracking_uri("sqlite:///mlflow_c12.db") and mlflow.set_experiment("m44-c12").

Hint 2

mlflow.search_runs(experiment_names=["m44-c12"], order_by=["metrics.cv_auc DESC"]) returns a DataFrame; select params.max_depth, metrics.cv_auc and metrics.train_auc.

Solution
import logging
import mlflow
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
logging.getLogger("mlflow").setLevel(logging.WARNING)
Path("mlflow_c12.db").unlink(missing_ok=True)
mlflow.set_tracking_uri("sqlite:///mlflow_c12.db")
mlflow.set_experiment("m44-c12")
X = customers[NUMERIC].fillna(0)
y = customers["churned"]
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for depth in [2, 4, 8]:
with mlflow.start_run(run_name=f"tree-depth-{depth}"):
tree = DecisionTreeClassifier(max_depth=depth, random_state=42)
cv_auc = cross_val_score(tree, X, y, cv=cv, scoring="roc_auc").mean()
train_auc = roc_auc_score(y, tree.fit(X, y).predict_proba(X)[:, 1])
mlflow.log_param("max_depth", depth)
mlflow.log_metrics({"cv_auc": cv_auc, "train_auc": train_auc})
runs = mlflow.search_runs(experiment_names=["m44-c12"],
order_by=["metrics.cv_auc DESC"])
table = runs[["params.max_depth", "metrics.cv_auc", "metrics.train_auc"]]
print(table.to_string(index=False, float_format="{:.3f}".format))
assert len(runs) == 3
assert runs.iloc[0]["params.max_depth"] == "4"
Output
params.max_depth metrics.cv_auc metrics.train_auc
4 0.775 0.793
8 0.718 0.874
2 0.714 0.717

How it works:

  1. Each with mlflow.start_run() block creates one run in the SQLite store. Deleting the file first makes the exercise start clean each time you run it.
  2. Parameters are stored as text, so the assert compares with "4", not 4.
  3. The table tells the overfitting story of module 37: depth 8 has the best training AUC but not the best CV AUC. Logging both makes the gap visible for every run.

M44-C13 · Refactor: from functions to a predictor class

Section titled “M44-C13 · Refactor: from functions to a predictor class”
Core

Refactor procedural code into a class: the starter scores customers with three loose functions and a global variable. Write a class ChurnPredictor with a class method from_bundle(path), a version property and a method predict_one(record: dict) -> float that validates the record with the setup’s Customer model first. The starter saves the bundle. Print the version and the probabilities of the first two customers, rounded to 3 decimals.

Expected output
2.0.0 [0.012, 0.004]
Starter
import joblib
pipeline = build_churn_pipeline().fit(customers[FEATURES], customers["churned"])
bundle = {"pipeline": pipeline,
"metadata": {"model_version": "2.0.0", "features": FEATURES}}
Path("output").mkdir(exist_ok=True)
joblib.dump(bundle, "output/predictor.joblib")
# Procedural version to refactor:
MODEL = None
def load(path):
global MODEL
MODEL = joblib.load(path)
def to_frame(record):
return pd.DataFrame([record], columns=MODEL["metadata"]["features"])
def predict(record):
return MODEL["pipeline"].predict_proba(to_frame(record))[0, 1]
# TODO: class ChurnPredictor with from_bundle, version and predict_one
Hint 1

@classmethod def from_bundle(cls, path: Path) -> "ChurnPredictor": return cls(joblib.load(path)).

Hint 2

In predict_one, call Customer.model_validate(record).model_dump(), then convert has_autopay to int, as the lesson’s API does.

Solution
import joblib
pipeline = build_churn_pipeline().fit(customers[FEATURES], customers["churned"])
bundle = {"pipeline": pipeline,
"metadata": {"model_version": "2.0.0", "features": FEATURES}}
Path("output").mkdir(exist_ok=True)
joblib.dump(bundle, "output/predictor.joblib")
class ChurnPredictor:
"""Score one customer with a saved churn bundle."""
def __init__(self, bundle: dict) -> None:
self._pipeline = bundle["pipeline"]
self._metadata = bundle["metadata"]
@classmethod
def from_bundle(cls, path: Path) -> "ChurnPredictor":
return cls(joblib.load(path))
@property
def version(self) -> str:
return self._metadata["model_version"]
def predict_one(self, record: dict) -> float:
clean = Customer.model_validate(record).model_dump()
row = pd.DataFrame([clean], columns=self._metadata["features"])
row["has_autopay"] = row["has_autopay"].astype(int)
return float(self._pipeline.predict_proba(row)[0, 1])
predictor = ChurnPredictor.from_bundle(Path("output/predictor.joblib"))
records = customers[FEATURES].head(2).to_dict("records")
probabilities = [round(predictor.predict_one(r), 3) for r in records]
print(predictor.version, probabilities)
expected = bundle["pipeline"].predict_proba(customers[FEATURES].head(2))[:, 1]
assert np.allclose(probabilities, expected, atol=5e-4)
Output
2.0.0 [0.012, 0.004]

How it works:

  1. The class keeps the pipeline and the metadata together as private attributes; no global variable can be half-loaded.
  2. from_bundle is an alternative constructor (module 18): it reads the file and builds the object. Tests can call ChurnPredictor(bundle) with an in-memory bundle instead.
  3. predict_one validates first, so the API, a batch job and a notebook all get the same checks. The probabilities equal the pipeline’s own.

M44-X01 · Batch scoring with row-level validation

Section titled “M44-X01 · Batch scoring with row-level validation”
Challenge

A partner sends six customer records as JSON. Score the valid ones and report the invalid ones without stopping the batch. Train build_churn_pipeline() on all customers. For each record, validate it with the setup’s Customer model. Print a table of the valid records with their churn probability (3 decimals) and, below it, one line per rejected record with its index, the first error’s field and its type.

Expected output
contract tenure_months support_tickets churn_probability
0 two-year 72 0 0.012
2 two-year 40 0 0.041
5 two-year 72 6 0.271
rejected record 1: plan (literal_error)
rejected record 3: age (missing)
rejected record 4: monthly_charges (greater_than)
Starter
base = customers[FEATURES].iloc[0].to_dict()
raw_records = [
base,
base | {"plan": "platinum"},
base | {"tenure_months": 40, "contract": "two-year", "has_autopay": 1},
{k: v for k, v in base.items() if k != "age"},
base | {"monthly_charges": -10.0, "support_tickets": 2},
base | {"logins_last_30d": 0, "support_tickets": 6},
]
# TODO: train the pipeline
# TODO: validate each record; collect valid rows and rejections
# TODO: score the valid rows in one predict_proba call; print both reports
Hint 1

The first record comes from a pandas row, so total_charges may be a NumPy float. Customer.model_validate() accepts it.

Hint 2

Collect (index, Customer) pairs for valid records and (index, field, type) for rejections. Build one DataFrame from [c.model_dump() for _, c in valid] and call predict_proba once.

Hint 3

Convert has_autopay to int before you score, as the API does.

Solution
pipeline = build_churn_pipeline().fit(customers[FEATURES], customers["churned"])
base = customers[FEATURES].iloc[0].to_dict()
raw_records = [
base,
base | {"plan": "platinum"},
base | {"tenure_months": 40, "contract": "two-year", "has_autopay": 1},
{k: v for k, v in base.items() if k != "age"},
base | {"monthly_charges": -10.0, "support_tickets": 2},
base | {"logins_last_30d": 0, "support_tickets": 6},
]
valid, rejected = [], []
for index, record in enumerate(raw_records):
try:
valid.append((index, Customer.model_validate(record)))
except ValidationError as exc:
first = exc.errors()[0]
rejected.append((index, first["loc"][0], first["type"]))
frame = pd.DataFrame([c.model_dump() for _, c in valid], columns=FEATURES,
index=[i for i, _ in valid])
frame["has_autopay"] = frame["has_autopay"].astype(int)
frame["churn_probability"] = pipeline.predict_proba(frame[FEATURES])[:, 1].round(3)
print(frame[["contract", "tenure_months", "support_tickets", "churn_probability"]])
for index, field, error_type in rejected:
print(f"rejected record {index}: {field} ({error_type})")
assert list(frame.index) == [0, 2, 5]
assert [r[0] for r in rejected] == [1, 3, 4]
Output
contract tenure_months support_tickets churn_probability
0 two-year 72 0 0.012
2 two-year 40 0 0.041
5 two-year 72 6 0.271
rejected record 1: plan (literal_error)
rejected record 3: age (missing)
rejected record 4: monthly_charges (greater_than)

How it works:

  1. Each record is validated on its own, so one bad record cannot stop the batch. The rejected list is the report for the partner.
  2. All valid rows are scored in one predict_proba call. This is much faster than one call per row on large batches.
  3. The index of each valid row is kept, so every probability can be traced to its input record.

Alternative: pydantic.TypeAdapter(list[Customer]).validate_python(raw_records) validates the whole list at once. It raises one ValidationError that lists the errors of every bad item, so you lose the valid rows of that batch.

Challenge

Write drift_report(reference, current, numeric, categorical) that returns one row per feature with its kind, psi, ks_pvalue and status. Run the KS test only for numeric features with more than 20 distinct values; leave NaN for the others and for categorical features. For categorical features, use the category shares over the union of categories, with a floor of 0.0001. Apply it to customers who signed up before 2024 (reference) and in 2024 (current), for every feature in NUMERIC and CATEGORICAL. Print the report sorted by PSI. Which drift is expected and which deserves a question?

Expected output
3160 1840
kind psi ks_pvalue status
feature
tenure_months numeric 8.708 0.000 major
total_charges numeric 6.152 0.000 major
contract categorical 0.906 NaN major
support_tickets numeric 0.081 NaN stable
monthly_charges numeric 0.023 0.095 stable
age numeric 0.009 0.688 stable
avg_session_minutes numeric 0.006 0.145 stable
plan categorical 0.005 NaN stable
logins_last_30d numeric 0.004 0.827 stable
region categorical 0.003 NaN stable
payment_method categorical 0.001 NaN stable
has_autopay numeric 0.000 NaN stable
month-to-month share: before 0.396, 2024 0.833
Starter
from scipy.stats import ks_2samp
def categorical_psi(reference: pd.Series, current: pd.Series) -> float:
# TODO: shares over the union of categories, floor 1e-4, PSI formula
...
def drift_report(reference: pd.DataFrame, current: pd.DataFrame,
numeric: list[str], categorical: list[str]) -> pd.DataFrame:
# TODO: one row per feature: kind, psi, ks_pvalue, status
...
signup_year = pd.to_datetime(customers["signup_date"]).dt.year
# TODO: reference = before 2024, current = 2024; print the report
Hint 1

reference.value_counts(normalize=True) gives shares. .reindex(categories, fill_value=0) adds missing categories.

Hint 2

Build a list of dictionaries, one per feature, then pd.DataFrame(rows).set_index("feature").

Hint 3

Think about what tenure_months and total_charges mean for customers who signed up this year.

Solution
from scipy.stats import ks_2samp
def categorical_psi(reference: pd.Series, current: pd.Series) -> float:
categories = sorted(set(reference.dropna()) | set(current.dropna()))
ref = reference.value_counts(normalize=True).reindex(categories, fill_value=0)
cur = current.value_counts(normalize=True).reindex(categories, fill_value=0)
ref, cur = ref.clip(lower=1e-4), cur.clip(lower=1e-4)
return float(((cur - ref) * np.log(cur / ref)).sum())
def drift_report(reference: pd.DataFrame, current: pd.DataFrame,
numeric: list[str], categorical: list[str]) -> pd.DataFrame:
rows = []
for column in numeric:
p_value = np.nan
if reference[column].nunique() > 20: # KS assumes a continuous variable
p_value = ks_2samp(reference[column].dropna(),
current[column].dropna()).pvalue
rows.append({"feature": column, "kind": "numeric",
"psi": psi(reference[column], current[column]),
"ks_pvalue": p_value})
for column in categorical:
rows.append({"feature": column, "kind": "categorical",
"psi": categorical_psi(reference[column], current[column]),
"ks_pvalue": np.nan})
report = pd.DataFrame(rows).set_index("feature")
report["status"] = pd.cut(report["psi"], [0, 0.1, 0.25, np.inf],
labels=["stable", "moderate", "major"],
include_lowest=True)
return report.sort_values("psi", ascending=False)
signup_year = pd.to_datetime(customers["signup_date"]).dt.year
reference = customers[signup_year < 2024]
current = customers[signup_year == 2024]
report = drift_report(reference, current, NUMERIC, CATEGORICAL)
print(len(reference), len(current))
print(report.round(3))
before = (reference["contract"] == "month-to-month").mean()
after = (current["contract"] == "month-to-month").mean()
print(f"month-to-month share: before {before:.3f}, 2024 {after:.3f}")
assert report.index[0] == "tenure_months"
assert report.loc["contract", "status"] == "major"
assert report.loc["region", "status"] == "stable"
Output
3160 1840
kind psi ks_pvalue status
feature
tenure_months numeric 8.708 0.000 major
total_charges numeric 6.152 0.000 major
contract categorical 0.906 NaN major
support_tickets numeric 0.081 NaN stable
monthly_charges numeric 0.023 0.095 stable
age numeric 0.009 0.688 stable
avg_session_minutes numeric 0.006 0.145 stable
plan categorical 0.005 NaN stable
logins_last_30d numeric 0.004 0.827 stable
region categorical 0.003 NaN stable
payment_method categorical 0.001 NaN stable
has_autopay numeric 0.000 NaN stable
month-to-month share: before 0.396, 2024 0.833

How it works:

  1. Numeric features use decile bins from the reference and the KS test; categorical features use one bin per category over the union, so a brand-new category in the current data also counts.
  2. tenure_months and total_charges drift massively. That is expected: customers who joined this year cannot have long tenures. A drift report needs context; a feature that depends on the signup date always drifts in a cohort comparison.
  3. contract is the drift that deserves a question: 83% of the 2024 signups are on month-to-month contracts, against 40% before. Is it a campaign or a change in the offer? Or is it survivorship: older cohorts contain only the customers who stayed, and those are mostly on long contracts? Ask the business before you retrain.
  4. support_tickets (10 values) and has_autopay (0/1) get no KS test. The PSI of 0.08 for tickets is below 0.1 but not far: keep watching it.

M44-X03 · A batch prediction endpoint with limits

Section titled “M44-X03 · A batch prediction endpoint with limits”
Challenge

Build a FastAPI app with POST /predict/batch. The body is {"customers": [...]} with 1 to 100 records of the setup’s Customer model. The response holds the model_version and a list of probabilities (4 decimals). Train build_churn_pipeline() on all customers and load it in a lifespan function. Test four requests and print the status code and either the probabilities or the first error’s type and location: 3 valid customers, an empty list, 101 customers and a list whose second customer has age 7.

Expected output
three 200 [0.0124, 0.0043, 0.0409]
empty 422 too_short ['body', 'customers']
too many 422 too_long ['body', 'customers']
bad age 422 greater_than_equal ['body', 'customers', 1, 'age']
Starter
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.testclient import TestClient
# TODO: BatchRequest with customers: list[Customer] = Field(min_length=1, max_length=100)
# TODO: BatchPrediction with model_version and probabilities
# TODO: lifespan that trains (or loads) the pipeline; the endpoint; four test requests
Hint 1

Field(min_length=..., max_length=...) also works on lists: it limits the number of items.

Hint 2

For an error inside the list, loc is ["body", "customers", 1, "age"]: the field name, the item index and the inner field.

Solution
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.testclient import TestClient
models: dict[str, Pipeline] = {}
class BatchRequest(BaseModel):
customers: list[Customer] = Field(min_length=1, max_length=100)
class BatchPrediction(BaseModel):
model_version: str
probabilities: list[float]
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
models["churn"] = build_churn_pipeline().fit(customers[FEATURES],
customers["churned"])
yield
models.clear()
app = FastAPI(lifespan=lifespan)
@app.post("/predict/batch")
def predict_batch(batch: BatchRequest) -> BatchPrediction:
frame = pd.DataFrame([c.model_dump() for c in batch.customers], columns=FEATURES)
frame["has_autopay"] = frame["has_autopay"].astype(int)
probabilities = models["churn"].predict_proba(frame)[:, 1].round(4)
return BatchPrediction(model_version="1.1.0",
probabilities=probabilities.tolist())
records = customers[FEATURES].head(3).to_dict("records")
bodies = {
"three": {"customers": records},
"empty": {"customers": []},
"too many": {"customers": [records[0]] * 101},
"bad age": {"customers": [records[0], records[1] | {"age": 7}]},
}
statuses = {}
with TestClient(app) as client:
for name, body in bodies.items():
response = client.post("/predict/batch", json=body)
statuses[name] = response.status_code
result = response.json()
if response.status_code == 200:
print(name, 200, result["probabilities"])
else:
error = result["detail"][0]
print(name, response.status_code, error["type"], error["loc"])
assert statuses == {"three": 200, "empty": 422, "too many": 422, "bad age": 422}
Output
three 200 [0.0124, 0.0043, 0.0409]
empty 422 too_short ['body', 'customers']
too many 422 too_long ['body', 'customers']
bad age 422 greater_than_equal ['body', 'customers', 1, 'age']

How it works:

  1. A batch endpoint saves one HTTP round trip per customer. max_length=100 protects the service: a client cannot send a million rows in one request and block a worker.
  2. pydantic validates every item of the list with the Customer model; the error location includes the item index, so the client knows which record to fix.
  3. .tolist() turns the NumPy array into plain Python floats for the JSON response.

M44-X04 · Monitor the sales mix month by month

Section titled “M44-X04 · Monitor the sales mix month by month”
Challenge

A model that forecasts store demand was trained on orders from January to March 2023. Monitor data/sales.csv month by month from April 2023: for each month, compute the PSI of the order revenue against the reference months and the categorical PSI of channel (online versus store; reuse the formula of W08). Print every month where either PSI is above 0.1, with both values, the online share and the status channel drift or revenue drift. How many months are flagged, and which drift is it?

Expected output
reference online share 0.289
revenue_psi channel_psi online_share status
month
2024-02 0.035 0.102 0.442 channel drift
2024-05 0.020 0.111 0.449 channel drift
2024-07 0.033 0.120 0.455 channel drift
2024-08 0.027 0.103 0.443 channel drift
2024-10 0.021 0.149 0.475 channel drift
2024-11 0.029 0.269 0.541 channel drift
2024-12 0.033 0.209 0.510 channel drift
7 of 21 months flagged
Starter
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
sales["month"] = sales["order_date"].dt.to_period("M")
reference = sales[sales["month"] <= pd.Period("2023-03", freq="M")]
# TODO: loop over the later months; compute revenue PSI and channel PSI
# TODO: print the flagged months
Hint 1

sales.groupby("month") gives one DataFrame per month; skip months up to 2023-03.

Hint 2

Channel shares: group["channel"].value_counts(normalize=True).reindex(["online", "store"]).

Solution
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
sales["month"] = sales["order_date"].dt.to_period("M")
reference = sales[sales["month"] <= pd.Period("2023-03", freq="M")]
channels = ["online", "store"]
ref_channel = reference["channel"].value_counts(normalize=True).reindex(channels)
rows = []
for month, group in sales.groupby("month"):
if month <= pd.Period("2023-03", freq="M"):
continue
cur_channel = group["channel"].value_counts(normalize=True).reindex(channels)
channel_psi = float(((cur_channel - ref_channel)
* np.log(cur_channel / ref_channel)).sum())
revenue_psi = psi(reference["revenue"], group["revenue"])
rows.append({"month": str(month), "revenue_psi": revenue_psi,
"channel_psi": channel_psi, "online_share": cur_channel["online"]})
monitor = pd.DataFrame(rows).set_index("month")
is_flagged = (monitor["revenue_psi"] > 0.1) | (monitor["channel_psi"] > 0.1)
flagged = monitor[is_flagged].copy()
flagged["status"] = np.where(flagged["channel_psi"] > 0.1, "channel drift",
"revenue drift")
print(f"reference online share {ref_channel['online']:.3f}")
print(flagged.round(3))
print(f"{len(flagged)} of {len(monitor)} months flagged")
assert (monitor["revenue_psi"] < 0.1).all()
assert (flagged["status"] == "channel drift").all()
Output
reference online share 0.289
revenue_psi channel_psi online_share status
month
2024-02 0.035 0.102 0.442 channel drift
2024-05 0.020 0.111 0.449 channel drift
2024-07 0.033 0.120 0.455 channel drift
2024-08 0.027 0.103 0.443 channel drift
2024-10 0.021 0.149 0.475 channel drift
2024-11 0.029 0.269 0.541 channel drift
2024-12 0.033 0.209 0.510 channel drift
7 of 21 months flagged

How it works:

  1. The revenue per order stays stable in every month: its PSI never reaches 0.1.
  2. The online share grows from 28.9% in the reference months to more than 50% at the end of 2024. The channel PSI first crosses 0.1 in February 2024, then again and again, and stays above it at the end of the year. Single flags could be noise; a series of flags along a steady trend is a lasting change.
  3. Interpretation: a demand model per store would overestimate store traffic, because more orders move online. The fix is not only retraining: add the channel as a dimension of the forecast, or forecast online and store demand separately.
Challenge

The training function below gives a different ROC-AUC on each run. Write audit(train_fn) that calls the function twice and returns True when both results are equal. Show that the buggy function fails the audit. Fix it with one seed parameter used everywhere, show that it passes, and write a run record to output/run_record.json with the seed, the data hash (first 12 characters), the scikit-learn version and the metric. Print the audit results and the run record without the version.

Buggy code
def train_buggy() -> float:
X_tr, X_te, y_tr, y_te = train_test_split(customers[NUMERIC].fillna(0),
customers["churned"], test_size=0.25)
forest = RandomForestClassifier(n_estimators=50, max_depth=6)
forest.fit(X_tr, y_tr)
return roc_auc_score(y_te, forest.predict_proba(X_te)[:, 1])
Expected output
buggy passes audit: False
fixed passes audit: True
{'seed': 42, 'roc_auc': 0.7998}
data 7cb64d231768 64
Starter
import sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
# TODO: copy train_buggy from above
# TODO: audit(train_fn) -> bool
# TODO: train_fixed(seed=42) with random_state=seed in both places
# TODO: run record dict; json.dump to output/run_record.json
Hint 1

Two random steps need a seed: the split and the forest.

Hint 2

functools.partial(train_fixed, seed=42) turns the fixed function into one without arguments, so audit() can call it.

Solution
from functools import partial
import sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
def train_buggy() -> float:
X_tr, X_te, y_tr, y_te = train_test_split(customers[NUMERIC].fillna(0),
customers["churned"], test_size=0.25)
forest = RandomForestClassifier(n_estimators=50, max_depth=6)
forest.fit(X_tr, y_tr)
return roc_auc_score(y_te, forest.predict_proba(X_te)[:, 1])
def train_fixed(seed: int) -> float:
X_tr, X_te, y_tr, y_te = train_test_split(
customers[NUMERIC].fillna(0), customers["churned"], test_size=0.25,
stratify=customers["churned"], random_state=seed)
forest = RandomForestClassifier(n_estimators=50, max_depth=6, random_state=seed)
forest.fit(X_tr, y_tr)
return roc_auc_score(y_te, forest.predict_proba(X_te)[:, 1])
def audit(train_fn) -> bool:
return train_fn() == train_fn()
print("buggy passes audit:", audit(train_buggy))
print("fixed passes audit:", audit(partial(train_fixed, seed=42)))
data_hash = hashlib.sha256(Path("data/customers.csv").read_bytes()).hexdigest()
record = {
"seed": 42,
"data_sha256": data_hash, # the full hash; shorten it only for display
"sklearn_version": sklearn.__version__,
"roc_auc": round(train_fixed(42), 4),
}
Path("output").mkdir(exist_ok=True)
Path("output/run_record.json").write_text(json.dumps(record, indent=2))
saved = json.loads(Path("output/run_record.json").read_text())
print({k: v for k, v in saved.items() if k not in ("sklearn_version", "data_sha256")})
print("data", saved["data_sha256"][:12], len(saved["data_sha256"]))
assert audit(partial(train_fixed, seed=42))
assert saved == record
Output
buggy passes audit: False
fixed passes audit: True
{'seed': 42, 'roc_auc': 0.7998}
data 7cb64d231768 64

How it works:

  1. Without seeds, both the split and the forest’s bootstrap samples change on every call, so two calls almost never agree.
  2. One seed parameter, passed to every random step, makes the function a pure function of its inputs: same seed, same data, same versions, same score.
  3. The run record is what a teammate needs to reproduce the number: the seed, the exact data and the library version. In a real project MLflow (or a JSON file next to the model bundle) stores it.