# Install evidently if needed
# !pip install "evidently>=0.7"Data Drift Detection — Hands-On Notebook
CS 203 — Week 11
In this notebook we’ll: 1. Visualize drift with histograms 2. Detect drift with the KS test (scipy) 3. Compute PSI manually 4. Use Evidently for automated drift reports 5. Simulate gradual drift over time 6. Try a real-world scenario
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import ks_2samp, chi2_contingency
from sklearn.datasets import load_iris, load_wine
plt.style.use("seaborn-v0_8-whitegrid")
np.random.seed(42)Part 1: Setup — Simulating Training vs Production Data
We’ll use the Iris dataset. Imagine: - Training data: flowers measured in January - Production data: flowers measured in July by a new field team
We split the rows at random, so both halves come from the same population. Then we simulate one realistic change: the July team’s calipers read sepal width about 0.3 cm too high (a measurement drift). Everything else is unchanged.
(Why not just take iloc[:100] vs iloc[100:]? Iris rows are sorted by species, so that split puts every virginica in “production”. That is a class-sorted split, not realistic drift.)
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["target"] = iris.target
# Random split: training and production come from the SAME population
df_shuffled = df.sample(frac=1, random_state=42).reset_index(drop=True)
df_train = df_shuffled.iloc[:100].copy()
df_prod = df_shuffled.iloc[100:].copy()
# Simulated drift: July's calipers read sepal width ~0.3 cm too high
rng = np.random.default_rng(0)
df_prod["sepal width (cm)"] += 0.3 + rng.normal(0, 0.05, len(df_prod))
print(f"Training: {len(df_train)} rows")
print(f"Production: {len(df_prod)} rows")
print(f"\nTraining class distribution:\n{df_train['target'].value_counts().sort_index()}")
print(f"\nProduction class distribution:\n{df_prod['target'].value_counts().sort_index()}")Notice: the class mix is similar in both halves (random split, so no label drift). The only real change is the sepal-width offset we injected: covariate drift in one input feature. Let’s see whether our tools find it.
Part 2: Visual Drift Detection — Histograms
The simplest way to spot drift: plot the same feature from both datasets.
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
for ax, col in zip(axes.flat, iris.feature_names):
ax.hist(df_train[col], bins=20, alpha=0.5, label="Training", color="steelblue", density=True)
ax.hist(df_prod[col], bins=20, alpha=0.5, label="Production", color="coral", density=True)
ax.set_title(col, fontsize=12)
ax.legend()
plt.suptitle("Training vs Production — Do these look the same?", fontsize=14, fontweight="bold")
plt.tight_layout()
plt.show()Discussion: Which features look shifted? Which look stable? (We injected drift into exactly one feature: can you spot it?)
The problem with visual inspection: it’s subjective. We need a number.
Part 3: KS Test — A Number for Drift
The Kolmogorov-Smirnov test compares two distributions and gives us: - KS statistic: the maximum gap between the cumulative distributions (0 = identical, 1 = completely different) - p-value: if there were no drift (both samples from the same distribution), the probability of seeing a gap at least this large. Small p (< 0.05) = hard to explain without drift.
# Test each feature
print(f"{'Feature':30s} {'KS stat':>8s} {'p-value':>8s} {'Verdict'}")
print("-" * 65)
for col in iris.feature_names:
stat, p = ks_2samp(df_train[col], df_prod[col])
verdict = "DRIFT" if p < 0.05 else "OK"
print(f"{col:30s} {stat:8.4f} {p:8.4f} [{verdict}]")Visualizing the KS test
Let’s see what the KS test actually measures — the gap between cumulative distribution curves.
# Pick the feature we drifted
feature = "sepal width (cm)"
# Sort values and compute empirical CDF
train_sorted = np.sort(df_train[feature])
prod_sorted = np.sort(df_prod[feature])
train_cdf = np.arange(1, len(train_sorted) + 1) / len(train_sorted)
prod_cdf = np.arange(1, len(prod_sorted) + 1) / len(prod_sorted)
fig, ax = plt.subplots(figsize=(10, 5))
ax.step(train_sorted, train_cdf, label="Training CDF", color="steelblue", linewidth=2)
ax.step(prod_sorted, prod_cdf, label="Production CDF", color="coral", linewidth=2)
# Find and annotate the maximum gap
stat, p = ks_2samp(df_train[feature], df_prod[feature])
ax.set_title(f"KS Test for '{feature}' — D = {stat:.3f}, p = {p:.4f}", fontsize=13)
ax.set_xlabel(feature)
ax.set_ylabel("Cumulative Probability")
ax.legend(fontsize=12)
ax.annotate(f"Max gap = {stat:.3f}", xy=(0.03, 0.85), xycoords="axes fraction", fontsize=14,
bbox=dict(boxstyle="round", fc="lightyellow", ec="orange"))
plt.tight_layout()
plt.show()Part 4: Simulate Artificial Drift
Now let’s add a much bigger, second shift (petal length +2 cm) and watch the KS test catch it.
# Shift petal_length by +2 cm in production
df_prod_shifted = df_prod.copy()
df_prod_shifted["petal length (cm)"] += 2.0
print("After shifting petal length by +2 cm:\n")
print(f"{'Feature':30s} {'KS stat':>8s} {'p-value':>8s} {'Verdict'}")
print("-" * 65)
for col in iris.feature_names:
stat, p = ks_2samp(df_train[col], df_prod_shifted[col])
verdict = "DRIFT" if p < 0.05 else "OK"
marker = " ← shifted!" if col == "petal length (cm)" else ""
print(f"{col:30s} {stat:8.4f} {p:8.4f} [{verdict}]{marker}")# Visualize the shift
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Before shift
axes[0].hist(df_train["petal length (cm)"], bins=20, alpha=0.5, label="Training", color="steelblue", density=True)
axes[0].hist(df_prod["petal length (cm)"], bins=20, alpha=0.5, label="Production", color="coral", density=True)
axes[0].set_title("Before: petal length not shifted", fontsize=12)
axes[0].legend()
# After shift
axes[1].hist(df_train["petal length (cm)"], bins=20, alpha=0.5, label="Training", color="steelblue", density=True)
axes[1].hist(df_prod_shifted["petal length (cm)"], bins=20, alpha=0.5, label="Production (shifted +2)", color="coral", density=True)
axes[1].set_title("After: Petal length shifted by +2 cm", fontsize=12)
axes[1].legend()
plt.suptitle("Can you see the drift?", fontsize=14, fontweight="bold")
plt.tight_layout()
plt.show()Part 5: PSI — Population Stability Index
PSI gives a single score instead of a p-value. Popular in banking/fintech.
Bins come from the training quantiles. The outermost bins must be open-ended (-inf and +inf): otherwise any production value outside the training range falls outside every bin and silently disappears, so a batch that moved completely would count as almost no mass.
Traffic light rules: - PSI < 0.1 → Green (no drift) - PSI 0.1–0.25 → Yellow (monitor) - PSI > 0.25 → Red (drift!)
def compute_psi(reference, current, bins=10):
"""Population Stability Index between two arrays."""
edges = np.quantile(reference, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf # open-ended outer bins: nothing falls outside
ref_pct = np.histogram(reference, bins=edges)[0] / len(reference)
cur_pct = np.histogram(current, bins=edges)[0] / len(current)
# Avoid log(0) for empty bins
ref_pct = np.clip(ref_pct, 0.001, None)
cur_pct = np.clip(cur_pct, 0.001, None)
psi = np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct))
return psi
# Sanity check: a batch shifted completely outside the training range must give a LARGE PSI
ref = np.random.normal(0, 1, 1000)
print(f"PSI, same distribution: {compute_psi(ref, np.random.normal(0, 1, 1000)):.3f}")
print(f"PSI, shifted by +100: {compute_psi(ref, ref + 100):.3f}")
print()
print(f"{'Feature':30s} {'PSI':>8s} {'Verdict'}")
print("-" * 55)
for col in iris.feature_names:
psi = compute_psi(df_train[col].values, df_prod_shifted[col].values)
if psi < 0.1:
verdict = "GREEN (no drift)"
elif psi < 0.25:
verdict = "YELLOW (monitor)"
else:
verdict = "RED (drift!)"
print(f"{col:30s} {psi:8.3f} [{verdict}]")Part 6: Gradual Drift Over Time
Real drift usually happens slowly — not overnight. Let’s simulate 12 months of gradual shift.
feature = "petal length (cm)"
results = []
for month in range(1, 13):
df_month = df_prod.copy()
# Each month, the shift increases by 0.3 cm
df_month[feature] += month * 0.3
stat, p = ks_2samp(df_train[feature], df_month[feature])
psi = compute_psi(df_train[feature].values, df_month[feature].values)
results.append({"month": month, "ks_stat": stat, "p_value": p, "psi": psi})
df_results = pd.DataFrame(results)
fig, axes = plt.subplots(1, 3, figsize=(16, 4))
axes[0].plot(df_results["month"], df_results["ks_stat"], "o-", color="steelblue", linewidth=2)
axes[0].set_title("KS Statistic Over Time")
axes[0].set_xlabel("Month")
axes[0].set_ylabel("KS Statistic")
axes[1].plot(df_results["month"], df_results["p_value"], "o-", color="coral", linewidth=2)
axes[1].axhline(y=0.05, color="red", linestyle="--", label="p=0.05 threshold")
axes[1].set_title("p-value Over Time")
axes[1].set_xlabel("Month")
axes[1].set_ylabel("p-value")
axes[1].legend()
axes[2].plot(df_results["month"], df_results["psi"], "o-", color="green", linewidth=2)
axes[2].axhline(y=0.1, color="orange", linestyle="--", label="PSI=0.1 (monitor)")
axes[2].axhline(y=0.25, color="red", linestyle="--", label="PSI=0.25 (drift!)")
axes[2].set_title("PSI Over Time")
axes[2].set_xlabel("Month")
axes[2].set_ylabel("PSI")
axes[2].legend()
plt.suptitle("Drift Gets Worse Over Time", fontsize=14, fontweight="bold")
plt.tight_layout()
plt.show()Key insight: The KS statistic and PSI both grow as drift increases (PSI is not perfectly smooth: it wobbles as values move from bin to bin). The p-value drops to near zero quickly — it’s very sensitive. PSI gives a more gradual signal.
Part 7: Evidently — Automated Drift Reports
Instead of checking features one by one, let Evidently do it all at once.
from evidently import Report
from evidently.presets import DataDriftPreset
# Drop target column — we're only checking input features
train_features = df_train.drop("target", axis=1)
prod_features = df_prod_shifted.drop("target", axis=1)
report = Report([DataDriftPreset()])
my_eval = report.run(reference_data=train_features, current_data=prod_features)
my_evalExplore the report above:
- How many features drifted?
- Click on each feature — see the histograms
- Which statistical test did Evidently choose?
- Do the results match our manual KS tests?
# Save the report as an HTML file you can share
my_eval.save_html("drift_report.html")
print("Report saved to drift_report.html — open in browser!")Part 8: A Different Kind of Shift — A Class the Model Never Saw
sklearn’s wine dataset has 13 chemical measurements of wines from three cultivars (grape varieties). The target is the cultivar, not a quality score.
Imagine a cultivar classifier trained only on bottles of cultivars 0 and 1. In production, bottles of cultivar 2 start arriving. This is not ordinary covariate drift (same classes, inputs moved a bit): it is label/concept shift: a class never seen in training. The inputs change too, so the drift tests will fire, but the real problem is that the correct answer is a class the model cannot output.
wine = load_wine()
df_wine = pd.DataFrame(wine.data, columns=wine.feature_names)
df_wine["target"] = wine.target # cultivar: 0, 1 or 2 (not wine quality)
# Training: cultivars 0 and 1 only. Production: cultivar 2 only (never seen in training)
df_seen = df_wine[df_wine["target"].isin([0, 1])].drop("target", axis=1)
df_new = df_wine[df_wine["target"] == 2].drop("target", axis=1)
print(f"Training (cultivars 0, 1): {len(df_seen)} samples")
print(f"Production (cultivar 2): {len(df_new)} samples")# Manual KS test
print(f"{'Feature':30s} {'KS stat':>8s} {'p-value':>10s} {'Verdict'}")
print("-" * 65)
for col in wine.feature_names:
stat, p = ks_2samp(df_seen[col], df_new[col])
verdict = "DRIFT" if p < 0.05 else "OK"
print(f"{col:30s} {stat:8.4f} {p:10.6f} [{verdict}]")# Evidently report for wine data
report_wine = Report([DataDriftPreset()])
wine_eval = report_wine.run(reference_data=df_seen, current_data=df_new)
wine_evalPart 9: Impact on Model Performance
Drift detection tells you the inputs changed. Does the model actually perform worse?
Here the answer is guaranteed before we run anything: a classifier trained on classes 0 and 1 can only ever predict 0 or 1, so its accuracy on cultivar-2 bottles is exactly 0. Retraining on more of the same data will not help; you need labelled examples of the new class.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
# Train on cultivars 0 and 1
X_seen = df_wine[df_wine["target"].isin([0, 1])].drop("target", axis=1)
y_seen = df_wine[df_wine["target"].isin([0, 1])]["target"]
model = RandomForestClassifier(random_state=42)
scores_seen = cross_val_score(model, X_seen, y_seen, cv=5)
print(f"Accuracy on cultivars 0/1 (training distribution): {scores_seen.mean():.3f} ± {scores_seen.std():.3f}")
# Fit on cultivars 0/1, then predict cultivar-2 bottles
model.fit(X_seen, y_seen)
X_new = df_wine[df_wine["target"] == 2].drop("target", axis=1)
y_new = df_wine[df_wine["target"] == 2]["target"]
# The model has never seen class 2, so it cannot predict it: every prediction is wrong.
preds = model.predict(X_new)
print(f"\nPredictions on cultivar-2 bottles: {np.unique(preds, return_counts=True)}")
print(f"Actual labels: all class 2")
print(f"Accuracy on cultivar 2: {(preds == y_new.values).mean():.3f}")
print(f"\n→ 0% by construction: the correct class was never in training (label shift, not just input drift).")Summary
| What we learned | Tool |
|---|---|
| Visual drift check | matplotlib histograms |
| Statistical test (numeric) | scipy.stats.ks_2samp() |
| Statistical test (categorical) | scipy.stats.chi2_contingency() (train counts vs prod counts) or scipy.stats.chisquare(observed, n_prod * p_train) (vs a fixed reference) |
| Stability score | PSI (custom function) |
| Automated full report | evidently (4 lines) |
| Impact verification | Train on old data, test on new |
| Unseen class in production | Drift tests flag it; fixing it needs new labels |
Key takeaway: Detecting drift is easy. The hard part is deciding what to do about it.