Reading history

Data Drift and Model Monitoring in Python

7 min read 1 views

Learn data drift and concept drift in Python: measure drift with PSI, the KS test and adversarial validation, and plan model monitoring.

A model is trained on the past but used in the future. The world keeps changing: prices rise, customers change habits, a new law changes the rules. Slowly, the data your model sees stops looking like the data it learned from. This is called drift. In this lesson you will measure drift with simple tests and learn why some kinds of drift can hide from them.

In this lesson you will learn

  • The difference between data drift and concept drift
  • How to measure drift in one column with PSI and the KS test
  • Why the KS test raises alarms too easily on big data
  • How adversarial validation checks all columns at once
  • What to monitor after a model goes live

You should know train-test split, ROC AUC and saving a model.

Two Kinds of Drift

  • Data drift (also called covariate shift): the inputs change. Example: average applicant income rises after a pay rise across the country.
  • Concept drift: the link between inputs and the answer changes. Example: after a price shock, people with the same income now repay loans less often.

Data drift can be seen in the inputs alone. Concept drift often cannot. You only notice it when the true outcomes arrive and the model’s accuracy has fallen.

Data drift: inputs move0255075100Monthly income (k taka)trainingJulyConcept drift: the rule moves025507510000.51Monthly income (k taka)Chance of repayingold rulenew rule

Checking One Column: PSI and KS

The Population Stability Index (PSI) splits a column into 10 bins using the training data. It then compares what share of new values falls in each bin. Banks have used it for years. A common rule of thumb:

PSIMeaning
Below 0.1No real change
0.1 to 0.25Moderate change: look into it
Above 0.25Large change: act

The Kolmogorov-Smirnov (KS) test compares two sets of numbers and gives a p-value. A small p-value means the two sets probably come from different distributions.

import numpy as np
from scipy.stats import ks_2samp

def psi(expected, actual, bins=10):
    """Population Stability Index: how far a column's spread has moved."""
    edges = np.quantile(expected, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    e = np.histogram(expected, edges)[0] / len(expected)
    a = np.histogram(actual, edges)[0] / len(actual)
    e, a = np.clip(e, 1e-4, None), np.clip(a, 1e-4, None)
    return np.sum((a - e) * np.log(a / e))

rng = np.random.default_rng(7)
# Monthly income (thousand taka) of loan applicants when the model was trained
train_income = rng.normal(40, 10, 5000)

months = {
    "January (same as training)": rng.normal(40, 10, 1000),
    "April (slight rise)":        rng.normal(42, 10, 1000),
    "July (big change)":          rng.normal(50, 14, 1000),
}
print(f"{'month':<28} {'mean':>5} {'PSI':>6} {'KS p-value':>11}")
for name, now in months.items():
    p = ks_2samp(train_income, now).pvalue
    print(f"{name:<28} {now.mean():5.1f} {psi(train_income, now):6.3f} {p:11.4f}")

Output

month                         mean    PSI  KS p-value
January (same as training)    40.1  0.010      0.3946
April (slight rise)           41.6  0.042      0.0000
July (big change)             49.6  0.728      0.0000
  • January looks like training data: PSI 0.01 and a large KS p-value. No alarm.
  • In April the mean rose by only about 1,600 taka. PSI is 0.04, still “no real change”. But the KS p-value is 0.0000, a loud alarm.
  • July has a big change, and both measures agree.
  • With thousands of rows, the KS test can spot tiny shifts that do not matter. PSI measures the size of the change, so it is easier to act on.

Does Drift Hurt the Model?

Now we train a loan model and test it on three new months: one unchanged, one with data drift, and one with concept drift. We also run adversarial validation: we train a classifier to tell old rows from new rows. If it cannot do better than chance (AUC near 0.5), the inputs have not changed.

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

rng = np.random.default_rng(1)

def make_month(n, income_mean, rule_shift=0.0):
    income = rng.normal(income_mean, 10, n)        # thousand taka per month
    debt = rng.normal(20, 6, n)                    # thousand taka owed
    # chance of repaying the loan; rule_shift changes the real-world rule itself
    score = 0.15 * (income - 40) - 0.2 * (debt - 20) - rule_shift
    repaid = (rng.random(n) < 1 / (1 + np.exp(-score))).astype(int)
    return np.column_stack([income, debt]), repaid

X_train, y_train = make_month(5000, 40)
model = LogisticRegression().fit(X_train, y_train)

tests = {
    "same world":            make_month(2000, 40),
    "data drift (income up)": make_month(2000, 50),
    "concept drift (rule)":  make_month(2000, 40, rule_shift=1.5),
}
for name, (X, y) in tests.items():
    print(f"{name:<24} accuracy {model.score(X, y):.3f}   repaid rate {y.mean():.2f}")

# Adversarial validation: can a model tell training rows from new rows?
# AUC near 0.5 = the data looks the same; near 1.0 = it has clearly changed.
for name, (X_new, _) in tests.items():
    X_both = np.vstack([X_train[:2000], X_new])
    is_new = np.r_[np.zeros(2000), np.ones(len(X_new))]
    auc = cross_val_score(RandomForestClassifier(n_estimators=100, random_state=0),
                          X_both, is_new, cv=5, scoring="roc_auc").mean()
    print(f"{name:<24} train-vs-new AUC {auc:.2f}")

Output

same world               accuracy 0.789   repaid rate 0.50
data drift (income up)   accuracy 0.802   repaid rate 0.73
concept drift (rule)     accuracy 0.690   repaid rate 0.28
same world               train-vs-new AUC 0.49
data drift (income up)   train-vs-new AUC 0.71
concept drift (rule)     train-vs-new AUC 0.50
  • Data drift: the adversarial AUC jumps to 0.71, so the change is easy to detect. But accuracy did not fall. The model’s rule still holds for richer applicants. Drift in the inputs does not always mean trouble.
  • Concept drift: accuracy falls from 0.79 to 0.69. Yet the adversarial AUC is 0.50, because the inputs look exactly the same. Only the rule changed.
  • The repaid rate tells the story: it fell from 50% to 28%. You can only see that once loans are actually repaid or not.

Input checks are not enough

Checking input columns catches data drift early. Concept drift needs true outcomes. Keep collecting labels after launch, even a small sample, and track the real accuracy over time.

A Simple Monitoring Plan

What to trackHowCatches
Each input columnPSI each week or monthData drift
All inputs togetherAdversarial validation AUCData drift across columns
PredictionsShare of each predicted class, average scoreData drift, bugs
True outcomesAccuracy or AUC on newly labelled rowsConcept drift
Data qualityMissing values, new categoriesBroken data feeds

When drift is confirmed, the usual fix is to retrain on recent data. Some teams retrain on a fixed schedule, such as every month, and compare the new model with the old one before switching.

Common Mistakes

  1. Treating every KS alarm as a crisis. On large data it flags tiny, harmless shifts. Look at the size of the change too.
  2. Monitoring only inputs. Concept drift hides from input checks.
  3. Retraining on everything forever. Old data may follow old rules. Give recent data more weight or use a time window.
  4. No baseline. Save the training data’s statistics when you train the model, so you have something to compare with.

Practice Exercises

Exercise 1. After a new mobile app launches, the share of young applicants doubles. Is this data drift or concept drift?

Show answer

Data drift: the mix of inputs (ages) changed. Whether it hurts the model depends on whether young applicants behave the way the model learned. Check the accuracy on them once outcomes arrive.

Exercise 2. The adversarial AUC is 0.98. What does that tell you, and what would you do next?

Show answer

A model can almost perfectly tell old rows from new rows, so the inputs have changed a lot. Look at that model’s feature importance to find which columns changed. Then check whether it is a real change or a broken data feed, such as a column now measured in different units.

Frequently Asked Questions

What is the difference between data drift and concept drift?

Data drift means the input values change, such as incomes rising. Concept drift means the link between inputs and the answer changes, such as people with the same income repaying less often. Concept drift usually hurts accuracy more and is harder to detect.

How often should I retrain my model?

It depends on how fast your world changes. Watch PSI and real accuracy. Retrain when they show a meaningful change, or on a regular schedule if outcomes arrive slowly.

What PSI value means drift?

A common rule is that below 0.1 means no real change, 0.1 to 0.25 means a moderate change, and above 0.25 means a large change. These are rules of thumb, not strict limits.

Summary

  • Data drift changes the inputs; concept drift changes the rule linking inputs to outputs.
  • PSI measures how much one column has moved; the KS test is very sensitive on big data.
  • Adversarial validation checks whether new rows look different from training rows.
  • Concept drift needs true outcomes to detect, so keep collecting labels.

Next: Machine Learning Project: Loan Default Prediction.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *