44. ML in production basics
A model in a notebook helps nobody until other software can use it. This module takes the churn model of Part 5 out of the notebook. You make the training run reproducible, give the project a clear structure, save the model with the facts that describe it, serve it as a web API with strict input checks and automated tests, watch the incoming data for drift and record every experiment. Every example uses the churn data in data/customers.csv.
This is the last module of Part 5. The deployment capstone builds on it.
What you will learn
Section titled “What you will learn”- Make a training run reproducible: fix seeds, pin and record library versions, fingerprint the data with a hash and split the rows deterministically.
- Lay out an ML project with
src/,config/,data/,models/,notebooks/andtests/, and know what belongs in a notebook and what belongs in a script. - Save a fitted pipeline together with its metadata (version, training date, metrics, feature list) and check the bundle when you load it.
- Serve predictions with FastAPI: a pydantic request model with
Fieldconstraints andLiteralcategories, a response model,/healthand/predict, tested withTestClientand pytest. - Detect data drift between the training data and a new batch with the population stability index (PSI) and the Kolmogorov–Smirnov test, and plan what to monitor.
- Track experiments with MLflow: log parameters, metrics and a model, then query and compare the runs.
Prerequisites
Section titled “Prerequisites”- Pipelines,
ColumnTransformer, cross-validation and joblib persistence: 34. The scikit-learn workflow. - ROC-AUC, predicted probabilities and decision thresholds: 36. Classification.
- HTTP methods, status codes and JSON: 16. APIs and web data.
Literal, type hints and a first look at pydantic: 12. Type hints.- Test functions, fixtures and
parametrize: 14. Testing with pytest. - Requirements files,
pyproject.tomland the src layout: 08. Modules, packages and environments. - Hypothesis tests and p-values: 29. Statistics and probability.
- The churn data
data/customers.csv, described in the data dictionary.
Concepts
Section titled “Concepts”The lesson page runs top to bottom in one namespace. The first block fixes the pandas display and loads the 5,000 customers.
import numpy as npimport pandas as pd
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")print(customers.shape)print(f"churn rate {customers['churned'].mean():.1%}")(5000, 15)churn rate 19.3%From a notebook to production
Section titled “From a notebook to production”A model is in production when other people or other software rely on its predictions, on new data, again and again. A churn model in production might score every customer each night, or answer a request from the customer-care app in a few milliseconds. MLOps (machine learning operations) is the set of practices that keeps such a model correct over time: reproducible training, versioned artifacts, automated tests, deployment and monitoring.
flowchart LR
D["Data snapshot"] --> T["Training script"]
T --> A["Model bundle<br/>+ metadata"]
T --> E["Experiment log<br/>(MLflow)"]
A --> S["Prediction API"]
S --> M["Monitoring"]
M -->|"drift or decay"| D
Four things change when a model leaves the notebook:
| In a notebook | In production |
|---|---|
| You run cells in any order | A script runs top to bottom, the same way every time |
| The data is one file you loaded | New data arrives every day, and it changes |
| You look at the output | Other programs read the output; nobody checks each prediction |
| An error shows a traceback | An error must give a clear message and must not stop the service |
Models are used in two ways. Batch inference scores many rows on a schedule, for example every customer each night, and writes the scores to a table. Online inference answers one request at a time, as soon as it arrives, usually through a web API. Latency is the time one request takes. Batch jobs care about total run time; online services care about latency.
The most common production bug has a name: training–serving skew. It means that the model sees different inputs in production than in training. Examples: the API sends has_autopay as True while the model learned 1, or the app computes tenure_months from a different date. The defense is to reuse the same code for both: one module with the feature lists and the pipeline, imported by the training script and by the API.
Reproducibility
Section titled “Reproducibility”A run is reproducible when you, or a colleague, can run it again later and get the same model and the same numbers. Without it, you cannot tell if a better score comes from your change or from luck, and you cannot rebuild the model that a customer complaint is about. Five things can change a result:
| Source of change | What to do | Example in this module |
|---|---|---|
| Randomness (splits, bootstraps, initial weights) | Fix every seed: random_state=42, np.random.default_rng(42), torch.manual_seed(42) |
Example 1 |
| Library versions | Pin them in requirements.txt or a lock file, and record them in the model metadata |
Example 1, Example 3 |
| Data | Keep a snapshot and record its hash | Example 1 |
| Which rows are in the test set | Split deterministically, for example by a hash of the id | Example 2 |
| Code and configuration | Keep code in git and settings in a config file; record the model version | Example 3 |
A pinned requirement names one exact version, such as scikit-learn==1.9.1. A file of pinned requirements lets anyone rebuild the same environment. uv pip freeze (or pip freeze) prints every installed package with its exact version:
uv pip freeze > requirements.txt # pin every installed packageuv pip install -r requirements.txt # rebuild the same environment elsewhereA data fingerprint is a short value that identifies the exact content of a dataset. The SHA-256 hash of a file is a good fingerprint: change one byte and the hash changes completely. Store it with the model, and you can later prove which data trained it.
Project structure
Section titled “Project structure”A notebook is good for exploring. It is a poor container for code that must run every night. A clear folder layout tells every reader where things live. This is a common layout for an ML project:
churn-service/├── pyproject.toml # project metadata and dependencies├── requirements.txt # pinned versions (or uv.lock)├── config/│ └── train.toml # seeds, paths, hyperparameters├── data/│ ├── raw/ # input snapshots, never edited by hand│ └── processed/ # files that scripts derive from raw/├── models/ # saved model bundles (not in git)├── notebooks/│ └── 01-eda.ipynb # exploration and charts only├── src/│ └── churn/│ ├── __init__.py│ ├── features.py # feature lists and the pipeline│ ├── train.py # python -m churn.train│ └── api.py # the FastAPI app└── tests/ ├── test_features.py └── test_api.pyThe rules behind the layout:
- Code that matters lives in
src/, in importable modules. Training and serving import the same feature code, which prevents training–serving skew. The src layout (module 08) makes the tests use the installed package, not stray files. - Notebooks explore; scripts produce. A notebook may load the data and plot it. The model that goes to production comes from a script that runs top to bottom with one command.
data/raw/is read-only. Scripts read raw files and write todata/processed/ormodels/. Large data and model files stay out of git; their hashes and versions go into git.- Settings live in a config file, not in the code. A configuration file holds the values that change between runs: paths, seeds and hyperparameters.
The course snippets in python/snippets/m44/ use a flat layout (all files in one folder) so that you can copy them into your project folder and run them at once. Python’s built-in tomllib reads a TOML config file. A frozen dataclass then gives the settings names, types and a fixed value:
import tomllibfrom dataclasses import dataclass
config_text = """[train]seed = 42test_size = 0.25C = 1.0model_path = "models/churn_model.joblib""""
@dataclass(frozen=True)class TrainConfig: seed: int test_size: float C: float model_path: str
config = TrainConfig(**tomllib.loads(config_text)["train"])print(config)TrainConfig(seed=42, test_size=0.25, C=1.0, model_path='models/churn_model.joblib')In a real project, tomllib.load() reads config/train.toml (opened in binary mode, "rb"). A typo in a key, such as sed = 42, raises a TypeError at once, because the dataclass has no field with that name.
Model persistence with metadata
Section titled “Model persistence with metadata”Module 34 saved a fitted pipeline with joblib.dump(). A file alone is not enough in production. Months later, someone asks: which version is this, when was it trained, on which data, with which library versions, and how good was it? Model metadata answers these questions. This module saves it twice. It goes into the same file as the pipeline, as one model bundle, so the model always carries its own description. A copy goes into a small JSON sidecar file next to the bundle, together with the SHA-256 hash of the bundle file:
| Metadata field | Why it matters |
|---|---|
model_version |
the API reports it; logs and complaints refer to it |
trained_at |
shows how old the model is |
data_sha256 |
proves which data trained the model |
sklearn_version |
a pickled model needs the same library version to load safely |
features |
the exact input columns, in order |
metrics |
the score to compare with live performance |
threshold |
the decision rule that turns a probability into an action |
Why both? Unpickling a joblib file can run code, so a check that needs the unpickled bundle comes too late. The sidecar is plain JSON, safe to read. The loader reads the sidecar first and checks three things before it calls joblib.load(): the library version must match, the feature list must be the one the code expects and the file’s SHA-256 must equal the recorded hash. A failed check raises a clear error at start-up, not a wrong answer at 3 a.m. MLflow works the same way: its MLmodel file describes a model before anything is loaded.
Serving predictions with FastAPI
Section titled “Serving predictions with FastAPI”A web framework is a library that turns Python functions into web endpoints. FastAPI is a modern Python web framework. It reads the type hints of your functions to validate the request, convert the data and write the API documentation. You write a function and decorate it with @app.post("/predict"). FastAPI calls the function for each POST request to /predict. This decorated function is a path operation.
A FastAPI app does not listen on the network by itself. An ASGI server (ASGI: Asynchronous Server Gateway Interface, the standard between Python web servers and web apps) does that. Uvicorn is the common choice:
uv pip install uvicorn # not in the course requirementsuvicorn app:app --reload # module app.py, object appcurl http://127.0.0.1:8000/health # in a second terminal--reload restarts the server when you save a file; use it only during development. While the server runs, http://127.0.0.1:8000/docs shows interactive documentation that FastAPI generates from your models.
This is what happens to one request:
sequenceDiagram
participant C as Client
participant F as FastAPI app
participant V as pydantic
participant M as Pipeline
C->>F: POST /predict (JSON body)
F->>V: validate the body as Customer
alt invalid body
V-->>C: 422 and a list of errors
else valid body
F->>M: predict_proba(one-row DataFrame)
M-->>F: churn probability
F-->>C: 200 and a Prediction JSON
end
The service loads the model once, at start-up, not once per request. Loading takes time, and a model that fails its checks should stop the service before it takes traffic. FastAPI’s lifespan function runs code at start-up (before yield) and at shutdown (after yield).
A health check endpoint (/health) answers “is the service up, and which model does it serve?”. Load balancers and monitoring tools call it every few seconds.
Input validation with pydantic
Section titled “Input validation with pydantic”Module 12 introduced pydantic, a library that validates data against a class with type hints. FastAPI uses it for every request and response. A request model describes the JSON body that a client must send. A response model describes the JSON that the API returns. Both are pydantic.BaseModel classes.
A type hint alone checks the type. Field() adds field constraints, rules on the value:
| Constraint | Meaning | Example |
|---|---|---|
ge, gt |
greater than or equal, greater than | age: int = Field(ge=18, le=100) |
le, lt |
less than or equal, less than | monthly_charges: float = Field(gt=0, le=1000) |
min_length, max_length |
length of a string or list | name: str = Field(min_length=1, max_length=80) |
pattern |
a regular expression for a string | customer_id: str = Field(pattern=r"^C\d{5}$") |
default |
the value when the field is missing | total_charges: float | None = Field(default=None, ge=0) |
allow_inf_nan=False |
reject infinity and NaN | ConfigDict(allow_inf_nan=False) for every float |
For a categorical input, Literal["basic", "standard", "premium"] accepts exactly those strings and rejects everything else, such as "gold" or "Basic". This matters for the model: an unknown category would silently become an all-zero one-hot row. model_config = ConfigDict(extra="forbid") also rejects fields that the model does not define, which catches typos such as "tenure_month".
Bound every number on both sides. pydantic accepts "Infinity", "NaN" and 1e308 for a float by default. Without bounds, an infinite total_charges crashes the scaler inside the pipeline, and 1e308 passes and returns a probability of exactly 1. allow_inf_nan=False rejects the non-finite values, and an upper limit such as le=120_000 rejects absurd ones.
When validation fails, FastAPI answers with status 422 (Unprocessable Content: the JSON is well formed but its content is not valid). The body lists every error, with its type, its location and a message. The client sees all problems at once, not one per attempt.
By default, pydantic runs in lax mode: it converts values when the meaning is clear. The string "34" becomes the integer 34, and "yes" becomes True. It refuses conversions that lose information, such as 3.5 for an int. Pass strict=True to Field() or ConfigDict() to refuse every conversion.
Testing an API with TestClient
Section titled “Testing an API with TestClient”You do not need a running server to test an API. FastAPI’s TestClient sends requests directly to the app object, inside the same Python process. It has the same methods as an HTTP client: client.get("/health") and client.post("/predict", json=...). Use it as a context manager, with TestClient(app) as client:, so that the lifespan runs and the model is loaded.
Starlette 1.10, the library under FastAPI, runs TestClient on the httpx2 package, which the course requirements pin.
Errors a service must handle
Section titled “Errors a service must handle”Validation catches bad input with a 422. Two other failures need a deliberate answer, an HTTPException with the right status code:
| Situation | Status | What the client sees |
|---|---|---|
| The body fails validation | 422 | the list of errors |
| A resource does not exist | 404 | {"detail": "..."} |
| The model is not loaded (start-up failed, or still loading) | 503 Service Unavailable | {"detail": "model not loaded"}; retry later |
| The model raises while predicting | 500 Internal Server Error | {"detail": "prediction failed"}, no internal details |
For a 500, the service logs what operators need (the model version and the error type) and sends the client a short, generic message. A stack trace in a response would leak file paths and library versions to strangers.
Data drift
Section titled “Data drift”A model learns the patterns of its training data. When new data looks different, the model works outside what it has seen, and its predictions can become wrong without any error message. Several kinds of change exist:
| Name | What changes | Churn example |
|---|---|---|
| Data drift (covariate shift) | the distribution of the inputs | a price increase raises every monthly_charges |
| Prior shift (label shift) | the share of each class | a competitor’s offer doubles the churn rate |
| Concept drift | the relation between inputs and target | after a new app, few logins no longer mean “about to leave” |
| Prediction drift | the distribution of the model’s scores | the share of customers flagged jumps from 40% to 55% |
Data drift and prediction drift are visible at once, from the inputs and the scores. Prior shift and concept drift need the true labels, which arrive later (you know who churned only a month later). So monitoring compares the inputs first and the performance when the labels arrive.
The data that you compare with is the reference data: usually the training set. The current data is a new batch, such as last month’s customers.
Population stability index (PSI). Cut the reference values into bins (usually 10 bins by quantile, so each holds 10% of the reference). Let be the share of reference rows in bin and the share of current rows. Then
Each term is never negative: when both factors are positive, and when both are negative. PSI is 0 when the shares are identical and grows with the size of the shift. A common rule of thumb: below 0.1 is stable, 0.1 to 0.25 is a moderate shift worth a look, above 0.25 is a major shift. An empty bin would give , so code replaces zero shares with a small number such as 0.0001.
Kolmogorov–Smirnov test (KS test). The two-sample KS test compares two samples of a numeric feature. Its statistic is the largest vertical gap between the two empirical cumulative distribution functions (ECDF, module 28):
scipy.stats.ks_2samp(reference, current) returns and a p-value. The null hypothesis is “both samples come from the same distribution”. With thousands of rows, the test finds even tiny, harmless shifts, so the p-value tells you that a shift exists, and or PSI tells you whether it is large. Use both. The KS test assumes a continuous variable. On a 0/1 column or a count with few values, such as support_tickets (0–9), ties make its p-values unreliable (too large). For such features and for categories, compare the category shares with PSI, or use a chi-square test (module 29).
Monitoring
Section titled “Monitoring”Monitoring means measuring a production system continuously and raising an alert (a message to a person) when a measure crosses a threshold. For an ML service, watch four layers:
| Layer | What to measure | Example alert |
|---|---|---|
| Service health | requests per minute, error rate (5xx, 422), latency | 95th-percentile latency above 200 ms for 10 minutes |
| Input data quality | missing values, out-of-range values, unknown categories, row counts | more than 2% of requests rejected with 422 |
| Drift | PSI per feature against the training data, KS tests | any feature with PSI above 0.25 this week |
| Model quality | share of positive predictions; ROC-AUC and recall once labels arrive | monthly ROC-AUC 0.03 below the training metric |
The thresholds in this table are choices, not standards: set them from the cost of a missed problem and of a false alarm. Also record each prediction with its model version, so you can join it with the true label later. When an alert fires, a person investigates: a data bug (fix the pipeline), a real change in the world (retrain on recent data) or concept drift (rethink the features). Retraining means fitting the same pipeline on newer data; it gets a new model version.
Experiment tracking with MLflow
Section titled “Experiment tracking with MLflow”During model development you try many settings. After a week, nobody remembers which run gave 0.813 and with which C. Experiment tracking records each training run with its settings and results, in a store that you can search. MLflow is a widely used open-source tool for this:
| MLflow term | Meaning |
|---|---|
| Tracking URI | where MLflow stores the records, for example sqlite:///mlflow.db (a local SQLite file) |
| Experiment | a named group of runs, such as churn-baseline |
| Run | one execution of your training code |
| Parameter | an input setting of the run, such as C=0.1 (stored as text) |
| Metric | a number that the run produced, such as cv_auc_mean |
| Tag | a free-form label, such as the data hash |
| Artifact | a file saved with the run: a model, a chart, a report |
| Model signature | the names and types of the model’s inputs and outputs |
mlflow ui --backend-store-uri sqlite:///mlflow.db opens a web page that lists and compares the runs.
Worked examples
Section titled “Worked examples”Example 1 — Prove that a training run is reproducible
Section titled “Example 1 — Prove that a training run is reproducible”Goal: Record the environment and the data fingerprint of a churn training run, and show that a fixed seed gives exactly the same score twice. A teammate must be able to rerun your model next month.
Step 1 — Record the library versions
Section titled “Step 1 — Record the library versions”import sysfrom importlib.metadata import version
packages = ["numpy", "pandas", "scikit-learn", "fastapi", "pydantic", "mlflow"]versions = {name: version(name) for name in packages}for name, installed in versions.items(): print(f"{name:<14}{installed}")print("Python 3.12 or newer:", sys.version_info >= (3, 12))numpy 2.5.4pandas 3.1.1scikit-learn 1.9.1fastapi 0.162.2pydantic 2.14.3mlflow 3.18.0Python 3.12 or newer: Trueimportlib.metadata.version() reads the version of an installed distribution by its name on PyPI (scikit-learn, not sklearn). Save this dictionary with the model. Your versions match these when you installed the pinned course requirements.
Step 2 — Fingerprint the data
Section titled “Step 2 — Fingerprint the data”import hashlibfrom pathlib import Path
data_path = Path("data/customers.csv")file_hash = hashlib.sha256(data_path.read_bytes()).hexdigest()print("file sha256: ", file_hash[:16])
row_hashes = pd.util.hash_pandas_object(customers, index=False)content_hash = hashlib.sha256(row_hashes.to_numpy().tobytes()).hexdigest()changed = customers.copy()changed.loc[0, "monthly_charges"] += 0.01changed_rows = pd.util.hash_pandas_object(changed, index=False)changed_hash = hashlib.sha256(changed_rows.to_numpy().tobytes()).hexdigest()print("content sha256:", content_hash[:16])print("after a 1-cent change:", changed_hash[:16])file sha256: 7cb64d2317686e7acontent sha256: e1268048216e05e4after a 1-cent change: f9eea497ad1fdde4The file hash identifies the exact bytes on disk. The content hash identifies a DataFrame that you built in memory, for example after a SQL query. pd.util.hash_pandas_object() gives one 64-bit hash per row; hashing those again gives one value for the table. A change of one cent in one row changes the whole fingerprint. Print or store only the first 12–16 hex characters for display; keep the full hash in the metadata.
Step 3 — Train with a fixed seed, twice
Section titled “Step 3 — Train with a fixed seed, twice”from sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_split
numeric = ["age", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes"]
def train_and_score(seed: int) -> float: X_tr, X_te, y_tr, y_te = train_test_split( customers[numeric], customers["churned"], test_size=0.25, stratify=customers["churned"], random_state=seed, ) forest = RandomForestClassifier(n_estimators=100, max_depth=6, random_state=seed) forest.fit(X_tr, y_tr) return roc_auc_score(y_te, forest.predict_proba(X_te)[:, 1])
first, second = train_and_score(42), train_and_score(42)print("same seed, same score:", first == second, round(first, 4))same seed, same score: True 0.8016The seed fixes both random steps: which rows go to the test set and which rows and features each tree sees. Two runs on the same machine give the same score to the last digit, so == is safe here. This is the test of reproducibility: rerun and compare.
Step 4 — Measure how much the seed matters
Section titled “Step 4 — Measure how much the seed matters”scores = [train_and_score(seed) for seed in (0, 1, 2, 3, 4)]print([round(s, 4) for s in scores])print(f"spread across seeds: {max(scores) - min(scores):.4f}")[0.8232, 0.7958, 0.8289, 0.8223, 0.82]spread across seeds: 0.0331Other seeds give other scores. The spread is the noise of your setup. An “improvement” smaller than this spread may be luck. Report the seed with every score, and compare models on several seeds or with cross-validation.
Common mistakes:
- Setting a seed in one place only.
train_test_split, the model and any sampling step each needrandom_state. - Pinning versions in
requirements.txtbut not recording them with the model. A file found on a server six months later then has no history. - Hashing the file after a cleaning step changed it. Hash the exact input that the training script read.
Example 2 — Split customers by a hash of their id
Section titled “Example 2 — Split customers by a hash of their id”Goal: Assign each customer to the training or test set in a way that never changes, even when new customers arrive. Then the test set of model version 2 still contains no customer that version 1 trained on.
Step 1 — See a random split move customers
Section titled “Step 1 — See a random split move customers”old_data = customers.iloc[:4500] # the data of last month_, test_old = train_test_split(old_data, test_size=0.2, random_state=42)_, test_new = train_test_split(customers, test_size=0.2, random_state=42)moved = set(test_old["customer_id"]) - set(test_new["customer_id"])print(len(test_old), len(test_new))print(f"{len(moved)} old test customers are now in the training set")900 1000528 old test customers are now in the training setThe seed is the same, but the data has 500 more rows, so the random shuffle is different. Most of last month’s test customers move to the training set. If you compare version 1 and version 2 on the new test set, version 2 has seen some of the “test” customers during training: its score is too optimistic.
Step 2 — Assign each customer by a stable hash
Section titled “Step 2 — Assign each customer by a stable hash”import zlib
def in_test_set(customer_id: str, test_percent: int = 20) -> bool: """Put a customer in the test set when its id hashes into the first 20%.""" bucket = zlib.crc32(customer_id.encode("utf-8")) % 100 return bucket < test_percent
print([in_test_set(cid) for cid in ["C00001", "C00002", "C00003", "C00004"]])is_test = customers["customer_id"].map(in_test_set)print(f"test share {is_test.mean():.3f}")from scipy.stats import norm
rate_test = customers.loc[is_test, "churned"].mean()rate_train = customers.loc[~is_test, "churned"].mean()p_all = customers["churned"].mean()se = np.sqrt(p_all * (1 - p_all) * (1 / is_test.sum() + 1 / (~is_test).sum()))z = (rate_test - rate_train) / seprint(f"churn: test {rate_test:.3f}, train {rate_train:.3f}, z = {z:.2f}")print(f"two-sided p-value {2 * norm.sf(abs(z)):.3f}")[False, False, False, True]test share 0.200churn: test 0.168, train 0.199, z = -2.17two-sided p-value 0.030CRC32 is a fast checksum: it maps any bytes to a 32-bit number that is always the same for the same bytes. % 100 turns it into a bucket from 0 to 99, and 20% of the ids fall into buckets 0–19. The hash knows nothing about churn, so it cannot stratify. Here the test churn rate is 16.8%, against 19.9% in the training rows. The standard error of the difference between two rates (module 29) is with the overall rate , and the gap is standard errors. The p-value says that a gap this large happens in only about 3% of random splits: unlucky. A hash split cannot fix this, so check the rates, report them, and select models with cross-validation on the training rows.
Step 3 — Check that the split is stable
Section titled “Step 3 — Check that the split is stable”old_ids = old_data["customer_id"]old_test_ids = set(old_ids[old_ids.map(in_test_set)])new_test_ids = set(customers.loc[is_test, "customer_id"])print(len(old_test_ids), len(new_test_ids))print("old test customers all still in test:", old_test_ids <= new_test_ids)906 998old test customers all still in test: TrueThe assignment of a customer depends only on its own id. New customers join one set or the other; old customers never move. Large data platforms use the same idea to split users into A/B test groups.
Common mistakes:
- Using Python’s built-in
hash()for strings. It is randomized per process (unlessPYTHONHASHSEEDis set), so the split changes every time you start Python. Usezlib.crc32orhashlib. - Hashing a value that changes, such as an email address. Hash a permanent id.
- Using a hash split when the classes are very rare. The test churn rate can then differ from the overall rate by chance; check it, as Step 2 does.
Example 3 — Train and save the churn model bundle
Section titled “Example 3 — Train and save the churn model bundle”Goal: Move the churn model into scripts: one shared module with the features and the save and load code, one training script that writes a bundle with metadata. This is what a nightly training job runs.
Step 1 — Read the shared module
Section titled “Step 1 — Read the shared module”Copy the three files of this example and the next ones from python/snippets/m44/ into your project folder (the folder that holds data/). The shared module holds everything that training and serving must agree on:
"""Shared code for the churn model: features, pipeline, save and load.
train.py, app.py and the tests import this module, so training and servinguse exactly the same column lists and the same loading checks."""
import hashlibimport jsonfrom pathlib import Pathfrom typing import Any
import joblibimport sklearnfrom sklearn.compose import ColumnTransformerfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler
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 + NUMERICTARGET = "churned"REQUIRED_METADATA = {"model_version", "trained_at", "sklearn_version", "features"}
class ModelLoadError(RuntimeError): """The saved model bundle cannot be used safely."""
def build_pipeline(C: float = 1.0) -> Pipeline: """Return an unfitted pipeline: preprocessing plus logistic regression.""" 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 file_sha256(path: Path, chunk_size: int = 1 << 16) -> str: """Return the SHA-256 hex digest of a file, read in chunks.""" digest = hashlib.sha256() with path.open("rb") as f: while chunk := f.read(chunk_size): digest.update(chunk) return digest.hexdigest()
def sidecar_path(path: Path) -> Path: """Return the JSON file that describes a bundle: models/x.joblib -> x.json.""" return path.with_suffix(".json")
def save_bundle(pipeline: Pipeline, metadata: dict[str, Any], path: Path) -> None: """Save the pipeline and its metadata in one file, plus a JSON sidecar.
The sidecar repeats the metadata and adds the SHA-256 of the bundle file, so a loader can check both before it unpickles anything. """ missing = REQUIRED_METADATA - metadata.keys() if missing: raise ValueError(f"metadata is missing {sorted(missing)}") path.parent.mkdir(parents=True, exist_ok=True) joblib.dump({"pipeline": pipeline, "metadata": metadata}, path) sidecar = metadata | {"bundle_sha256": file_sha256(path)} sidecar_path(path).write_text(json.dumps(sidecar, indent=2))
def load_bundle(path: Path) -> dict[str, Any]: """Check a bundle with its sidecar, then load it.
Every check runs before joblib.load(), because unpickling can run code. The hash proves that the file is the one that save_bundle() wrote. Load only bundles that your own pipeline created. """ sidecar = sidecar_path(path) if not path.exists() or not sidecar.exists(): raise ModelLoadError(f"{path} or its sidecar not found: run python train.py") metadata = json.loads(sidecar.read_text()) if metadata["sklearn_version"] != sklearn.__version__: raise ModelLoadError( f"model saved with scikit-learn {metadata['sklearn_version']}, " f"running {sklearn.__version__}: retrain or pin the version" ) if metadata["features"] != FEATURES: raise ModelLoadError("feature list differs from churn_model.FEATURES") if file_sha256(path) != metadata["bundle_sha256"]: raise ModelLoadError(f"{path.name} changed since it was saved: hash mismatch") return joblib.load(path)file_sha256() reads the file in chunks of 64 KiB (1 << 16 bytes), so it also works for files larger than memory. save_bundle() refuses metadata without the required keys, writes the bundle and then the sidecar models/churn_model.json with the bundle’s hash. load_bundle() reads only the sidecar first. It refuses a bundle from another scikit-learn version, with other features or with a changed file, and calls joblib.load() only after all three checks pass. The pipeline is the baseline of the data dictionary: one-hot encoding, median imputation, scaling and logistic regression.
Step 2 — Read the training script
Section titled “Step 2 — Read the training script”"""Train the churn model and save it with its metadata.
Run from the project folder: python train.pyWrites models/churn_model.joblib (the pipeline and its metadata) andmodels/churn_model.json (the metadata and the SHA-256 of the bundle)."""
from pathlib import Path
import numpy as npimport pandas as pdimport sklearnfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from churn_model import FEATURES, TARGET, build_pipeline, file_sha256, save_bundle
SEED = 42DATA = Path("data/customers.csv")MODEL = Path("models/churn_model.joblib")MODEL_VERSION = "1.0.0"TRAINED_AT = "2025-01-06" # fixed for the course; real code: date.today().isoformat()THRESHOLD = 0.35 # flag a customer when the churn probability is at least this
def main() -> None: customers = pd.read_csv(DATA) X, y = customers[FEATURES], customers[TARGET] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=SEED ) pipeline = build_pipeline(C=1.0) cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED) cv_auc = cross_val_score(pipeline, X_train, y_train, cv=cv, scoring="roc_auc") pipeline.fit(X_train, y_train) test_auc = roc_auc_score(y_test, pipeline.predict_proba(X_test)[:, 1])
metadata = { "model_name": "churn-logreg", "model_version": MODEL_VERSION, "trained_at": TRAINED_AT, "data_file": DATA.name, "data_sha256": file_sha256(DATA), "n_train": len(X_train), "seed": SEED, "sklearn_version": sklearn.__version__, "pandas_version": pd.__version__, "numpy_version": np.__version__, "features": FEATURES, "threshold": THRESHOLD, "metrics": { "cv_roc_auc_mean": round(float(cv_auc.mean()), 4), "cv_roc_auc_std": round(float(cv_auc.std()), 4), "test_roc_auc": round(float(test_auc), 4), }, } save_bundle(pipeline, metadata, MODEL) print(f"trained on {len(X_train):,} rows, tested on {len(X_test):,}") print(f"CV ROC-AUC {cv_auc.mean():.3f} ± {cv_auc.std():.3f}") print(f"test ROC-AUC {test_auc:.3f}") print(f"data sha256 {metadata['data_sha256'][:12]}…") print(f"saved {MODEL} and {MODEL.with_suffix('.json')} (version {MODEL_VERSION})")
if __name__ == "__main__": main()The constants at the top are the settings of this run; a larger project reads them from config/train.toml. TRAINED_AT is a fixed string so that this page shows the same output every time. In your own work, use date.today().isoformat(). The threshold 0.35 flags more customers than 0.5 would: for churn, a missed churner costs more than an unneeded retention call (module 36 explains how to choose it).
Step 3 — Run the training script
Section titled “Step 3 — Run the training script”python train.pytrained on 3,750 rows, tested on 1,250CV ROC-AUC 0.813 ± 0.011test ROC-AUC 0.813data sha256 7cb64d231768…saved models/churn_model.joblib and models/churn_model.json (version 1.0.0)The scores match the baseline in the data dictionary. The script writes two files: the bundle models/churn_model.joblib, which holds the pipeline and its metadata, and the JSON sidecar models/churn_model.json.
Step 4 — Load the bundle and check it
Section titled “Step 4 — Load the bundle and check it”from churn_model import FEATURES, ModelLoadError, file_sha256, load_bundle, save_bundle
bundle = load_bundle(Path("models/churn_model.joblib"))metadata = bundle["metadata"]shown = ["model_name", "model_version", "trained_at", "sklearn_version", "threshold"]for key in shown: print(f"{key:<16}{metadata[key]}")print("metrics:", metadata["metrics"])print("same data as now:", metadata["data_sha256"] == file_sha256(data_path))print(bundle["pipeline"].predict_proba(customers[FEATURES].head(3))[:, 1].round(3))model_name churn-logregmodel_version 1.0.0trained_at 2025-01-06sklearn_version 1.9.1threshold 0.35metrics: {'cv_roc_auc_mean': 0.8126, 'cv_roc_auc_std': 0.0113, 'test_roc_auc': 0.8131}same data as now: True[0.013 0.004 0.045]load_bundle() read the sidecar models/churn_model.json, checked the version, the features and the file hash, and only then unpickled the bundle. Any program can now answer “which model is this?” from the files alone. The data hash matches the current file, so the model was trained on exactly this data. The pipeline takes the raw columns, in the order of FEATURES, and returns churn probabilities.
Step 5 — Refuse an incompatible bundle
Section titled “Step 5 — Refuse an incompatible bundle”old_metadata = metadata | {"sklearn_version": "1.5.2"}save_bundle(bundle["pipeline"], old_metadata, Path("models/old_model.joblib"))load_bundle(Path("models/old_model.joblib"))churn_model.ModelLoadError: model saved with scikit-learn 1.5.2, running 1.9.1: retrain or pin the versionThe sidecar says that the bundle was saved with scikit-learn 1.5.2, so load_bundle() refuses it with a clear message, without unpickling the file. Here the metadata is faked to show the check. In real life this happens after someone upgrades scikit-learn on the server but keeps the old model file. scikit-learn itself only warns (InconsistentVersionWarning), and a service that ignores warnings may then predict nonsense.
Step 6 — Refuse a file that changed
Section titled “Step 6 — Refuse a file that changed”with Path("models/churn_model.joblib").open("ab") as f: f.write(b"\x00") # one extra byte: a damaged copy or a tampered fileload_bundle(Path("models/churn_model.joblib"))churn_model.ModelLoadError: churn_model.joblib changed since it was saved: hash mismatchOne extra byte changes the SHA-256, so the loader refuses the file before joblib.load() can run anything in it. The next block saves the bundle again, so the rest of the page has a valid model.
save_bundle(bundle["pipeline"], metadata, Path("models/churn_model.joblib"))print(load_bundle(Path("models/churn_model.joblib"))["metadata"]["model_version"])1.0.0Common mistakes:
- Deploying the joblib file without its sidecar. The loader then cannot check anything before it unpickles. Copy both files together, and keep the release hash in a trusted place too.
- Using
datetime.now()for anything that a test compares. Fix the value in tests, or compare only its format. - Catching
ModelLoadErrorand starting the service anyway. A service without a valid model must fail at start-up.
Example 4 — Serve the model with FastAPI
Section titled “Example 4 — Serve the model with FastAPI”Goal: Wrap the saved bundle in a web API with a /health endpoint and a /predict endpoint that takes one customer as JSON. The customer-care app calls it when an agent opens a customer’s page.
Step 1 — Read the app
Section titled “Step 1 — Read the app”"""A FastAPI service that predicts churn for one customer.
Run python train.py first, then start the service with: uvicorn app:app --reload
Endpoints: GET /health 200 with the model version, or 503 if no model is loaded POST /predict 200 with a churn probability, 422 for invalid input, 503 if no model is loaded, 500 if the model itself fails"""
import loggingfrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom typing import Any, Literal
import pandas as pdfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, ConfigDict, Field
from churn_model import FEATURES, load_bundle
MODEL_PATH = Path("models/churn_model.joblib")logger = logging.getLogger("churn_api")ml_models: dict[str, Any] = {} # filled once by lifespan()
# The allowed values are exactly the categories of the training data.Region = Literal["East", "North", "South", "West"]Plan = Literal["basic", "standard", "premium"]Contract = Literal["month-to-month", "one-year", "two-year"]PaymentMethod = Literal["electronic_check", "credit_card", "bank_transfer", "paypal"]
class Customer(BaseModel): """The features of one customer, exactly as the client sends them."""
# Reject unknown fields, and reject inf and NaN in every float field. model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
age: int = Field(ge=18, le=100) region: Region plan: Plan contract: Contract payment_method: PaymentMethod has_autopay: bool tenure_months: int = Field(ge=0, le=120) monthly_charges: float = Field(gt=0, le=1000) # None for brand-new customers; at most 120 months x 1000 per month. 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)
class Prediction(BaseModel): churn_probability: float will_churn: bool threshold: float model_version: str
class Health(BaseModel): status: Literal["ok"] model_version: str trained_at: str
@asynccontextmanagerasync def lifespan(app: FastAPI) -> AsyncIterator[None]: """Load and check the model once, at start-up; a bad bundle stops the app.""" ml_models["churn"] = load_bundle(MODEL_PATH) yield ml_models.clear()
app = FastAPI(title="Churn API", version="1.0.0", lifespan=lifespan)
def get_bundle() -> dict[str, Any]: """Return the loaded bundle, or answer 503 when the service is not ready.""" bundle = ml_models.get("churn") if bundle is None: raise HTTPException(status_code=503, detail="model not loaded") return bundle
@app.get("/health")def health() -> Health: metadata = get_bundle()["metadata"] return Health( status="ok", model_version=metadata["model_version"], trained_at=metadata["trained_at"], )
@app.post("/predict")def predict(customer: Customer) -> Prediction: bundle = get_bundle() metadata = bundle["metadata"] row = pd.DataFrame([customer.model_dump()], columns=FEATURES) row["has_autopay"] = row["has_autopay"].astype(int) # the model saw 0/1 try: probability = float(bundle["pipeline"].predict_proba(row)[0, 1]) except Exception as exc: # Log what operators need; send the client no internal details. logger.error( "prediction failed: model=%s error=%s", metadata["model_version"], type(exc).__name__, ) raise HTTPException(status_code=500, detail="prediction failed") from exc return Prediction( churn_probability=round(probability, 4), will_churn=probability >= metadata["threshold"], threshold=metadata["threshold"], model_version=metadata["model_version"], )Read it from the top:
- The
Literalaliases list every allowed category, so a typo such as"Month-to-month"is rejected. The values are exactly the categories of the training data. Customeris the request model. FastAPI sees the parametercustomer: Customerand reads the JSON body into it.PredictionandHealthare response models: the return type hint tells FastAPI to validate and document the response.lifespanloads the bundle once into the dictionaryml_models. Ifload_bundle()raises, the service does not start.get_bundle()answers 503 when no model is loaded, instead of crashing with aKeyError.predict()catches an error of the pipeline, logs the model version and the error type, and answers 500 with a short message.predict()first builds a one-row DataFrame with the columns in the order ofFEATURES. It convertshas_autopayfromTrue/Falseto the 1/0 that the model learned: this one line prevents a training–serving skew.- The endpoint functions use plain
def. FastAPI runs them in a thread pool, which suits CPU work such aspredict_proba. Useasync defonly for code that awaits other async code.
Step 2 — Start the server
Section titled “Step 2 — Start the server”uvicorn app:app --reloadcurl -s -X POST http://127.0.0.1:8000/predict \ -H "Content-Type: application/json" \ -d '{"age": 34, "region": "East", "plan": "premium", "contract": "month-to-month", "payment_method": "electronic_check", "has_autopay": false, "tenure_months": 3, "monthly_charges": 99.5, "total_charges": 298.5, "support_tickets": 4, "logins_last_30d": 2, "avg_session_minutes": 6.5}'Run the first line in one terminal and the curl command in a second one. curl is a command-line HTTP client; -X POST sets the method, -H adds a header and -d sends the body. The rest of this example does the same requests in Python, with no server.
Step 3 — Call the health endpoint
Section titled “Step 3 — Call the health endpoint”from fastapi.testclient import TestClient
from app import app
with TestClient(app) as client: response = client.get("/health")print(response.status_code)print(response.json())200{'status': 'ok', 'model_version': '1.0.0', 'trained_at': '2025-01-06'}Entering the with block runs the lifespan, which loads the bundle. The response is real HTTP: a status code, headers and a JSON body. response.json() turns the body into a dictionary.
Step 4 — Request a prediction
Section titled “Step 4 — Request a prediction”risky_customer = { "age": 34, "region": "East", "plan": "premium", "contract": "month-to-month", "payment_method": "electronic_check", "has_autopay": False, "tenure_months": 3, "monthly_charges": 99.5, "total_charges": 298.5, "support_tickets": 4, "logins_last_30d": 2, "avg_session_minutes": 6.5,}loyal_customer = risky_customer | { "contract": "two-year", "payment_method": "credit_card", "has_autopay": True, "tenure_months": 60, "total_charges": 5970.0, "support_tickets": 0, "logins_last_30d": 25,}with TestClient(app) as client: for name, body in [("risky", risky_customer), ("loyal", loyal_customer)]: response = client.post("/predict", json=body) print(name, response.status_code) print(" ", response.json())risky 200 {'churn_probability': 0.9203, 'will_churn': True, 'threshold': 0.35, 'model_version': '1.0.0'}loyal 200 {'churn_probability': 0.0087, 'will_churn': False, 'threshold': 0.35, 'model_version': '1.0.0'}The json= argument turns the dictionary into a JSON body and sets the Content-Type header. The risky customer has every churn signal of the data dictionary: a short tenure, a monthly contract, electronic check, many tickets and few logins. The loyal customer has none of them. The API returns the probability, the decision and the model version that made it.
Step 5 — See the 503 and 500 answers
Section titled “Step 5 — See the 503 and 500 answers”from app import ml_models
class BrokenModel: def predict_proba(self, X): raise ValueError("model file corrupted")
not_started = TestClient(app) # no "with": the lifespan never ranresponse = not_started.post("/predict", json=risky_customer)print(response.status_code, response.json())
with TestClient(app) as client: ml_models["churn"]["pipeline"] = BrokenModel() # simulate a failing model response = client.post("/predict", json=risky_customer)print(response.status_code, response.json())503 {'detail': 'model not loaded'}prediction failed: model=1.0.0 error=ValueError500 {'detail': 'prediction failed'}Without the lifespan, ml_models is empty and get_bundle() answers 503: “not ready, try later”. With a model that raises, the client gets a 500 with a generic message, and the log line (on standard error) tells the operator which model failed and how. The broken model lives only in this with block: the next with TestClient(app) runs the lifespan again and loads the real bundle. In a real service, configure logging to send these lines to your log system.
Common mistakes:
- Loading the model inside
predict(). Every request then reads the file again: slow, and an invalid file fails only at the first request. - Building the DataFrame from
customer.model_dump()withoutcolumns=FEATURES. The column order then follows the class, and a later change to the class can break the model input. - Running
uvicorn app:appfrom another folder. The relative pathsmodels/anddata/then point to the wrong place. Start it from the project folder.
Example 5 — Reject invalid requests with pydantic
Section titled “Example 5 — Reject invalid requests with pydantic”Goal: Send requests with wrong values, a missing field and an unknown field, and read the 422 errors that FastAPI returns. A client developer reads exactly these messages when the integration fails.
Step 1 — Send a request with five problems
Section titled “Step 1 — Send a request with five problems”import json
bad_request = risky_customer | { "age": 12, "plan": "gold", "tenure_months": "ten", "customer_id": "C00001"}del bad_request["contract"]with TestClient(app) as client: response = client.post("/predict", json=bad_request)errors = response.json()["detail"]print(response.status_code, len(errors), "errors")print(json.dumps(errors[0], indent=2))422 5 errors{ "type": "greater_than_equal", "loc": [ "body", "age" ], "msg": "Input should be greater than or equal to 18", "input": 12, "ctx": { "ge": 18 }}The status is 422 and the body holds a list called detail, with one entry per problem. The first entry is the real JSON for the age: its type is a machine-readable code, loc says where the problem is (body, then the field), msg is for humans, input repeats the bad value and ctx gives the limit.
Step 2 — Print one line per error
Section titled “Step 2 — Print one line per error”for error in errors: field = error["loc"][-1] print(f"{field:<15} {error['type']:<20} {error['msg'][:60]}")age greater_than_equal Input should be greater than or equal to 18plan literal_error Input should be 'basic', 'standard' or 'premium'contract missing Field requiredtenure_months int_parsing Input should be a valid integer, unable to parse string as acustomer_id extra_forbidden Extra inputs are not permittedAll five problems are reported in one response: a value out of range, an unknown category, a missing field, text where a number belongs and an unknown field. Without extra="forbid", pydantic would silently drop customer_id. The message is cut to 60 characters only to fit this page.
Step 3 — See what lax mode converts
Section titled “Step 3 — See what lax mode converts”from pydantic import ValidationError
from app import Customer
loose = risky_customer | {"age": "34", "has_autopay": "yes", "tenure_months": 3.0}customer = Customer.model_validate(loose)print(repr(customer.age), customer.has_autopay, repr(customer.tenure_months))for bad in [{"tenure_months": 3.5}, {"total_charges": "Infinity"}]: try: Customer.model_validate(risky_customer | bad) except ValidationError as exc: print(bad, exc.errors()[0]["type"])34 True 3{'tenure_months': 3.5} int_from_float{'total_charges': 'Infinity'} finite_numberYou can validate without the API: Customer.model_validate() checks a dictionary and raises ValidationError on failure. In lax mode, "34" becomes 34, "yes" becomes True and 3.0 becomes 3, because no information is lost. 3.5 months cannot become an integer without loss, so pydantic rejects it. "Infinity" would convert to a float, but allow_inf_nan=False rejects it as finite_number.
Step 4 — Read the schema that the API publishes
Section titled “Step 4 — Read the schema that the API publishes”schema = app.openapi()["components"]["schemas"]["Customer"]["properties"]for field in ["age", "plan", "total_charges"]: print(field, {key: value for key, value in schema[field].items() if key != "title"})age {'type': 'integer', 'maximum': 100.0, 'minimum': 18.0}plan {'type': 'string', 'enum': ['basic', 'standard', 'premium']}total_charges {'anyOf': [{'type': 'number', 'maximum': 120000.0, 'minimum': 0.0}, {'type': 'null'}]}FastAPI turns the pydantic model into an OpenAPI schema: a standard, machine-readable description of the API. The /docs page and client code generators read it. The constraints that you wrote once with Field() and Literal become documentation that cannot drift away from the code.
Common mistakes:
- Typing categories as
str. The API then accepts"gold", and the one-hot encoder turns the unknown value into all zeros without any error. - Returning 200 with an error message in the body. Clients and monitoring tools rely on the status code.
- Writing range checks by hand inside
predict(). They duplicateField(), and FastAPI cannot document them.
Example 6 — Test the API with pytest
Section titled “Example 6 — Test the API with pytest”Goal: Turn the requests of Examples 4 and 5 into automated tests that run on every change, so a broken endpoint never reaches production.
Step 1 — Read the tests
Section titled “Step 1 — Read the tests”"""Tests for the churn API. Run: pytest -q test_app.py (after python train.py)."""
from collections.abc import Iterator
import pytestfrom fastapi.testclient import TestClient
from app import app, ml_models
VALID = { "age": 34, "region": "East", "plan": "premium", "contract": "month-to-month", "payment_method": "electronic_check", "has_autopay": False, "tenure_months": 3, "monthly_charges": 99.5, "total_charges": 298.5, "support_tickets": 4, "logins_last_30d": 2, "avg_session_minutes": 6.5,}
@pytest.fixture(scope="module")def client() -> Iterator[TestClient]: with TestClient(app) as test_client: # "with" runs the lifespan: loads the model yield test_client
def test_health_reports_model_version(client: TestClient) -> None: response = client.get("/health") assert response.status_code == 200 assert response.json()["model_version"] == "1.0.0"
def test_predict_returns_a_probability(client: TestClient) -> None: response = client.post("/predict", json=VALID) assert response.status_code == 200 body = response.json() assert 0.0 <= body["churn_probability"] <= 1.0 assert body["will_churn"] == (body["churn_probability"] >= body["threshold"])
def test_risky_customer_scores_higher_than_loyal_one(client: TestClient) -> None: loyal = VALID | { "contract": "two-year", "payment_method": "credit_card", "has_autopay": True, "tenure_months": 60, "total_charges": 5970.0, "support_tickets": 0, "logins_last_30d": 25, } risky = client.post("/predict", json=VALID).json()["churn_probability"] safe = client.post("/predict", json=loyal).json()["churn_probability"] assert risky > safe
def test_total_charges_may_be_missing(client: TestClient) -> None: new_customer = VALID | {"tenure_months": 0} del new_customer["total_charges"] assert client.post("/predict", json=new_customer).status_code == 200
@pytest.mark.parametrize( ("field", "value"), [ ("age", 12), ("plan", "gold"), ("monthly_charges", -5), ("tenure_months", "ten"), ("total_charges", "Infinity"), ("total_charges", 1e308), ],)def test_invalid_value_is_rejected( client: TestClient, field: str, value: object) -> None: response = client.post("/predict", json=VALID | {field: value}) assert response.status_code == 422 assert response.json()["detail"][0]["loc"] == ["body", field]
def test_missing_and_unknown_fields_are_rejected(client: TestClient) -> None: missing = {k: v for k, v in VALID.items() if k != "contract"} assert client.post("/predict", json=missing).status_code == 422 extra = VALID | {"customer_id": "C00001"} assert client.post("/predict", json=extra).status_code == 422
class BrokenModel: """A stand-in for a model that fails, such as a corrupted file."""
def predict_proba(self, X: object) -> None: raise ValueError("broken model")
def test_model_failure_returns_500( client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setitem(ml_models["churn"], "pipeline", BrokenModel()) response = client.post("/predict", json=VALID) assert response.status_code == 500 assert response.json() == {"detail": "prediction failed"}
def test_missing_model_returns_503( client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delitem(ml_models, "churn") assert client.get("/health").status_code == 503 assert client.post("/predict", json=VALID).status_code == 503The last two tests use pytest’s monkeypatch fixture (module 14) to swap in a broken model and to remove the model; monkeypatch restores both after each test. The client fixture has scope="module": pytest enters the TestClient once for the whole file, so the model is loaded once. The tests check behavior, not exact probabilities. “A risky customer scores higher than a loyal one” stays true after a retraining; “the probability is 0.9203” does not. Such a test of expected model behavior is a behavioral test.
Step 2 — Run the tests
Section titled “Step 2 — Run the tests”pytest -q test_app.py............. [100%]13 passed in 0.96sThirteen tests pass: the parametrized test counts six times, once per bad value, including "Infinity" and 1e308. The tests need the model file, so a CI job runs python train.py (or downloads the released bundle) before pytest.
Step 3 — List the tests by name
Section titled “Step 3 — List the tests by name”pytest -v --no-header test_app.py======================================= test session starts ========================================collecting ... collected 13 items
test_app.py::test_health_reports_model_version PASSED [ 7%]test_app.py::test_predict_returns_a_probability PASSED [ 15%]test_app.py::test_risky_customer_scores_higher_than_loyal_one PASSED [ 23%]test_app.py::test_total_charges_may_be_missing PASSED [ 30%]test_app.py::test_invalid_value_is_rejected[age-12] PASSED [ 38%]test_app.py::test_invalid_value_is_rejected[plan-gold] PASSED [ 46%]test_app.py::test_invalid_value_is_rejected[monthly_charges--5] PASSED [ 53%]test_app.py::test_invalid_value_is_rejected[tenure_months-ten] PASSED [ 61%]test_app.py::test_invalid_value_is_rejected[total_charges-Infinity] PASSED [ 69%]test_app.py::test_invalid_value_is_rejected[total_charges-1e+308] PASSED [ 76%]test_app.py::test_missing_and_unknown_fields_are_rejected PASSED [ 84%]test_app.py::test_model_failure_returns_500 PASSED [ 92%]test_app.py::test_missing_model_returns_503 PASSED [100%]
======================================== 13 passed in 0.98s ========================================-v prints each test ID. The parametrized cases get IDs from their values, such as [plan-gold], so a failure tells you at once which input broke.
Common mistakes:
- Creating
TestClient(app)withoutwith. The lifespan does not run,ml_modelsstays empty and every request gets a 503 (Step 5 of Example 4). - Asserting an exact probability. Retraining changes it slightly and the test fails for no real reason. Assert ranges, orderings and status codes.
- Testing only valid input. Most production incidents come from unexpected input; test the 422 cases too.
Example 7 — Detect drift in a new month of customers
Section titled “Example 7 — Detect drift in a new month of customers”Goal: Compare the training data with a simulated batch of new customers after a price increase and a drop in app usage. Decide which features drifted and whether the model’s output changed.
Step 1 — Build the reference data and the new batch
Section titled “Step 1 — Build the reference data and the new batch”from churn_model import NUMERIC, TARGET
X_train, X_test, y_train, y_test = train_test_split( customers[FEATURES], customers[TARGET], test_size=0.25, stratify=customers[TARGET], random_state=42,)rng = np.random.default_rng(42)new_month = X_test.copy()new_month["monthly_charges"] = (new_month["monthly_charges"] * 1.08).round(2)new_month["logins_last_30d"] = rng.binomial(new_month["logins_last_30d"], 0.75)switch = (new_month["contract"] == "one-year") & (rng.random(len(new_month)) < 0.4)new_month.loc[switch, "contract"] = "month-to-month"print(len(X_train), len(new_month))print(f"mean charges {X_train['monthly_charges'].mean():.2f} " f"-> {new_month['monthly_charges'].mean():.2f}")3750 1250mean charges 60.78 -> 65.88The reference is the training set of train.py (same seed, same split). The new month starts from the 1,250 test customers and changes three things: prices rise by 8%, each login survives with probability 0.75 (rng.binomial(n, 0.75) keeps about three quarters of each count), and 40% of one-year contracts become month-to-month. Every other column is unchanged.
Step 2 — Write a PSI function and test it
Section titled “Step 2 — Write a PSI function and test it”def psi(reference: pd.Series, current: pd.Series, bins: int = 10) -> float: """Population stability index of current against reference.""" 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)))
print(round(psi(X_train["age"], X_train["age"]), 6))print(round(psi(X_train["age"], X_train["age"] + 10), 3))0.00.997The bin edges are the deciles of the reference data. np.unique merges equal edges, which happen for columns with few distinct values such as support_tickets. The two outer bins are open-ended, so a new value far outside the training range still lands in a bin. The function passes two sanity checks: identical data gives 0, and ages shifted by 10 years give a huge PSI.
Step 3 — Compare every numeric feature
Section titled “Step 3 — Compare every numeric feature”from scipy.stats import ks_2samp
continuous = [c for c in NUMERIC if X_train[c].nunique() > 20] # KS needs theserows = []for column in NUMERIC: row = {"feature": column, "psi": psi(X_train[column], new_month[column]), "ks_stat": np.nan, "ks_pvalue": np.nan} if column in continuous: ks = ks_2samp(X_train[column].dropna(), new_month[column].dropna()) row |= {"ks_stat": ks.statistic, "ks_pvalue": ks.pvalue} rows.append(row)drift = pd.DataFrame(rows).set_index("feature")drift["status"] = pd.cut(drift["psi"], [0, 0.1, 0.25, np.inf], labels=["stable", "moderate", "major"], include_lowest=True)print(drift.sort_values(["psi", "feature"], ascending=[False, True]).round(3)) psi ks_stat ks_pvalue statusfeaturemonthly_charges 0.364 0.147 0.000 majorlogins_last_30d 0.181 0.168 0.000 moderatetenure_months 0.014 0.040 0.102 stableage 0.011 0.027 0.475 stableavg_session_minutes 0.010 0.026 0.566 stabletotal_charges 0.009 0.027 0.502 stablesupport_tickets 0.001 NaN NaN stablehas_autopay 0.001 NaN NaN stableBoth measures agree. monthly_charges has a major shift and logins_last_30d a moderate one; every other feature is stable, with PSI near 0.01 and large p-values. has_autopay (0/1) and support_tickets (10 values) have no KS result: the test needs a continuous variable, and their PSI over the few values is the right check. The p-values below 0.001 for the two drifted features say “this is not chance”. The PSI values say how large the shift is.
How small a shift does the KS test detect at these sample sizes? Apply a 1% and a 2% price rise to the unchanged test customers:
for rise in [0.01, 0.02]: shifted = X_test["monthly_charges"] * (1 + rise) p_value = ks_2samp(X_train["monthly_charges"], shifted).pvalue print(f"{rise:.0%} rise: KS p-value {p_value:.3f}, " f"PSI {psi(X_train['monthly_charges'], shifted):.3f}")1% rise: KS p-value 0.115, PSI 0.0112% rise: KS p-value 0.006, PSI 0.035With 3,750 and 1,250 rows, a 2% price rise already gives a p-value below 0.01, while its PSI stays tiny. So decide on PSI and use the test as a second opinion.
Step 4 — Plot the two drifted features
Section titled “Step 4 — Plot the two drifted features”import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), layout="constrained")for ax, column in zip(axes, ["monthly_charges", "logins_last_30d"], strict=True): both = pd.concat([X_train[column], new_month[column]]) bins = np.histogram_bin_edges(both, bins=30) ax.hist(X_train[column], bins=bins, density=True, alpha=0.55, label="training data") ax.hist(new_month[column], bins=bins, density=True, alpha=0.55, label="new month") ax.set_title(f"{column}: PSI {drift.loc[column, 'psi']:.2f}") ax.set_xlabel(column)axes[0].set_ylabel("density")axes[0].legend()plt.show()
density=True scales both histograms to the same area, so a batch of 1,250 rows compares fairly with 3,750 rows. The same bin edges for both, computed on both batches together, make the bars line up and keep the new, higher charges inside the plot. A chart like this belongs in every drift report: a number says “something changed”, the chart shows what.
Step 5 — Check a categorical feature and the predictions
Section titled “Step 5 — Check a categorical feature and the predictions”categories = sorted(set(X_train["contract"]) | set(new_month["contract"]))ref_share = X_train["contract"].value_counts(normalize=True).reindex( categories, fill_value=0).clip(lower=1e-4)cur_share = new_month["contract"].value_counts(normalize=True).reindex( categories, fill_value=0).clip(lower=1e-4)contract_psi = float(((cur_share - ref_share) * np.log(cur_share / ref_share)).sum())print(pd.DataFrame({"train": ref_share, "new": cur_share}).round(3))print(f"contract PSI {contract_psi:.3f}")
pipeline = bundle["pipeline"]p_train = pd.Series(pipeline.predict_proba(X_train)[:, 1])p_new = pd.Series(pipeline.predict_proba(new_month)[:, 1])threshold = metadata["threshold"]print(f"mean churn score {p_train.mean():.3f} -> {p_new.mean():.3f}")flag_train, flag_new = (p_train >= threshold).mean(), (p_new >= threshold).mean()print(f"flagged share {flag_train:.3f} -> {flag_new:.3f}")print(f"score PSI {psi(p_train, p_new):.3f}") train newcontractmonth-to-month 0.550 0.670one-year 0.244 0.156two-year 0.206 0.174contract PSI 0.069mean churn score 0.193 -> 0.237flagged share 0.189 -> 0.254score PSI 0.065For a categorical feature, each category is one bin. The shares are taken over the union of both batches’ categories, with the same floor of 0.0001 as psi(), so a category that is new or missing in one batch still counts. The contract mix moved toward month-to-month, but the PSI is still below 0.1. The scores tell a stronger story: the share of flagged customers rises from 18.9% to 25.4%, so the retention team gets a third more calls to make. Yet the score PSI is only 0.065. PSI summarizes the whole distribution; a shift near the threshold matters more for the decision than PSI shows. So monitor the decision rate too, not only PSI. This prediction drift is not a bug: higher prices, fewer logins and more monthly contracts are real churn risks. Whether the model is still accurate on such customers, only the labels of next month can tell.
Common mistakes:
- Computing the bin edges on the current data, or on both together. The reference defines the bins; otherwise the measure changes with every batch.
- Raising an alert on every small p-value. With large samples almost everything is “significant”. Use PSI or thresholds.
- Retraining at once on every alert. First check the data pipeline: a unit change (cents instead of dollars) also looks like major drift.
Example 8 — Track churn experiments with MLflow
Section titled “Example 8 — Track churn experiments with MLflow”Goal: Log three churn runs with different regularization strengths to a local MLflow store, find the best run with a query and load its model back. This replaces a spreadsheet of results that nobody updates.
Step 1 — Point MLflow at a local database
Section titled “Step 1 — Point MLflow at a local database”import loggingimport os
import mlflowimport mlflow.sklearnimport sklearnfrom mlflow.models import infer_signature
logging.getLogger("mlflow").setLevel(logging.WARNING) # hide INFO lines# uv environments have no pip; MLflow warns that it cannot pin pip in conda.yaml.logging.getLogger("mlflow.utils.environment").setLevel(logging.ERROR)os.environ["MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR"] = "false" # no download bars
mlflow.set_tracking_uri("sqlite:///mlflow.db")experiment = mlflow.set_experiment("churn-baseline")print(experiment.name, experiment.lifecycle_stage)churn-baseline activesqlite:///mlflow.db (three slashes) means “the file mlflow.db in the current folder”. The first call creates the database tables and logs INFO lines such as “Creating initial MLflow database tables…” to standard error; the logger level hides them. set_experiment() creates the experiment if it does not exist and makes it active.
Step 2 — Log one run per value of C
Section titled “Step 2 — Log one run per value of C”from sklearn.model_selection import StratifiedKFold, cross_val_score
from churn_model import build_pipeline
X_track = X_train.astype({column: "float64" for column in NUMERIC})cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)for C in [0.01, 0.1, 1.0]: with mlflow.start_run(run_name=f"logreg-C{C}"): model = build_pipeline(C=C) auc = cross_val_score(model, X_track, y_train, cv=cv, scoring="roc_auc") model.fit(X_track, y_train) mlflow.log_params({"C": C, "seed": 42, "n_train": len(X_track)}) mlflow.log_metrics({"cv_auc_mean": auc.mean(), "cv_auc_std": auc.std()}) mlflow.set_tag("data_sha256", file_hash) signature = infer_signature(X_track, model.predict_proba(X_track)) mlflow.sklearn.log_model( model, name="model", signature=signature, input_example=X_track.head(2), pyfunc_predict_fn="predict_proba", skops_trusted_types=["numpy.dtype"], pip_requirements=[f"scikit-learn=={sklearn.__version__}", f"pandas=={pd.__version__}"], ) print(f"logged C={C}: CV ROC-AUC {auc.mean():.4f}")logged C=0.01: CV ROC-AUC 0.8087logged C=0.1: CV ROC-AUC 0.8122logged C=1.0: CV ROC-AUC 0.8126Each with mlflow.start_run() block is one run. Inside it, log_params stores the settings, log_metrics the results and set_tag the data fingerprint. log_model saves the fitted pipeline with:
- a signature, inferred from real inputs and outputs, that records the columns and types the model expects. The integer columns are cast to
float64first, as MLflow recommends: an integer column cannot hold a missing value, and JSON clients may send34.0. pyfunc_predict_fn="predict_proba", so MLflow’s generic loader returns probabilities, not 0/1 labels.skops_trusted_types: MLflow 3 saves scikit-learn models in the safer skops format, which refuses types it does not know.numpy.dtypeis a plain NumPy data type, safe to trust.pip_requirements, the exact versions the model needs. MLflow would otherwise infer them from the environment.
Step 3 — Compare the runs with a query
Section titled “Step 3 — Compare the runs with a query”runs = mlflow.search_runs( experiment_names=["churn-baseline"], order_by=["metrics.cv_auc_mean DESC"])columns = ["tags.mlflow.runName", "params.C", "metrics.cv_auc_mean", "metrics.cv_auc_std"]print(runs[columns].to_string(index=False, float_format="{:.4f}".format))tags.mlflow.runName params.C metrics.cv_auc_mean metrics.cv_auc_std logreg-C1.0 1.0 0.8126 0.0113 logreg-C0.1 0.1 0.8122 0.0123 logreg-C0.01 0.01 0.8087 0.0136search_runs() returns a pandas DataFrame with one row per run. Parameters appear as params.<name> (as text), metrics as metrics.<name> and tags as tags.<name>. It also has columns such as run_id and start_time, which differ on every run, so this page does not print them. You can filter too: filter_string="metrics.cv_auc_mean > 0.81". The three values of C give nearly the same score; the differences are smaller than one standard deviation, so the choice of C hardly matters here.
Step 4 — Load the best model back
Section titled “Step 4 — Load the best model back”best = runs.iloc[0]best_model = mlflow.sklearn.load_model(f"runs:/{best['run_id']}/model")generic = mlflow.pyfunc.load_model(f"runs:/{best['run_id']}/model")sample = X_test.head(3).astype({column: "float64" for column in NUMERIC})print(type(best_model).__name__, best["params.C"])print(best_model.predict_proba(sample)[:, 1].round(3))print(np.asarray(generic.predict(sample))[:, 1].round(3))Pipeline 1.0[0.151 0.298 0.071][0.151 0.298 0.071]The URI runs:/<run_id>/model names the model of one run. mlflow.sklearn.load_model() gives back the scikit-learn pipeline. mlflow.pyfunc.load_model() gives a generic wrapper with one predict() method, the same for every library, which also checks the input against the signature. Both return the same probabilities.
Common mistakes:
- Logging the score of the test set for every run, then picking the best. The test set is then part of model selection. Log CV scores for selection and touch the test set once.
- Forgetting the
withblock. A run started withmlflow.start_run()alone stays open until you callmlflow.end_run(), and later logs go into it. - Keeping
mlflow.dbandmlruns/in git. They grow with every run. Add both to.gitignore, or use a shared tracking server for a team.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
No seed in train_test_split or the model |
Scores change on every run; nobody can reproduce a result | random_state=42 everywhere; record the seed |
hash(customer_id) for a split |
The split changes every time Python starts | zlib.crc32(id.encode()) % 100 or hashlib |
| Random split on growing data | Old test rows end up in training; version 2 looks too good | Split by a stable hash of the id |
| Model file without metadata | Nobody knows the version, the data or the metrics | Save one bundle: pipeline plus metadata dictionary |
| Newer scikit-learn on the server | InconsistentVersionWarning, wrong or failed predictions |
Pin the version; check it in load_bundle() |
| Model loaded inside the endpoint | Slow requests; a bad file fails at the first request | Load once in the lifespan function |
Categories typed as str |
Unknown values such as "gold" become all-zero rows |
Literal[...] with the training categories |
No extra="forbid" |
A typo such as tenure_month is dropped silently and the default is used |
model_config = ConfigDict(extra="forbid") |
TestClient(app) without with |
503 (or a KeyError without get_bundle()): the model was never loaded |
with TestClient(app) as client: |
| No bounds on float inputs | "Infinity" gives a 500; 1e308 gives a probability of 1 |
allow_inf_nan=False and le= on every number |
| Stack trace or raw error in a 500 response | Leaks paths and versions to clients | Log the details; return a generic detail |
joblib.load() before any check |
A tampered file can run code on load | Check the sidecar hash and metadata first |
| Drift bins computed on new data | PSI changes meaning with every batch | Bin edges from the reference data only |
mlflow.set_tracking_uri("file:./mlruns") in MLflow 3.18 |
MlflowException: the file store is in maintenance mode |
sqlite:///mlflow.db |
mlflow.sklearn.log_model without skops_trusted_types |
MlflowException about untrusted types such as numpy.dtype |
Pass the types that the error lists, after you check them |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: FastAPI with pydantic models is a standard way to build any JSON API: user sign-up, payments, internal tools. The same
Fieldconstraints validate an email length or an order quantity, andTestClienttests them. - Software releases: pinned versions, lock files and file hashes make every build reproducible. Package managers such as uv and pip check the SHA-256 hash of each downloaded wheel.
- Operations: health check endpoints, latency metrics and alerts are the basis of site reliability engineering. Load balancers stop sending traffic to a server whose
/healthfails. - Experimentation platforms: hash-based assignment puts each user in a stable A/B test group, and drift checks catch broken event tracking before it ruins an analysis.
Summary
Section titled “Summary”- A model in production runs on new data, again and again, for other software. Training–serving skew is the classic bug: share one feature module between training and serving.
- Reproducibility needs fixed seeds, pinned and recorded versions, a data hash and a deterministic split. Measure the score spread across seeds before you trust a small gain.
- Keep production code in
src/and scripts, settings in a config file, raw data read-only, and notebooks for exploration. - Save the pipeline and its metadata (version, training date, data hash, library versions, features, metrics, threshold) as one bundle, with a JSON sidecar that records the bundle’s SHA-256. Check the sidecar before you unpickle, and load only files your own pipeline created.
- FastAPI turns type-hinted functions into endpoints. A pydantic request model with
Fieldconstraints andLiteralcategories rejects bad input with a 422 that lists every error; bound every number and reject inf and NaN. Answer 503 when no model is loaded and a generic 500 when the model fails. Load the model once in the lifespan; expose/health. TestClienttests the API in-process. Test status codes, ranges, orderings and invalid input, not exact probabilities.- Data drift changes the inputs; concept drift changes the relation to the target. PSI measures the size of a shift, the KS test its significance. Bin edges come from the reference data.
- MLflow records parameters, metrics, tags and models of each run. Use a SQLite tracking URI in MLflow 3 and query runs with
search_runs().
Self-check questions
Section titled “Self-check questions”Q1. You train the same model twice and get ROC-AUC 0.8122 and 0.8139. Name three possible causes.
Answer
A seed is missing (in the split, in the model or in a sampling step); the data changed between runs (check the hash); or a library version changed (check the recorded versions). With seeds, data and versions fixed, a scikit-learn model gives the same score to the last digit on the same machine and library build.
Q2. Why is hash(customer_id) % 100 < 20 a bad way to choose the test set?
Answer
Python randomizes the hash of strings per process (unless PYTHONHASHSEED is set). Each new Python process puts different customers in the test set. Use a stable function such as zlib.crc32(customer_id.encode()) % 100 or a hashlib digest.
Q3. A random split with random_state=42 is reproducible. Why does Example 2 still prefer a hash split?
Answer
A random split is reproducible only for the same data. When new rows arrive, the shuffle changes and most old test rows move to the training set. Model version 2 is then evaluated on rows it trained on. A hash split assigns each id the same way forever, whatever other rows exist.
Q4. Name five metadata fields that you save with a production model, and why each one matters.
Answer
The model version (logs and the API refer to it), the training date (age of the model), the data hash (which data trained it), the scikit-learn version (it must match to load safely), the feature list (exact inputs, in order), the metrics (the baseline for monitoring) and the decision threshold (how a probability becomes an action). Any five of these.
Q5. A client sends {"plan": "gold", ...} to the churn API. What happens with plan: Literal["basic", "standard", "premium"], and what would happen with plan: str?
Answer
With Literal, pydantic rejects the request: status 422 with a literal_error that lists the allowed values. With str, the request passes, and the OneHotEncoder(handle_unknown="ignore") turns the unknown plan into all zeros. The model returns a probability for a customer that does not exist, and nobody notices.
Q6. Why does the app load the model in the lifespan function and not inside predict()?
Answer
Loading takes time; doing it once at start-up keeps each request fast. It also fails early: if load_bundle() raises (missing file, wrong version), the service does not start, instead of failing on the first customer’s request.
Q7. A test asserts response.json()["churn_probability"] == 0.9203. Why is this a weak test, and what is better?
Answer
Any retraining changes the probability slightly, so the test fails without a real bug and people learn to ignore it. Better: check the status code, that the probability is between 0 and 1, that will_churn agrees with the threshold, and behavioral facts such as “a risky customer scores higher than a loyal one”.
Q8. For monthly_charges, the KS test gives p = 0.003 and PSI = 0.02. For logins_last_30d, p < 1e-10 and PSI = 0.31. What do you conclude?
Answer
Both shifts are statistically real (small p-values), but only the logins shift is large. PSI 0.02 is stable; with thousands of rows, the KS test detects tiny, harmless shifts. PSI 0.31 is a major shift: investigate the logins data (a tracking bug or a real change) and watch the model’s performance closely.
Q9. What is the difference between data drift and concept drift? Which one can you detect without labels?
Answer
Data drift is a change in the distribution of the inputs. Concept drift is a change in the relation between the inputs and the target. You can detect data drift (and prediction drift) at once from the inputs and the scores. Concept drift needs the true labels, which arrive later, so you see it as a drop in performance.
Q10. In MLflow, what is the difference between a parameter, a metric and an artifact? Give a churn example of each.
Answer
A parameter is an input setting of the run, such as C=0.1. A metric is a number that the run produced, such as cv_auc_mean=0.8122. An artifact is a file saved with the run, such as the fitted pipeline (the logged model) or a drift chart.
Q11. mlflow.set_tracking_uri("file:./mlruns") raises an error in MLflow 3.18. What do you use instead, and where do the model files go?
Answer
Use a database URI such as sqlite:///mlflow.db. The runs, parameters and metrics go into the SQLite file; the model files and other artifacts still go into the folder ./mlruns.
Q12. Why does load_bundle() read the JSON sidecar and hash the bundle file before it calls joblib.load()? What does a hash stored next to the file not protect against?
Answer
Unpickling can run code, so every check must happen before joblib.load(). The sidecar is plain JSON and safe to read: it gives the version, the features and the expected SHA-256, and a changed file fails the hash check. A hash in a file next to the bundle does not stop an attacker who can replace both files. Keep the release hash in a trusted place too, and load only files that your own pipeline created.
Q13. The churn API returns 422, 503 and 500 in different situations. What does each one tell the client?
Answer
422: the request body is invalid; fix the input (the detail list says how). 503: the service is not ready, for example the model is not loaded; retry later. 500: the server failed while predicting; the client cannot fix it, and the operators find the cause in the log, which records the model version and the error type.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 27 exercises on reproducibility, model bundles, pydantic validation, FastAPI endpoints and tests, drift metrics and MLflow.
- Mini-project: build a monthly model health report that checks the bundle, measures drift and decides whether to retrain.
- Cheat sheet: persistence, FastAPI, pydantic, drift and MLflow on one page.
- This is the last module of Part 5. Test yourself with the Part 5 checkpoint, then choose a project from the capstones. The deployment capstone extends this module’s API.