Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathMonitor and Improve a Model in Production
  1. 1
    Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
  2. 2
    Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
  3. 3
    Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
  4. 4
    A/B Tests for Models: Did the New Model Make Things Better for People?
  5. 5
    When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
  6. 6
    Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
  7. 7
    The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
  8. 8
    Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. MLOps and Production ML

Learning path: Monitor and Improve a Model in Production · Step 1 of 8

Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change

A ticket priority model slips while its code stays the same. Compare old and new tickets with PSI and an Evidently report, score the model on fresh labels, retrain with half of the new batch and run the seven-step monitoring loop.

Chaand Sheikh

·27 November 2026Monitoring and Release

What you will learn

  • Explain why a model can get worse when nobody changes the code
  • Compare training data with a newer batch using shares, means and a hand-made PSI
  • Produce a drift report with Evidently and read which columns moved
  • Measure the model on fresh labels, retrain with new data and check the score again

Before you start

  • MLOps in One Picture
  • Pipelines and ColumnTransformer

Our support team has a model that sets the priority of each ticket, low or high. It has been running for months and everyone was happy. Then the complaints start going up.

So people check the code. Same model file, same pipeline, same deploy. Nothing changed there. But look at the tickets: more of them now arrive by chat, and the customers sound angrier than before. Urgent tickets get a low priority, and the people waiting aren't happy.

The model learned from old tickets. When new tickets look different, its old habits stop fitting. The code is fine. The data moved. That's drift, and you saw it in one picture in MLOps in One Picture. Here we catch it in code and fix it.

Think of a drifting compass

A ship's compass is set properly at the harbour. On a long trip it slowly starts to point a little wrong. Nobody touched it. It just drifts.

A good captain checks the compass against the stars, a fresh and trusted reference, and recalibrates it before the ship is lost. A model works the same way:

  • Watch the data: compare what comes in now with what the model learned from.
  • Measure the model on fresh labels, the real answers once they are known.
  • Retrain when the score slips.

The project has four scripts, one for each step below. All the data is synthetic support tickets: tickets.csv is the old training data and tickets_live.csv is a newer batch that already has the right answers.

Step 1: compare old and new data with PSI

The simplest check puts the two sets side by side. 01_compare.py prints a few plain numbers and a PSI (population stability index) for each numeric column.

from pathlib import Path

import numpy as np
import pandas as pd

DATA = Path(__file__).parent / "data"
train = pd.read_csv(DATA / "tickets.csv")
live = pd.read_csv(DATA / "tickets_live.csv")


def psi(old, new, bins=10):
    # Rule of thumb: PSI > 0.2 means a big shift
    edges = np.quantile(old, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    a = np.histogram(old, edges)[0] / len(old)
    b = np.histogram(new, edges)[0] / len(new)
    a, b = np.clip(a, 1e-4, None), np.clip(b, 1e-4, None)
    return float(np.sum((b - a) * np.log(b / a)))


chat = lambda df: round((df.channel == "chat").mean(), 3)
high = lambda df: round((df.priority == "high").mean(), 3)
print("chat share      ", chat(train), "->", chat(live))
print("mean sentiment  ", round(train.sentiment.mean(), 3), "->", round(live.sentiment.mean(), 3))
print("high priority   ", high(train), "->", high(live))
for col in ["words", "previous_tickets", "hour", "sentiment"]:
    print(f"PSI {col:<17}", round(psi(train[col], live[col]), 3))
chat share       0.298 -> 0.578
mean sentiment   0.097 -> -0.352
high priority    0.458 -> 0.604
PSI words             0.02
PSI previous_tickets  0.024
PSI hour              0.036
PSI sentiment         1.1

The psi function cuts the old values into ten equal bins (each holds about a tenth of the old rows), then counts how many of the new values land in each bin. The more the shares differ, the bigger the PSI. The comment gives the rule of thumb: above 0.2 is a big shift, below 0.1 is steady.

Now read the output. The chat share went from about 30% to about 58%. The average sentiment went from slightly positive, 0.097, to −0.352. The share of high priority tickets went up too. Words, previous tickets and hour have small PSI values, but sentiment is 1.1, far above 0.2. That one column changed a lot.

PSI per column: only sentiment crosses 0.2 words 0.02 previous_tickets 0.024 hour 0.036 sentiment 1.1 0.2 rule of thumb 0 0.5 1.0 PSI, training tickets vs newer batch
Output of 01_compare.py on the synthetic tickets. Three columns stay near zero; sentiment is 1.1.

Step 2: let Evidently write a drift report

Doing it by hand is good for understanding. In a bigger project you can let a library do the comparing for every column. 02_drift_report.py uses Evidently:

from pathlib import Path

import pandas as pd
from evidently import Report
from evidently.presets import DataDriftPreset

DATA = Path(__file__).parent / "data"
columns = ["channel", "customer_tier", "product_area", "words",
           "has_attachment", "previous_tickets", "hour", "sentiment"]
train = pd.read_csv(DATA / "tickets.csv")[columns]
live = pd.read_csv(DATA / "tickets_live.csv")[columns]

snapshot = Report([DataDriftPreset()]).run(live, train)
snapshot.save_html(str(Path(__file__).parent / "drift_report.html"))

result = snapshot.dict()["metrics"]
count = result[0]["value"]
print("drifted columns:", int(count["count"]), "of", len(columns), "| share", round(count["share"], 2))
for metric in result[1:]:
    cfg = metric["config"]
    if metric["value"] > cfg["threshold"]:
        print("  drifted:", cfg["column"], round(metric["value"], 3))
drifted columns: 3 of 8 | share 0.38
  drifted: hour 0.127
  drifted: sentiment 1.027
  drifted: channel 0.202

In .run(live, train) the newer tickets are the current data and the training tickets are the reference. save_html writes drift_report.html, which you open in a browser to see every column with its chart.

Three of eight columns drifted: hour, sentiment and channel. Sentiment is the biggest by far, which matches our PSI. Channel is there too, which matches the chat share. Two different tools tell the same story. (Evidently's scores are on their own scale, so don't compare them number for number with the hand-made PSI. The next article, Drift Detection in Code, takes PSI apart and adds a KS test.)

Step 3: did the model actually get worse?

Drift in the data is a warning. What we really care about is whether the model got worse. 03_model_on_live.py trains once on the old training split, then scores the same model on the old test tickets and on the newer batch, which comes with the true priority.

from pathlib import Path

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

from features import categorical, load, make_pipeline, numeric

X_train, X_test, y_train, y_test = load()
model = make_pipeline(RandomForestClassifier(n_estimators=200, random_state=42))
model.fit(X_train, y_train)

live = pd.read_csv(Path(__file__).parent / "data" / "tickets_live.csv")
X_live = live[categorical + numeric]
y_live = (live["priority"] == "high").astype(int)

old_score = accuracy_score(y_test, model.predict(X_test))
live_score = accuracy_score(y_live, model.predict(X_live))
print("accuracy on old test tickets:", round(old_score, 3))
print("accuracy on live tickets    :", round(live_score, 3))
print("drop                        :", round(old_score - live_score, 3))
accuracy on old test tickets: 0.658
accuracy on live tickets    : 0.642
drop                        : 0.016

load() and make_pipeline() live in the project's features.py: a stratified 75/25 split and a ColumnTransformer that one-hot encodes the three text columns (see Pipelines and ColumnTransformer).

The score fell by 0.016 and we changed no code at all. This sample data is noisy, so the dip is small here. The direction is what matters. In a bigger system the slide can be much larger, and you'd never see it unless you measured.

Step 4: retrain with some of the new tickets

The score slipped, so we retrain with fresh data. 04_retrain.py splits the newer batch in half: one half for learning, the other half kept back only for scoring. Same random_state, so the split is the same every run.

from pathlib import Path

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

from features import categorical, load, make_pipeline, numeric

X_train, X_test, y_train, y_test = load()
live = pd.read_csv(Path(__file__).parent / "data" / "tickets_live.csv")
X_live = live[categorical + numeric]
y_live = (live["priority"] == "high").astype(int)
X_new, X_check, y_new, y_check = train_test_split(
    X_live, y_live, test_size=0.5, random_state=42, stratify=y_live)

old_model = make_pipeline(RandomForestClassifier(n_estimators=200, random_state=42))
old_model.fit(X_train, y_train)
print("before retraining:", round(accuracy_score(y_check, old_model.predict(X_check)), 3))

new_model = make_pipeline(RandomForestClassifier(n_estimators=200, random_state=42))
new_model.fit(pd.concat([X_train, X_new]), pd.concat([y_train, y_new]))
print("after retraining :", round(accuracy_score(y_check, new_model.predict(X_check)), 3))
print("old test tickets :", round(accuracy_score(y_test, new_model.predict(X_test)), 3))
before retraining: 0.628
after retraining : 0.644
old test tickets : 0.664

The old model scores 0.628 on the kept-back half. That's the before number. A fresh model with the same settings, trained on the old tickets plus the new half, scores 0.644 on tickets it never saw. And on the old test tickets it still scores 0.664, so it didn't forget the past.

Small, but the right direction, and it came from fresh data, not from a code change.

The monitoring loop

Doing this once is nice. A working system needs a routine, not a rescue:

The seven-step monitoring loop 1. Log predictions 2. Compare data PSI or report 3. Get fresh labels 4. Score the model 5. Retrain 6. Register the version 7. Deploy Drift (2) is the early warning. A falling score (4) is the proof.
A routine, not a rescue: the loop runs every week or so, and retraining happens only when the score shows it's needed.
  1. Log the predictions. Save the inputs and the answers the model gave.
  2. Compare the data, maybe every week. PSI or a drift report will do.
  3. Get fresh labels: the true answers once they are known. For a ticket, that could be the priority the support agent finally chose.
  4. Score the model on those new labels.
  5. Retrain with the old data plus the new data.
  6. Register the new version, for example in MLflow, which keeps the history of every version (MLflow Model Registry Aliases).
  7. Deploy it. Swap the new model in.

Drift in the data is the early warning. A falling score is the proof. Retrain only when you can show it, because retraining has a cost too.

Common mistakes

  • Checking the code first and stopping there. A model can get worse with nothing in the code changing. Look at the data.
  • Treating drift as proof. Drift says the inputs moved. Only a score on fresh labels says the model got worse.
  • Scoring the retrained model on the rows it learned from. Keep part of the new batch back, as 04_retrain.py does, or the "after" number means nothing.
  • Forgetting the old data. Check the retrained model on the old test tickets too, so a fix for new tickets doesn't break old ones.

Recap

StepScriptWhat it showed
Compare data01_compare.pyChat 0.298 → 0.578, sentiment PSI 1.1
Drift report02_drift_report.py3 of 8 columns: hour, sentiment, channel
Model on live03_model_on_live.py0.658 → 0.642, with no code change
Retrain04_retrain.py0.628 → 0.644 on kept-back tickets; old tickets 0.664

Try it yourself

  1. Run the four files and open drift_report.html in a browser.
  2. Edit make_tickets.py to make fewer chat tickets and calmer customers, then run everything again. Which numbers fall back?
  3. Retrain with only a quarter of the new batch and compare the score.

The project files and sample data for this lesson are in the community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
Next →
Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Python Virtual Environments: One Project, One Toolbox

Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.

Git and GitHub Fundamentals: Commits, Branches, Push and Pull

The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.

Testing a FastAPI App with pytest: Three Small Tests

A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.

Config and Logging Instead of Hard-Coded Values in ML Training

Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.

On this page
  • Think of a drifting compass
  • Step 1: compare old and new data with PSI
  • Step 2: let Evidently write a drift report
  • Step 3: did the model actually get worse?
  • Step 4: retrain with some of the new tickets
  • The monitoring loop
  • Common mistakes
  • Recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.