Sub topic 17
Monitoring, drift and retraining
This chapter assumes you can build and evaluate a scikit-learn pipeline, and that you have read the chapters on pipelines, final evaluation and prediction. A model that passed its final test evaluation is not finished. The test score describes how the model performed on data from the past. After deployment, the world keeps changing, and the model does not.
Why a deployed model degrades
A trained model is a frozen summary of the training data. It stays correct only while new data resembles that sample. Three things commonly break the resemblance:
- Customers, sensors, or markets change their behavior.
- An upstream system changes how it records a field, for example switching a unit from dollars to cents.
- Your own product changes, so the model's predictions alter the data it later sees.
Degradation is often silent. The model still returns a number for every row, and no exception is raised. A pipeline that predicts nonsense looks the same as one that predicts well, unless you measure.
Types of drift
Drift is a change between the data the model was trained on and the data it now receives. Three kinds matter in practice.
| Kind | What changes | Example | How you detect it |
|---|---|---|---|
| Data drift (covariate shift) | The distribution of inputs, P(X) | The average customer age rises | Compare input distributions |
| Label drift (prior shift) | The share of each class, P(y) | Fraud rate doubles | Compare predicted or true label rates |
| Concept drift | The relationship between inputs and target, P(y given X) | The same income and age now predict a different default risk after a rate change | Track performance against true labels |
Data drift does not always hurt accuracy. If the inputs shift into a region where the model is still accurate, the score may hold. Concept drift always hurts, because the learned rule is now wrong. This is why input monitoring alone is not enough.
What to monitor
Monitor at four levels, from cheapest to most informative.
- Data quality. Check for missing values, new categories, out-of-range values, and schema changes. These are the most common cause of real incidents, and they are easy to catch.
- Input distributions. Compare each feature in recent data against the training data.
- Prediction distributions. Track the mean predicted probability and the share of each predicted class. A sudden change is a warning even before labels arrive.
- Model performance. Compute your chosen metric from true labels. This is the only direct measure of quality.
The difficulty with level 4 is label delay. A loan default may be known only after a year. Until labels arrive, you rely on levels 1 to 3 as early warnings. Plan how you will collect labels, even a sample of them, before you deploy.
Detecting drift in code
A simple, widely used check compares a feature's training values to recent values with a two-sample Kolmogorov-Smirnov test. The test asks whether two samples plausibly come from the same distribution. The code below simulates a shift in one feature and flags it.
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_new, y_train, y_new = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=42
)
# Simulate drift: one feature is now measured 20 percent higher.
X_new = X_new.copy()
X_new["mean radius"] = X_new["mean radius"] * 1.2
def drift_report(reference, current, alpha=0.01):
rows = []
for col in reference.columns:
stat, p_value = ks_2samp(reference[col], current[col])
rows.append({"feature": col, "ks_stat": stat, "p_value": p_value})
report = pd.DataFrame(rows)
report["drifted"] = report["p_value"] < alpha
return report.sort_values("ks_stat", ascending=False)
report = drift_report(X_train, X_new)
print(report.head(5).to_string(index=False))
print("features flagged:", int(report["drifted"].sum()))The output ranks features by the KS statistic, which is the largest gap between the two cumulative distributions. The shifted feature, mean radius, appears at the top.
A second common measure is the Population Stability Index (PSI). It bins a feature and sums the differences in bin shares. A common rule of thumb treats PSI below 0.1 as stable, 0.1 to 0.25 as a moderate shift, and above 0.25 as a major shift. These cut-offs are conventions, not laws, so calibrate them on your own data.
A monitoring loop
Monitoring is a repeating process, not a single check. The diagram shows the loop that connects the pieces of this chapter.
Log enough to reconstruct each prediction: the input row, the model version, the output, and a timestamp. Without that record you cannot join predictions to labels later, and you cannot debug an incident.
Deciding when to retrain
Retraining has a cost in compute, review time, and risk. Three triggers are common.
- Schedule. Retrain weekly or monthly. This is simple and predictable, and it suits domains with steady change.
- Performance. Retrain when the live metric falls below a set threshold. This is the most direct trigger, but it depends on labels arriving.
- Drift. Retrain when input or prediction distributions move past a threshold. This reacts before labels arrive, but it can fire when the shift is harmless.
Many teams combine a schedule with alerts. Before acting on an alert, investigate. A drift alert caused by a broken upstream feed needs a data fix, and retraining on the broken data makes things worse.
Retraining safely
Retraining repeats the whole workflow, so all earlier rules still apply. Several points deserve extra care.
- Re-split by time. For data with a time order, train on older rows and validate on newer rows. A random split lets the model see the future and inflates the score.
- Choose the window. Training on all history keeps rare patterns but dilutes recent behavior. A rolling window adapts faster but can forget rare events. Try both and compare on recent validation data.
- Compare against the current model. Evaluate the candidate and the production model on the same recent holdout. Deploy only if the candidate is better by a margin you set in advance.
- Keep a fresh test set. If you reuse the same test set on every retraining cycle, you tune to it over time. Refresh it with recent labeled data.
- Version everything. Store the model, the code, the training data snapshot or its hash, and the metrics. You need to roll back quickly if the new model misbehaves.
The next code block shows a champion and challenger comparison on a recent holdout. The champion is the model in production, and the challenger is the retrained candidate.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
# Treat row order as time: old rows, then recent rows.
old_X, old_y = X.iloc[:300], y.iloc[:300]
recent_X, recent_y = X.iloc[300:500], y.iloc[300:500]
holdout_X, holdout_y = X.iloc[500:], y.iloc[500:]
def make_model():
return Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
champion = make_model().fit(old_X, old_y)
challenger = make_model().fit(
X.iloc[:500], y.iloc[:500]
) # old plus recent rows
champ_f1 = f1_score(holdout_y, champion.predict(holdout_X))
chall_f1 = f1_score(holdout_y, challenger.predict(holdout_X))
print("champion F1: ", round(champ_f1, 3))
print("challenger F1:", round(chall_f1, 3))
MARGIN = 0.01
print("deploy challenger:", chall_f1 > champ_f1 + MARGIN)Common errors
- Monitoring only uptime. A service can be healthy while its predictions are wrong. Monitor the data and the outputs, not only latency and errors.
- Training-serving skew. The deployed code transforms features differently from the training code. Using one saved pipeline for both avoids this, as covered in the pipelines chapter.
- Feedback loops. If predictions decide which cases get labeled, such as only approved loans having outcomes, the new labels are biased. Reserve a random sample for unbiased labels where you can.
- Alert fatigue. Too many thresholds that fire on harmless noise train people to ignore alerts. Start with a few that map to real decisions.
- Retraining automatically without checks. An automated job that deploys whatever it trains can ship a broken model. Gate deployment on validation.
Exercise
Your fraud model's input features look stable, but the share of confirmed fraud among flagged cases has dropped steadily over three months. Which kind of drift is most likely, and which monitoring level exposed it?
Show answer
Concept drift is most likely. The inputs are stable, so data drift is unlikely, but the relationship between inputs and fraud has changed, for example because fraudsters changed tactics. Performance monitoring against true labels (level 4) exposed it, which input distribution checks alone would have missed.
Exercise
A team retrains monthly using a random train and test split of all data collected so far, and reports that each new model beats the old one. Name two problems and a fix for each.
Show answer
First, a random split on time-ordered data lets the model train on rows from after some test rows, which inflates scores. Fix it by training on older data and validating on newer data. Second, the same test set is reused every cycle, so the team gradually tunes to it. Fix it by refreshing the test set with recent labeled data and comparing the candidate and current model on the same fresh holdout.