MLDay 46 of 50ML in Production
Serve a Model Behind an API
The credit-default model from Day 28 lives in a script.
The credit-default model from Day 28 lives in a script. The call-centre app needs a risk score while the agent is still on the phone, from fields someone just typed in. Until another program can call the model, it helps no one.
The idea
Serving a model means putting it behind an API: a web address that takes a request and sends back an answer. Two habits make it safe.
- Ship the whole pipeline. Save the cleaning steps and the model as one object, a scikit-learn
Pipeline(Day 11). The API then takes raw fields, and the cleaning runs exactly as it did in training. Saving the object to a file is serialization;joblibdoes it in one line. - Validate every request. A model never complains. Send it an age of −5 and it still returns a probability. So the API checks each field first and rejects a bad request with status 422, which names the field.
Then measure speed. Latency is the time one request takes. Report the p50 (the median call) and the p95 (95% of calls are at least this fast). Users notice the slow calls, and the mean hides them.
A tiny example
Ten calls, in milliseconds (ms): 12, 9, 11, 10, 13, 10, 9, 11, 48, 10. Sort them:
| Rank | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| Time (ms) | 9 | 9 | 10 | 10 | 10 | 11 | 11 | 12 | 13 | 48 |
The p50 is rank 5, 10 ms: a typical call. The p95 is rank 10, 48 ms: one call in ten was that slow. The mean, 14.3 ms, fits neither story. It's slower than 9 of the 10 calls, yet it hides the 48.
The formula
A percentile by nearest rank is one of the sorted times, picked by its position:
| Symbol | Meaning |
|---|---|
| the number of calls timed | |
| the share of calls that should be at least this fast: 0.5 for p50, 0.95 for p95 | |
| the -th fastest time, after sorting | |
| round up to a whole number |
Worked: for 100 calls, the p95 is , the 95th fastest. Five calls were slower. In the tiny example, , so with ten calls the p95 is simply the slowest one.
Try it
How wide is the slow tail?
500 requests with a typical time of 40 ms. p95 is the time 95% of requests beat; the slowest 5% take longer. Widen the spread and compare how far the median moves with how far p95 and p99 move.
p50 37 msp95 170.7 msp99 281.6 msp99 is 7.6× the median
4 slowest requests sit past the right edge. Percentiles use the nearest rank: p95 is the value at position ⌈0.95 × 500⌉ in sorted order.
Each bar counts requests by response time. σ, the spread (tail width), sets how far the slow ones stray. It starts at σ = 1.0: the p50 is 37.0 ms, but the p95 is 170.7 ms and the p99 281.6 ms. Say you promise a p95 under 100 ms. Drag σ down until the p95 drops under 100 ms (at 0.60 it is 95.5 ms). The median barely moves; only the tail shrinks.
In code
The script has three parts. First, rebuild the Day 28 model as one pipeline, save it, load it back and check that nothing changed. Day 44 made this training repeatable.
# script_id: day_046_serving_a_model/serve
import os
os.environ.setdefault("OMP_NUM_THREADS", "1") # one thread per prediction (see "Watch out"); set before sklearn loads
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
MODEL_DIR = Path(os.environ.get("ML_MODEL_DIR", Path(__file__).parent)) # next to the script
df = pd.read_csv(DATA_DIR / "credit_default" / "default_of_credit_card_clients.csv")
df = df.drop(columns="ID").rename(columns={"default payment next month": "default"})
X, y = df.drop(columns="default"), df["default"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
def clean(X):
X = X.copy()
X["EDUCATION"] = X["EDUCATION"].replace({0: 4, 5: 4, 6: 4}) # unknown codes -> 4, "others"
X["MARRIAGE"] = X["MARRIAGE"].replace({0: 3}) # unknown code -> 3, "others"
return X.astype(float)
pipe = make_pipeline(FunctionTransformer(clean), HistGradientBoostingClassifier(random_state=42))
pipe.fit(X_train, y_train) # raw columns in: the cleaning is part of the model
path = MODEL_DIR / "credit_model.joblib"
joblib.dump(pipe, path)
model = joblib.load(path) # only ever load files you made yourself
p = model.predict_proba(X_test)[:, 1]
print(f"{path.name}: {path.stat().st_size / 1024:.0f} KB")
print("same predictions after loading:", np.array_equal(p, pipe.predict_proba(X_test)[:, 1]))
print(f"test PR-AUC {average_precision_score(y_test, p):.3f}")
credit_model.joblib: 256 KB
same predictions after loading: True
test PR-AUC 0.551
The loaded pipeline scores the test set exactly like Day 28: PR-AUC 0.551. joblib.load runs whatever code
the file asks it to, so never load a pickle or joblib file from a source you don't trust. Two more limits:
the file stores clean by name, not its code, so the serving program must define or import the same function.
And load it with the same scikit-learn version that saved it; a different one warns you.
Second, the API. FastAPI turns a Python function into an endpoint. A Pydantic model describes the
request: each field's type and allowed range. Literal[1, 2] allows only those values;
Annotated[int, Field(...)] attaches a range to a type so a list can reuse it. FastAPI checks every request against it before your code runs.
# script_id: day_046_serving_a_model/serve
from contextlib import asynccontextmanager
from typing import Annotated, Literal
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field
Status = Annotated[int, Field(ge=-2, le=9)] # repayment status: -2 to 0 on time, 1 to 9 months late
Paid = Annotated[float, Field(ge=0)] # an amount paid can't be negative
class Client(BaseModel):
model_config = ConfigDict(extra="forbid") # reject fields we don't know
limit_bal: float = Field(gt=0)
sex: Literal[1, 2]
education: int = Field(ge=0, le=6)
marriage: int = Field(ge=0, le=3)
age: int = Field(ge=18, le=100)
pay: list[Status] = Field(min_length=6, max_length=6) # latest month first
bill_amt: list[float] = Field(min_length=6, max_length=6) # negative = the bank owes the client
pay_amt: list[Paid] = Field(min_length=6, max_length=6)
def to_frame(self) -> pd.DataFrame: # the training columns, in the training order
row = {"LIMIT_BAL": self.limit_bal, "SEX": self.sex, "EDUCATION": self.education,
"MARRIAGE": self.marriage, "AGE": self.age}
row |= dict(zip(["PAY_0", "PAY_2", "PAY_3", "PAY_4", "PAY_5", "PAY_6"], self.pay))
row |= {f"BILL_AMT{i}": v for i, v in enumerate(self.bill_amt, 1)}
row |= {f"PAY_AMT{i}": v for i, v in enumerate(self.pay_amt, 1)}
return pd.DataFrame([row])
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.model = joblib.load(path) # load once at startup, not on every request
yield
app = FastAPI(lifespan=lifespan)
@app.post("/predict")
def predict(client: Client) -> dict:
risk = app.state.model.predict_proba(client.to_frame())[0, 1]
return {"default_probability": round(float(risk), 3)}
The request's names needn't match the training columns, but to_frame must rebuild them exactly. A
mismatch there is train–serving skew
(Day 45): the model sees different inputs
in production than in training.
Third, call it. TestClient sends real HTTP requests to the app inside the same process, so no server is needed.
It sends one good request, one bad one and 100 timed calls.
# script_id: day_046_serving_a_model/serve
import time
from fastapi.testclient import TestClient
good = {"limit_bal": 50000, "sex": 2, "education": 2, "marriage": 1, "age": 35,
"pay": [2, 2, 0, 0, 0, 0], "bill_amt": [48000, 47000, 46000, 30000, 29000, 28000],
"pay_amt": [0, 1500, 1500, 1200, 1100, 1000]}
raw = Client(**good).to_frame().assign(AGE=-5)
print(f"model alone, age -5: {model.predict_proba(raw)[0, 1]:.3f}")
with TestClient(app) as http: # "with" runs the lifespan, so the model is loaded
r = http.post("/predict", json=good)
print(r.status_code, r.json())
r = http.post("/predict", json=good | {"age": -5, "pay": [0, 0, 0]})
print(r.status_code, [(e["loc"][-1], e["msg"]) for e in r.json()["detail"]])
ms = []
for _ in range(100):
start = time.perf_counter()
http.post("/predict", json=good)
ms.append((time.perf_counter() - start) * 1000)
p50, p95 = np.percentile(ms, [50, 95], method="inverted_cdf") # nearest rank, as above
print(f"100 calls: p50 {p50:.1f} ms, p95 {p95:.1f} ms, slowest {max(ms):.1f} ms")
model alone, age -5: 0.618
200 {'default_probability': 0.646}
422 [('age', 'Input should be greater than or equal to 18'), ('pay', 'List should have at least 6 items after validation, not 3')]
100 calls: p50 1.9 ms, p95 2.3 ms, slowest 2.5 ms
The client is two months late, and the API returns 0.646. Alone, the model scores the same client at age −5 as
0.618, with no complaint. The API refuses it, along with the three-month pay list, and names both fields. Your
times will differ from run to run; the p95 is the one to watch.
Quick check
Quick check
1. Why save the whole pipeline, not just the boosting model?
2. A request arrives with age = −5. What does the pipeline alone do?
3. 100 calls give p50 = 3 ms and p95 = 40 ms. What does the p95 tell you?
Next
Day 47: Detect Drift watches the requests this API receives, so you notice when the clients stop looking like the training data.
Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).