Skip to content
Visual explainer 8h to learn 5 steps

ML capstone: ship, monitor and document the model

Package batch or API inference with tests and sample predictions, set monitoring thresholds, and publish a model card and rollback plan.

By Invicly Tech, , in AI and Machine Learning with Python. About 14 minutes to read.

Topic 34 of 34

In short

The last milestone turns the saved pipeline into something others can call: a batch scoring job or a small HTTP API with a written inference contract. You add tests that pin the contract and some recorded sample predictions, set monitoring thresholds with named owners, and publish a model card and a rollback plan. The capstone is done when another person could run, check and retire your model without asking you.

Think of it like this: It is like handing over a car: the keys are the API, the manual is the model card, the dashboard lights are the monitors and the spare wheel is the rollback plan.

Explained simply

A model on your laptop helps nobody. In this last step you package it so others can use it, write down exactly how to call it, test it, plan how to watch it and describe it honestly. You can ship it as a batch job that scores a file each night, or as a small web API that answers one request at a time.

The inference contract is the promise between the model and its callers. It lists every input field with its type and allowed values, what happens with missing or unknown values, and what comes back: the probability, the yes or no flag, the threshold behind it and the model version.

Tests protect that promise. They check that good input works, bad input is rejected and a few fixed sample tickets still get the same scores as when you recorded them. If an upgrade changes those scores, the test fails before users notice.

Monitoring tells you when the world changes. You watch errors and speed, the input data, the share of tickets flagged and, once true outcomes arrive, real recall. Finally you write a model card, a short honest description of the model, and a rollback plan for switching back to the previous version.

Press Play on a diagram to walk through it one step at a time.

SequenceOne prediction through the API
Caller
API
Pipeline
Log store
  1. 1POST /predict with ticket fields
    Caller to API: POST /predict with ticket fields
  2. 2Validate types and allowed values
    API to API: Validate types and allowed values
  3. 3predict_proba on one-row frame
    API to Pipeline: predict_proba on one-row frame
  4. 4Probability of breach
    Pipeline to API: Probability of breach
  5. 5Inputs, score, model version
    API to Log store: Inputs, score, model version
  6. 6Probability, flag, model version
    API to Caller: Probability, flag, model version
LayersWhat to monitor, from fast to slow
  1. 1
    Service health

    Errors, latency, request volume

  2. 2
    Input data

    Schema breaks, missing and unseen values, drift

  3. 3
    Predictions

    Score distribution and daily flag rate

  4. 4
    Outcomes

    Recall and precision once labels arrive

  5. 5
    Business effect

    Breaches avoided, reviewer workload

CycleLife of the model after launch
  1. 1
    Serve

    Batch job or API with version stamp

  2. 2
    Monitor

    Health, inputs, scores, outcomes

  3. 3
    Review

    Owner checks alerts weekly

  4. 4
    Retrain or roll back

    Based on written triggers

  5. 5
    Approve

    Beats baseline, card updated

  6. Back to step 1

In depth

Batch job or API

Ask how fast the answer is needed. If the support lead plans escalations each morning, a nightly batch job that reads new tickets and writes a scores file is enough. Batch jobs are easy to rerun, easy to audit and cheap. If the score must appear the moment a ticket is created, you need an online API, which brings uptime, latency and scaling concerns.

For the capstone, either is fine. A batch script and a FastAPI app can share the same pipeline file and contract. Packaging in a Docker image based on a slim Python image makes it run the same on any machine. Docker is free for personal use; if you cannot install it, a pinned virtual environment and a run script are an acceptable local alternative.

CompareBatch versus online inference
Batch
  • Scores many rows on a schedule
  • Minutes or hours of delay is fine
  • Easy to rerun and audit
  • Rollback: rerun with old model
Online API
  • One request, one answer
  • Needs low latency and uptime
  • Must validate every request
  • Rollback: switch the served version

Writing the inference contract

Write the contract as a short document and enforce it in code. For each input give the name, type, unit, allowed range or values and the missing-value rule; for example, queue_size is a whole number from 0 to 500, and an unseen channel is rejected rather than guessed. For outputs give breach_probability between 0 and 1, flag true when the probability is at or above the frozen threshold, and model_version.

Also state the intended latency or batch schedule, the expected volume and who to contact. In an API, a Pydantic model enforces types and ranges, and FastAPI returns status 422 for invalid input automatically. In a batch job, check columns and value ranges before scoring and stop with a clear message if they fail.

  • Inputs: name, type, unit, range, missing rule
  • Outputs: probability, flag, threshold, version
  • Reject unknown values rather than guess
  • State schedule or latency and an owner

Tests that protect the model

Use pytest with four kinds of test. Contract tests send valid input and check the response fields and types. Rejection tests send a negative queue size or an unknown channel and expect status 422. Sample prediction tests run a few fixed tickets and compare scores with values recorded when the model was approved, allowing a small tolerance such as 0.01. A quality smoke test scores a held-out sample and checks that PR AUC is still clearly above the baseline.

Run the tests in the Docker image you ship, not only on your laptop, so version mismatches show up early. FastAPI's TestClient needs the httpx package and runs the lifespan startup when used as a context manager.

  • Contract: fields and types
  • Rejection: bad input returns 422
  • Sample predictions within a tolerance
  • Quality smoke test above baseline

Monitoring thresholds with owners

Write each monitor as a rule: what is measured, how often, the threshold, the owner and the action. Examples for the ticket model: error rate above 1 percent over 15 minutes pages the service owner. Missing or unseen values above 2 percent of a day's rows alerts the data owner. Daily flag rate outside 5 to 20 percent triggers a review. Population stability index (PSI) for queue_size above 0.25 triggers investigation; 0.1 to 0.25 means watch. These PSI cut-offs are a common rule of thumb, not a standard.

Because breach labels arrive a day or more later, compute real recall weekly and retrain or roll back if it stays below 0.60 for two weeks. Tune every number to your own data after launch.

FlowFrom alert to action
  1. 1
    Monitor fires

    Rule, value and time logged

  2. 2
    Owner triages

    Data bug, real drift or noise?

  3. 3
    Decide

    Fix data, retrain or roll back

  4. 4
    Validate

    New model must beat baseline and current

  5. 5
    Record

    Update model card and changelog

Model card and rollback plan

The model card is a short document that travels with the model. Hugging Face's model card format is a good template: model details and owners, intended uses and out-of-scope uses, training data with its source and licence, evaluation with the baseline-vs-candidate table and slice results, limitations and risks, and how to get help. State clearly if the data is synthetic or results are illustrative.

The rollback plan names the trigger, the person who decides and the steps. Keep the previous model file and config available, select the served version with one setting such as a MODEL_PATH environment variable or image tag, and practise the switch once before launch. Note how long it took. A rollback you have never tried is only a hope.

  • Card: uses, data, evaluation, slices, limits, owners
  • Say when data is synthetic
  • Keep the previous version deployable
  • One setting switches versions
  • Rehearse the rollback once

Learn it in 5 short steps

About 1h 35m each. Track them with a timer in your plan.

  1. 1
    Package batch or API inference~1h 35m
  2. 2
    Add tests and sample predictions~1h 35m
  3. 3
    Write the inference contract~1h 35m
  4. 4
    Set monitoring thresholds~1h 35m
  5. 5
    Publish the model card and rollback plan~1h 35m

Key points

  • Choose batch scoring unless a caller truly needs an answer within seconds; batch is simpler to run and to roll back.
  • Write the inference contract first: field names, types, allowed values, missing-value rules, outputs and the threshold.
  • Pin behaviour with tests: schema checks, bad-input rejection and recorded sample predictions with a small tolerance.
  • Every monitor needs a threshold, a check frequency, an owner and an action, or nobody will act on it.
  • Keep the previous model version deployable, and write down who decides to roll back and how long it takes.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import json, sys, joblib, pandas as pd
MODEL_VERSION = 'sla-hgb-v1'
FIELDS = ['ticket_id', 'priority', 'channel', 'queue_size', 'agent_tenure_days']
pipe = joblib.load('model/model.joblib')
threshold = json.load(open('model/config.json'))['threshold']
df = pd.read_csv(sys.argv[1])
missing = set(FIELDS) - set(df.columns)
if missing:
    sys.exit(f'contract broken, missing columns: {sorted(missing)}')
out = df[['ticket_id']].copy()
out['breach_probability'] = pipe.predict_proba(df[FIELDS[1:]])[:, 1].round(3)
out['flag'] = out.breach_probability >= threshold
out['model_version'] = MODEL_VERSION
out.to_csv(sys.argv[2], index=False)
print(f'scored {len(out)} rows, flagged {int(out.flag.sum())}')

A batch scoring job: python score.py new_tickets.csv scores.csv. It refuses input that breaks the contract and stamps every row with the model version.

A small FastAPI service with the contract enforced

The model loads once at startup in the lifespan function and is kept on app.state. The Ticket model encodes the contract: allowed priority and channel values, and ranges for the numbers. Invalid input never reaches the model; FastAPI returns 422 with the reason. Run it with fastapi dev app/main.py or uvicorn app.main:app, then open http://127.0.0.1:8000/docs to try a request. Expected evidence: a JSON reply with a probability, a flag and the version. Stop the server with Ctrl+C to clean up.

python
from contextlib import asynccontextmanager
import joblib, pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.model = joblib.load('model/model.joblib'); yield
app = FastAPI(lifespan=lifespan)
class Ticket(BaseModel):
    priority: str = Field(pattern='^(low|normal|high|urgent)$'); channel: str = Field(pattern='^(email|chat|phone)$')
    queue_size: int = Field(ge=0, le=500); agent_tenure_days: int = Field(ge=0)
@app.post('/predict')
def predict(t: Ticket):
    p = float(app.state.model.predict_proba(pd.DataFrame([t.model_dump()]))[0, 1])
    return {'breach_probability': round(p, 3), 'flag': p >= 0.35, 'model_version': 'sla-hgb-v1'}

Pin the contract and sample predictions with pytest

The first test sends a recorded sample ticket and checks the response shape and the score against the value saved at approval time, with a tolerance of 0.02. The value 0.62 here is illustrative; record your own by calling the approved model once. The second test checks that a negative queue size is rejected with 422. Using TestClient as a context manager runs the lifespan, so the model is loaded. Prerequisites: pip install pytest httpx. Expected evidence: 2 passed.

python
from fastapi.testclient import TestClient
from app.main import app
SAMPLE = {'priority': 'urgent', 'channel': 'email', 'queue_size': 45, 'agent_tenure_days': 30}

def test_sample_prediction_and_contract():
    with TestClient(app) as client:
        body = client.post('/predict', json=SAMPLE).json()
    assert set(body) == {'breach_probability', 'flag', 'model_version'}
    assert abs(body['breach_probability'] - 0.62) < 0.02  # recorded at approval

def test_rejects_negative_queue():
    with TestClient(app) as client:
        r = client.post('/predict', json={**SAMPLE, 'queue_size': -1})
    assert r.status_code == 422

Quick reference

  • Default to batch scoring; use an API only when an answer is needed within seconds.
  • Contract: input names, types, ranges, missing rule; outputs probability, flag, threshold, version.
  • FastAPI plus Pydantic returns 422 for invalid input; load the model once in lifespan.
  • Tests: contract, rejection, sample predictions with tolerance, quality above baseline.
  • PSI rule of thumb: under 0.1 stable, 0.1 to 0.25 watch, over 0.25 investigate.
  • Every monitor: metric, frequency, threshold, owner, action.
  • Model card: uses, out-of-scope uses, data and licence, evaluation by slice, limits, owners.
  • Rollback: keep the old version, switch with one setting, rehearse before launch.

Common mistakes

  • Returning a bare probability with no model version, so nobody can tell which model produced a past decision.
  • Setting drift alerts with no owner or action, so they fire for weeks and get muted.
  • Deleting the old model file on deploy, which turns a two-minute rollback into a retraining project.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1The support lead reviews risky tickets once each morning. Which deployment fits best?

Question 2

2A caller sends channel set to fax, which the model never saw. What should the contract say?

Question 3

3Breach labels arrive two days after each ticket. Which monitor can alert on day one?

Question 4

4What is the purpose of recorded sample predictions in the tests?

Question 5

5Which item belongs in a rollback plan?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write the inference contract for your model as a short text document covering every input, every output, the threshold and an owner.

  2. Exercise 2medium

    Write a Dockerfile for the API, build it, run it and send one request with curl. Then remove the container and image.

  3. Exercise 3hard

    Implement a PSI check for queue_size that compares training data with a week of new tickets and prints stable, watch or investigate. Test it on synthetic drift where queue sizes rise by 30 percent.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need a cloud account to finish the capstone?
No. A batch script or a local FastAPI app in Docker is enough. Cloud deployment is optional and may cost money, so treat it as an extra once the local version works.
What is the difference between data drift and concept drift?
Data drift means the inputs change, for example queues get longer. Concept drift means the link between inputs and outcome changes, for example a new staffing rota makes long queues less risky. Only outcome monitoring catches concept drift.
How often should I retrain?
Retrain when a written trigger fires, such as recall below the agreed bar for two weeks or strong drift, rather than on a fixed timer by default. Every retrained model must beat both the baseline and the current model before it replaces it.
What should a capstone submission contain?
The data card and licence, model brief, split file and hash, leakage review, baseline-vs-candidate table, slice report, saved pipeline, inference contract, tests with sample predictions, monitoring plan, model card and rollback plan, all in one repository.

Go deeper

ShareXLinkedInWhatsApp