Skip to content

44. ML in production basics — Cheat sheet

The essentials of module 44 on one page. Every runnable block on this page is checked against its output. The full service (churn_model.py, train.py, app.py, test_app.py) is in the lesson’s Examples 3 to 6.

I want to… Use… Example
fix randomness one seed everywhere random_state=42, np.random.default_rng(42)
pin the environment a requirements or lock file uv pip freeze > requirements.txt, uv lock
record installed versions importlib.metadata.version() version("scikit-learn")
fingerprint a file hashlib.sha256 hashlib.sha256(path.read_bytes()).hexdigest()
fingerprint a DataFrame pd.util.hash_pandas_object sort by a key first
split stably as data grows a hash of the id zlib.crc32(cid.encode()) % 100 < 20
read a TOML config tomllib.load(f) (binary mode) config/train.toml
save a model with metadata one joblib bundle + JSON sidecar joblib.dump({"pipeline": p, "metadata": m}, path)
refuse an incompatible or changed model check the sidecar before joblib.load version, features, SHA-256 of the file
build a JSON API FastAPI path operations @app.post("/predict")
validate the request body a pydantic BaseModel def predict(customer: Customer)
limit a number Field(ge=, gt=, le=, lt=) age: int = Field(ge=18, le=100)
allow fixed categories only Literal[...] plan: Literal["basic", "standard", "premium"]
reject unknown fields ConfigDict(extra="forbid") catches typos
reject inf and NaN ConfigDict(allow_inf_nan=False) with le= bounds on every number
answer “not ready” HTTPException(status_code=503) model not loaded
hide internal errors log, then HTTPException(status_code=500, detail="prediction failed") no stack trace to clients
make a field optional a default total_charges: float | None = None
shape the response return type or response_model= def predict(...) -> Prediction:
load the model once a lifespan function FastAPI(lifespan=lifespan)
answer “not found” HTTPException raise HTTPException(status_code=404, detail="...")
run the API Uvicorn uvicorn app:app --reload
test the API without a server TestClient with TestClient(app) as client:
measure the size of a shift PSI below 0.1 stable, above 0.25 major
test a continuous shift scipy.stats.ks_2samp ks_2samp(ref, cur).pvalue (not for 0/1 or few values)
track experiments MLflow mlflow.start_run(), log_params, log_metrics
compare runs mlflow.search_runs() order_by=["metrics.auc DESC"]
open the tracking UI mlflow ui --backend-store-uri sqlite:///mlflow.db
Source of change Fix Record in metadata
random splits, bootstraps, initial weights seed every random step seed
library versions pin with == or a lock file sklearn_version, pandas_version, …
the data keep a snapshot data_sha256
which rows are in the test set hash split by a permanent id split rule
code and settings git and a config file model_version, git commit
import hashlib
import zlib
from importlib.metadata import version
print(version("scikit-learn")) # distribution name
print(hashlib.sha256(b"churn,0\n").hexdigest()[:12]) # same bytes, same hash
print([zlib.crc32(c.encode()) % 100 < 20 for c in ["C00001", "C00004"]]) # stable
Output
1.9.1
623f44273ead
[False, True]
Terminal
uv pip freeze > requirements.txt # pin every installed package
uv lock # or: a lock file for a pyproject.toml project
uv pip install -r requirements.txt # rebuild the environment elsewhere
Project layout
project/
├── config/train.toml # seeds, paths, hyperparameters
├── data/raw/ # read-only snapshots
├── data/processed/ # derived by scripts
├── models/ # bundles (not in git)
├── notebooks/ # exploration only
├── src/<package>/ # features.py, train.py, api.py
├── tests/ # pytest, TestClient
└── requirements.txt # pinned versions
Notebook Script or module
explore, plot, try ideas train, score, serve, monitor
cells in any order top to bottom, one command
results looked at by you results read by other programs
import hashlib
import json
from pathlib import Path
import joblib
import sklearn
from sklearn.dummy import DummyClassifier
model = DummyClassifier(strategy="prior").fit([[0], [1], [2], [3]], [0, 0, 0, 1])
metadata = {"model_version": "1.0.0", "trained_at": "2025-01-06",
"sklearn_version": sklearn.__version__, "features": ["x"]}
path = Path("models/demo.joblib")
path.parent.mkdir(exist_ok=True)
joblib.dump({"pipeline": model, "metadata": metadata}, path)
digest = hashlib.sha256(path.read_bytes()).hexdigest()
path.with_suffix(".json").write_text(json.dumps(metadata | {"bundle_sha256": digest}))
sidecar = json.loads(path.with_suffix(".json").read_text()) # plain JSON: safe
assert sidecar["sklearn_version"] == sklearn.__version__
assert hashlib.sha256(path.read_bytes()).hexdigest() == sidecar["bundle_sha256"]
bundle = joblib.load(path) # only after the checks pass
print(bundle["metadata"]["model_version"], bundle["pipeline"].predict_proba([[5]]))
Output
1.0.0 [[0.75 0.25]]
Metadata field Why
model_version logs, API responses and complaints refer to it
trained_at age of the model
data_sha256 which data trained it
sklearn_version and other versions pickles need the same versions
features exact inputs, in order
metrics baseline for monitoring
threshold how a probability becomes an action
app.py (shape)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
ml_models["churn"] = load_bundle(MODEL_PATH) # once, at start-up
yield
ml_models.clear()
app = FastAPI(title="Churn API", lifespan=lifespan)
@app.get("/health")
def health() -> Health: ... # status and model version
@app.post("/predict")
def predict(customer: Customer) -> Prediction: # body validated as Customer
row = pd.DataFrame([customer.model_dump()], columns=FEATURES)
...
pydantic tool Meaning
x: int type check, with lax conversion ("34" → 34)
Field(ge=0, le=120) inclusive range
Field(gt=0, lt=1) exclusive range
Field(min_length=1, max_length=100) length of a string or list
Field(pattern=r"^C\d{5}$") regular expression
Field(multiple_of=0.5) steps
Literal["a", "b"] exact allowed values
x: float | None = None optional
ConfigDict(extra="forbid") unknown fields are errors
ConfigDict(strict=True) no conversions at all
ConfigDict(allow_inf_nan=False) reject inf, -inf and NaN floats
Model.model_validate(d) validate a dict; raises ValidationError
obj.model_dump() back to a dict
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class Signup(BaseModel):
model_config = ConfigDict(extra="forbid")
age: int = Field(ge=18)
plan: Literal["basic", "premium"]
try:
Signup.model_validate({"age": 16, "plan": "gold", "promo": "X"})
except ValidationError as exc:
print([(e["loc"][0], e["type"]) for e in exc.errors()])
Output
[('age', 'greater_than_equal'), ('plan', 'literal_error'), ('promo', 'extra_forbidden')]
Status Meaning in an ML API
200 prediction returned
404 unknown resource (path parameter)
422 body failed validation; detail lists every error
500 the model or the code failed; log the cause, send a generic detail
503 service not ready (model not loaded)
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/double")
def double(body: Signup) -> dict[str, int]:
return {"double_age": body.age * 2}
with TestClient(app) as client: # runs the lifespan
ok = client.post("/double", json={"age": 30, "plan": "basic"})
bad = client.post("/double", json={"age": 30})
print(ok.status_code, ok.json(), bad.status_code, bad.json()["detail"][0]["type"])
Output
200 {'double_age': 60} 422 missing
Terminal
pytest -q test_app.py # after python train.py
pytest -v --no-header test_app.py # one line per test ID

Test status codes, ranges, orderings (“risky scores higher than loyal”) and invalid input. Do not assert exact probabilities.

Kind What changes Needs labels?
data drift (covariate shift) input distribution no
prediction drift score distribution, flag rate no
prior (label) shift class shares yes
concept drift input–target relation yes
PSI=∑i=1B(ci−ri) ln⁡ciriD=max⁡x∣Fref(x)−Fcur(x)∣\mathrm{PSI} = \sum_{i=1}^{B} (c_i - r_i)\,\ln\frac{c_i}{r_i} \qquad D = \max_x \left| F_{\text{ref}}(x) - F_{\text{cur}}(x) \right|
import numpy as np
from scipy.stats import ks_2samp
rng = np.random.default_rng(42)
reference = rng.normal(60, 25, 3000)
current = rng.normal(65, 25, 1000)
inner = np.quantile(reference, np.linspace(0, 1, 11))[1:-1] # reference deciles
r = np.bincount(np.searchsorted(inner, reference, side="right"), minlength=10) / 3000
c = np.bincount(np.searchsorted(inner, current, side="right"), minlength=10) / 1000
r, c = np.clip(r, 1e-4, None), np.clip(c, 1e-4, None)
print(f"PSI {np.sum((c - r) * np.log(c / r)):.3f}")
print(f"KS D {ks_2samp(reference, current).statistic:.3f}")
Output
PSI 0.057
KS D 0.097
PSI Reading Action
below 0.1 stable none
0.1–0.25 moderate look at the feature and its source
above 0.25 major investigate; consider retraining
Layer Measure Example alert
service requests, error rate, latency p95 latency above 200 ms
input quality 422 rate, missing values, unknown categories more than 2% rejected
drift PSI per feature, KS tests any PSI above 0.25
predictions score PSI, flag rate flag rate up by a third
performance ROC-AUC, recall once labels arrive 0.03 below the training metric
traceability model version on every logged prediction missing version
Tracking (MLflow 3.18)
logging.getLogger("mlflow").setLevel(logging.WARNING) # hide INFO lines
mlflow.set_tracking_uri("sqlite:///mlflow.db") # not file:./mlruns
mlflow.set_experiment("churn-baseline")
with mlflow.start_run(run_name="logreg-C1.0"):
mlflow.log_params({"C": 1.0, "seed": 42})
mlflow.log_metrics({"cv_auc_mean": 0.8126})
mlflow.set_tag("data_sha256", "7cb64d231768")
mlflow.sklearn.log_model(model, name="model", signature=signature,
pyfunc_predict_fn="predict_proba",
skops_trusted_types=["numpy.dtype"],
pip_requirements=["scikit-learn==1.9.1"])
runs = mlflow.search_runs(experiment_names=["churn-baseline"],
order_by=["metrics.cv_auc_mean DESC"])
best = mlflow.sklearn.load_model(f"runs:/{runs.iloc[0]['run_id']}/model")
Call Does
mlflow.set_tracking_uri(uri) where records go
mlflow.set_experiment(name) create or select an experiment
mlflow.start_run(run_name=...) one run; use it with with
log_param(s), log_metric(s), set_tag settings, results, labels
log_artifact(path) any file, such as a chart
mlflow.sklearn.log_model(...) a model with signature and requirements
mlflow.search_runs(...) runs as a DataFrame: params.*, metrics.*, tags.*
mlflow.sklearn.load_model(uri) the original pipeline
mlflow.pyfunc.load_model(uri) a generic predict() wrapper
  • hash("C00001") changes between Python processes. Use zlib.crc32 or hashlib for splits and buckets.
  • A random split with a fixed seed changes when rows are added. Use a hash split for test sets that must stay fixed.
  • pd.util.hash_pandas_object depends on row order. Sort by a key before you fingerprint.
  • A joblib file can run code when loaded. Load only files you created.
  • scikit-learn only warns (InconsistentVersionWarning) when versions differ. Check the version yourself and fail.
  • Without Literal, an unknown category becomes an all-zero one-hot row and the model predicts anyway.
  • Without extra="forbid", a misspelled optional field is silently ignored and its default is used.
  • Lax mode converts "yes" to True and "34" to 34. Use strict=True when that is not acceptable.
  • TestClient(app) without with does not run the lifespan: the model is never loaded.
  • uvicorn app:app resolves relative paths from the folder where you start it.
  • TestClient in Starlette 1.10 runs on the httpx2 package (pinned in the course requirements); without it, importing TestClient warns.
  • pydantic accepts "Infinity", "NaN" and 1e308 for a float by default. Use allow_inf_nan=False and an upper bound on every number.
  • A check that needs the unpickled bundle runs too late against a malicious file. Check the sidecar and the file hash before joblib.load().
  • The KS test assumes a continuous variable. For 0/1 flags, small counts and categories, use PSI on the values (or a chi-square test).
  • PSI needs bin edges from the reference data. With large samples, the KS test flags tiny shifts: decide on PSI or DD.
  • PSI can miss a level shift of a wide, skewed variable such as a house price. Also watch the median and the residuals.
  • MLflow 3.18 raises on file:./mlruns; use sqlite:///mlflow.db. Parameters come back from search_runs as strings.
  • MLflow prints INFO logs and download progress bars to stderr. Set the mlflow logger to WARNING and MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR=false.