Skip to content

Expert: deep learning and AI · Building with generative AI, and MLOps · topic 57 of 62 · 35 min

MLOps: from notebook to production

Explanation

MLOps is the practice of running ML models reliably in production: versioning code, data and models, tracking experiments, packaging and serving models, monitoring their inputs and accuracy, and retraining when the world changes. A model is not finished when it scores well in a notebook; that is where its working life begins.

Why MLOps?

Many ML projects never reach users, and many that do quietly get worse over time. The causes are rarely the algorithm: nobody can reproduce last month's model, the live data differs from training data, or nobody notices that accuracy dropped after a festival season. MLOps borrows ideas from DevOps (automation, testing, monitoring) and adds the parts that are special to ML: data and models change too.

The ML lifecycle

  1. Data: collect, validate and version the training data.
  2. Experiment: train models and record every run's code version, data version, settings and scores.
  3. Package: save the model with its preprocessing (one pipeline) and its exact library versions.
  4. Deploy: serve predictions as an API (real time) or as scheduled jobs (batch).
  5. Monitor: watch service health, input data and, when labels arrive, real accuracy.
  6. Retrain: on a schedule or when monitoring says so, then evaluate and redeploy safely.

Versioning and experiment tracking

Code goes in Git. Data and model files are too large for Git, so tools such as DVC store versions of them elsewhere while Git keeps small pointers. Experiment trackers such as MLflow record parameters, metrics and the model file for every run, and a model registry marks which version is in staging and which is in production. The goal: anyone can answer "exactly which data and code produced the model that made this prediction?"

Serving: batch and real time

Batch prediction scores many rows on a schedule, such as every night computing churn risk for all customers. Real-time serving answers each request in milliseconds, such as a fraud score during a UPI payment. Real-time models are often wrapped in a small web API.

python
from fastapi import FastAPI
from pydantic import BaseModel
import joblib

app = FastAPI()
model = joblib.load("churn_pipeline.joblib")      # preprocessing + model, saved together

class Customer(BaseModel):
    tenure_months: int
    monthly_bill: float
    complaints_90d: int

@app.post("/predict")
def predict(c: Customer):
    p = model.predict_proba([[c.tenure_months, c.monthly_bill, c.complaints_90d]])[0][1]
    return {"churn_probability": round(float(p), 3)}
A minimal real-time prediction API with FastAPI. Run it with uvicorn and put it in a Docker container for deployment. Shown only.

Monitoring: drift

Data drift means the inputs change: a new city launches, prices rise, a festival changes shopping. Concept drift means the relationship between inputs and the target changes: what used to signal fraud no longer does because fraudsters adapted. Monitor input distributions (for example, compare the mean of a feature with its training mean, or use the population stability index, PSI), prediction distributions, and real accuracy when labels arrive. Alert when they move beyond agreed thresholds.

PSI compares the share of values in each bin between training (expected) and live (actual) data: PSI = Σ (actual − expected) × ln(actual ÷ expected). A common rule of thumb reads below 0.1 as little change, 0.1–0.25 as moderate and above 0.25 as a big shift, but agree thresholds for your own use case.

CI/CD for ML

Automate: tests for data (no missing ids, values in range), tests for code, an evaluation gate (the new model must beat the current one on the test set), and safe rollout such as shadow mode (the new model predicts silently alongside the old one) or a canary (a small share of traffic first). Keep the old model ready for a quick rollback.

Common mistakes

  • Different preprocessing in training and serving ("training-serving skew"). Fix: ship one pipeline.
  • No monitoring, so a broken input feed goes unnoticed for weeks.
  • Retraining automatically on bad data without an evaluation gate.
  • Not recording which model version made which prediction.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

MLOps: from notebook to production · 1/7

MLOps

A model's working life starts after the notebook. MLOps keeps it reliable in production.

Prefer a video by a teacher? Find free videos on “MLOps explained model deployment monitoring data drift MLflow” on YouTube ↗

In real life: A fraud model after a big sale

During a nationwide shopping festival, a payments company's fraud model starts flagging many more transactions. Monitoring shows the input distribution shifted sharply: far more first-time buyers and higher amounts (PSI above 0.25 on two features). The team raises the review threshold temporarily, labels a sample of flagged payments, retrains with festival data included, checks it against the evaluation gate and rolls it out to 5% of traffic before going fully live.

Practice (0/2 done)

Task 1 · Code · Python

Write mean_drift(train_mean, train_sd, live_values, threshold) that returns True when the live mean has moved more than `threshold` training standard deviations: abs(mean(live_values) − train_mean) / train_sd > threshold. Return False if live_values is empty.

Task 2 · Code · Python

Write psi(expected, actual) for two lists of bin proportions (each sums to about 1). Replace any proportion below 0.0001 with 0.0001, then return Σ (a − e) × ln(a / e) over the bins, rounded to 4 decimal places.

Quick quiz

Question 1

1.What is training-serving skew?

Question 2

2.Fraudsters change their tactics so old signals stop working. This is…

Question 3

3.What does an experiment tracker like MLflow record?

Question 4

4.What is a canary release?

Question 5

5.Which prediction style fits "score every customer's churn risk each night"?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is training-serving skew?

Answer: Data processed differently in training and in production

Shipping one saved pipeline prevents it.

Fraudsters change their tactics so old signals stop working. This is…

Answer: Concept drift

The relationship between inputs and the target changed.

What does an experiment tracker like MLflow record?

Answer: Each run's parameters, metrics, code/data versions and artefacts

It makes results reproducible and comparable.

What is a canary release?

Answer: Sending a small share of traffic to the new model first

Problems show up on a small share before everyone is affected.

Which prediction style fits "score every customer's churn risk each night"?

Answer: Batch prediction

Scheduled scoring of many rows is batch.

97% of transactions are not fraud. A model has 97% accuracy. What should you conclude?Related

Answer: It may be no better than always predicting "not fraud"

The majority-class baseline already scores 97%.

From The ML workflow end to end

Who mainly builds RAG and LLM-based product features?Related

Answer: AI engineer

AI engineers build on pre-trained models and APIs.

From Career paths: analyst, scientist, ML engineer, AI engineer

When is ML a poor choice?Related

Answer: When a simple exact formula already solves the problem

A formula like GST needs no model; ML adds cost and risk for no gain.

From What machine learning is

Roughly how much memory do the weights of a 13-billion-parameter model need in float16?Related

Answer: 26 GB

13 × 10⁹ × 2 bytes ≈ 26 GB.

From Deep learning tools and hardware

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Building with generative AI, and MLOps”. The module exam comes next.
  2. Module 11 exam: Building with generative AI, and MLOps · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Ethics, privacy and careers. 62 topics left in the course before the final exam.

← Previous: AI safety and responsible deployment