Lesson 3 of 9
Data Drift & Concept Drift Detection: Population Stability Index (PSI) & KS Tests
Machine learning models degrade silently over time because real-world distributions drift away from training distributions. Drift manifests in two distinct forms: Covariate / Data Drift P(X) (input feature distributions shift, e.g. inflation altering purchase amounts) and Concept Drift P(y|X) (the true causal relationship changes, e.g. consumer spending behavior transforming after an economic shock). Monitoring drift via the Population Stability Index (PSI) and Kolmogorov-Smirnov (KS) tests prevents catastrophic production failures.
Implementing Population Stability Index (PSI) & KS Drift Tests
import numpy as np
import pandas as pd
import scipy.stats as stats
# 1. BASELINE TRAINING DISTRIBUTION VS SHIFTED PRODUCTION STREAM
np.random.seed(42)
# Baseline training: average loan amount = $15,000
train_amounts = np.random.normal(loc=15000, scale=3000, size=5000)
# Production stream 6 months later: inflation has shifted mean to $19,500
prod_amounts = np.random.normal(loc=19500, scale=3500, size=5000)
# 2. POPULATION STABILITY INDEX (PSI) IMPLEMENTATION
def calculate_psi(baseline: np.ndarray, target: np.ndarray, n_bins: int = 10) -> float:
"""
Computes Population Stability Index:
PSI = sum((Actual% - Expected%) * ln(Actual% / Expected%))
"""
# Create bin boundaries based on baseline quantiles
quantiles = np.linspace(0, 100, n_bins + 1)
bins = np.percentile(baseline, quantiles)
bins[0] -= 1e-5
bins[-1] += 1e-5
# Calculate counts per bin
b_counts, _ = np.histogram(baseline, bins=bins)
t_counts, _ = np.histogram(target, bins=bins)
# Calculate percentages (add small epsilon to avoid log(0))
b_pct = (b_counts / len(baseline)) + 1e-6
t_pct = (t_counts / len(target)) + 1e-6
# PSI summation
psi_value = np.sum((t_pct - b_pct) * np.log(t_pct / b_pct))
return float(psi_value)
psi_score = calculate_psi(train_amounts, prod_amounts)
# Standard Industry PSI Benchmarks:
# PSI < 0.10: No significant drift (Stable)
# 0.10 <= PSI < 0.25: Moderate drift (Monitor closely)
# PSI >= 0.25: Significant drift (Model retraining mandatory!)
psi_status = (
"SIGNIFICANT DRIFT (Action Required)" if psi_score >= 0.25
else "MODERATE DRIFT (Warning)" if psi_score >= 0.10
else "STABLE (No Drift)"
)
# 3. TWO-SAMPLE KOLMOGOROV-SMIRNOV (KS) TEST FOR CONTINUOUS DISTRIBUTIONS
ks_stat, p_value = stats.ks_2samp(train_amounts, prod_amounts)
print("=== DATA DRIFT STATISTICAL AUDIT REPORT ===")
print(f"Population Stability Index (PSI) : {psi_score:.4f} -> {psi_status}")
print(f"Kolmogorov-Smirnov Statistic : {ks_stat:.4f} | p-value: {p_value:.4e}")
print(f"KS Test Conclusion : {'Reject H0: Distributions have drifted!' if p_value < 0.05 else 'Distributions match'}")Pro Tip: Evident vs Silent Concept Drift
Data drift P(X) can be detected immediately from incoming unlabeled inference requests. Concept drift P(y|X) requires ground truth labels (e.g. waiting 90 days to see if loans default). If data drift spikes significantly, assume concept drift is imminent and trigger automated canary monitoring.
MlDataDriftDetection Visual Representation
Hands-On Challenge: Build an Automated Drift Alerter
Write a background monitoring worker that computes PSI across all 20 features in an incoming batch of 10,000 transactions. If more than 3 features exceed a PSI of 0.25, dispatch an alert webhook to Slack/PagerDuty.
Quick Quiz & Key Concept Checks
Common Pitfall: Monitoring Drift on Low-Volume Samples
Computing PSI or KS tests on tiny sample batches (<100 records) produces noisy false alarms due to sampling variance. Accumulate at least 1,000 to 5,000 inference requests before computing statistical drift metrics.