Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 1

Lab: Measuring Drift on Shifted Data

Implement statistical drift detection algorithms from scratch, calculate Population Stability Index (PSI) and Kolmogorov-Smirnov metrics across sliding production windows, and calibrate drift thresholds on real-world sample distributions.

Contentsand lesson path

On this page

  1. Statistical Drift Detection: Quantifying Divergence in Production Data
  2. Practice check
  3. Apply it
  4. Review prompt

Lessons of ML Monitoring & Drift

  1. How Models Fail Silently in Production Concept · 20 min
  2. Logging Predictions and Joining Late Labels Concept · 20 min
  3. Lab: Measuring Drift on Shifted Data Lab · 30 min
  4. Worked Example: Alert Thresholds Nobody Mutes Worked example · 20 min
  5. Lab: From Alert to Action with a Runbook Lab · 25 min
  6. Check: Diagnose the Dashboard Knowledge check · 8 questions

What you will learn

  • Detect data drift and prediction drift with statistical tests or distances (PSI, Kolmogorov-Smirnov, Jensen-Shannon) and distinguish them from concept drift.

Prerequisites: Model Packaging & Serving

01. Statistical Drift Detection: Quantifying Divergence in Production Data

Detecting data drift requires rigorous mathematical frameworks to compare two probability distributions: a baseline reference distribution $P(X)$ (typically derived from the training or validation partition) and a target current distribution $Q(X)$ (derived from a recent production sliding window). When monitoring continuous and categorical features across millions of inference records, engineering teams rely on information-theoretic distances and non-parametric statistical tests.

  • Population Stability Index (PSI): Originating in financial credit risk modeling, PSI measures the divergence between a reference distribution $P$ and an actual distribution $Q$ partitioned into $B$ discrete bins (typically $B = 10$ deciles calibrated on the reference data). The metric is defined as:

$$\text{PSI} = \sum_{b=1}^{B} \left( Q_b - P_b \right) \times \ln\left( \frac{Q_b}{P_b} \right)$$

where $P_b$ and $Q_b$ represent the empirical percentage of samples falling into bin $b$ for the reference and current distributions respectively. Notice that $(Q_b - P_b)$ and $\ln(Q_b / P_b)$ always share the same sign, ensuring that every bin contributes a non-negative term to the total sum. By industrial convention:

  • $\text{PSI} < 0.10$: Minimal shift; distributions are stable; no action required.

  • $0.10 \le \text{PSI} < 0.20$: Moderate shift; warranting close monitoring and investigation.

  • $\text{PSI} \ge 0.20$: Significant distribution drift; demanding root cause analysis, pipeline audits, or model retraining.

  • Two-Sample Kolmogorov-Smirnov (KS) Test: The Kolmogorov-Smirnov test is a non-parametric test comparing the empirical cumulative distribution functions (ECDFs) of two continuous samples, $F_{\text{ref}}(x)$ and $F_{\text{curr}}(x)$. The KS statistic $D$ represents the maximum vertical distance between the two cumulative curves:

$$D = \sup_x \left| F_{\text{ref}}(x) - F_{\text{curr}}(x) \right|$$

A large $D$ indicates that the shape, location, or variance of the distribution has shifted significantly. While the test provides an asymptotic $p$-value indicating whether the two samples originate from identical distributions, relying exclusively on $p$-values in production leads to catastrophic alert fatigue.

  • The Large Sample Size Fallacy with P-Values: In production environments with tens of thousands or millions of inference requests per day, sample size $N$ is massive. Because hypothesis tests become hypersensitive as $N \to \infty$, a trivial, economically meaningless change in feature mean (such as average user age drifting from 34.00 to 34.05 years) yields an extreme $p$-value ($p < 10^{-15}$). If engineers trigger alerts on $p < 0.01$, on-call engineers receive dozens of false alarms daily and inevitably mute the alerting channel. Production systems must threshold on standardized effect sizes (such as the KS statistic $D > 0.05$ or $\text{PSI} > 0.15$) rather than raw $p$-values.

  • Selecting the Reference Window: The reference dataset must faithfully represent the data manifold the model learned during development. Using the training dataset or the initial 30-day post-launch production window provides an anchor against cumulative long-term drift. In contrast, comparing the current window only against the immediately preceding hour detects sudden spikes but remains blind to slow, gradual drift accumulating over months.

  • Handling Numerical Stability and Zero Bins: When computing PSI, if a newly observed feature value falls outside the reference range or a bin has zero observed counts ($Q_b = 0$), the ratio $\ln(Q_b / P_b)$ diverges to negative infinity. Production implementations apply Laplace smoothing or floor epsilon clipping (e.g., setting minimum frequencies to $10^{-4}$) to guarantee numerical stability across edge cases.

  • Categorical Drift and Jensen-Shannon Distance: For categorical features (such as merchant category codes, device types, or operational countries), continuous ECDF metrics like KS are inapplicable. Teams employ Chi-Square goodness-of-fit tests or the symmetric, bounded Jensen-Shannon (JS) divergence. The JS distance satisfies $0 \le \text{JS}(P, Q) \le 1$ when using base-2 logarithms, providing a scale-invariant metric suitable for uniform alerting thresholds across disparate data types.

  • Multivariate Drift vs Univariate Slices: Monitoring individual features one by one can miss complex multivariate distribution shifts where marginal distributions appear normal but correlation structures dissolve. High-maturity ML teams supplement univariate PSI with multivariate drift detectors, such as training a domain discriminator (binary classifier) to distinguish between reference and production records. If the domain classifier achieves ROC-AUC $> 0.65$, significant multidimensional covariate shift has occurred.

  • Wasserstein Distance (Earth Mover's Distance): For continuous features with clear physical or financial units (such as transaction amounts or physical sensor readings), engineers frequently compute the 1-Wasserstein metric $W_1(P, Q) = \int_{-\infty}^{\infty} |F_P(x) - F_Q(x)| dx$. Unlike dimensionless ratios like PSI, Wasserstein distance is expressed directly in the feature's native physical units (e.g., "$4.50 drift in average transaction size"), making it immediately intuitive for business stakeholders during cross-functional reviews.

  • Monitoring Unstructured Embeddings: In natural language processing, computer vision, and recommender systems, models process dense floating-point vector representations rather than tabular columns. Tabular PSI on individual vector dimensions fails to capture semantic meaning. Teams monitor embedding drift by tracking cosine similarity shifts between production centroids and reference clusters, or by measuring maximum mean discrepancy (MMD) across latent activation spaces.

Python · calculate_feature_drift.py Implementing PSI and KS drift detectors
import numpy as np
from scipy import stats

np.random.seed(42)

def compute_psi(ref: np.ndarray, curr: np.ndarray, bins: int = 10) -> float:
    quantiles = np.linspace(0, 100, bins + 1)
    bin_edges = np.percentile(ref, quantiles)
    bin_edges[0] = -np.inf
    bin_edges[-1] = np.inf
    
    ref_counts, _ = np.histogram(ref, bins=bin_edges)
    curr_counts, _ = np.histogram(curr, bins=bin_edges)
    
    # Clip to avoid zero division in log
    ref_pct = np.clip(ref_counts / len(ref), 1e-4, 1.0)
    curr_pct = np.clip(curr_counts / len(curr), 1e-4, 1.0)
    
    psi_bins = (curr_pct - ref_pct) * np.log(curr_pct / ref_pct)
    return float(np.sum(psi_bins))

# 1. Reference baseline (e.g. training set)
ref_data = np.random.normal(loc=50.0, scale=10.0, size=5000)

# 2. Stable production window
curr_stable = np.random.normal(loc=50.2, scale=9.9, size=2000)

# 3. Shifted production window (covariate drift)
curr_shifted = np.random.normal(loc=54.5, scale=12.0, size=2000)

psi_stable = compute_psi(ref_data, curr_stable)
psi_shifted = compute_psi(ref_data, curr_shifted)
ks_stable = stats.ks_2samp(ref_data, curr_stable)
ks_shifted = stats.ks_2samp(ref_data, curr_shifted)

print("=== ML MONITORING DRIFT AUDIT ===")
print(f"Reference Window: N={len(ref_data)} (mean={ref_data.mean():.2f})")
print(f"Stable Window:    PSI={psi_stable:.4f}, KS-stat={ks_stable.statistic:.4f}, "
      f"p={ks_stable.pvalue:.4f}")
print(f"Shifted Window:   PSI={psi_shifted:.4f}, KS-stat={ks_shifted.statistic:.4f}, "
      f"p={ks_shifted.pvalue:.4e}")
if psi_shifted > 0.2:
    print("Decision: Significant drift detected (PSI > 0.20) -> Trigger Runbook")
else:
    print("Decision: Stable distribution (PSI <= 0.10) -> Normal Operation")
Expected output · calculate_feature_drift.py
=== ML MONITORING DRIFT AUDIT ===
Reference Window: N=5000 (mean=50.06)
Stable Window:    PSI=0.0054, KS-stat=0.0412, p=0.0153
Shifted Window:   PSI=0.2137, KS-stat=0.1866, p=6.1475e-44
Decision: Significant drift detected (PSI > 0.20) -> Trigger Runbook

02. Practice check

Practice check · 2 questions

Check Your Understanding

Review key concepts and verify your understanding with these practice questions.

Q1. An automated daily feature drift pipeline reports a PSI value of 0.23 on the `customer_tenure_months` feature between production traffic and the training set. How should this result be interpreted according to standard conventions?
Q2. A two-sample Kolmogorov-Smirnov test evaluated on 500,000 daily transaction records yields p = 1.2e-8, yet the KS statistic D is only 0.012 and distribution visual overlays show near-perfect alignment. What explains this divergence?
Practice only: not graded, not saved, not evidence.

03. Apply it

When implementing automated drift detection in production pipelines:

  • Base Decisions on Effect Sizes Rather than P-Values: In high-volume production streams ($N > 10^4$), configure alert triggers on standardized effect sizes (e.g., $\text{PSI} \ge 0.20$ or KS statistic $D \ge 0.05$) to avoid alert fatigue from trivial shifts.
  • Clip Zero Frequencies with Laplace Smoothing: When computing PSI or Kullback-Leibler divergences, apply a small minimum floor ($10^{-4}$) to prevent divisions by zero or infinite log arguments when new feature values occur.
  • Partition Continuous Features on Reference Quantiles: Compute bin edges on the clean training baseline so that every reference bin contains an equal share of samples ($10%$ each), ensuring balanced sensitivity across the distribution.
  • Anchor to a Stable Baseline: Compare daily or weekly sliding windows against the validated training dataset or initial post-launch baseline to catch slow, cumulative drift that escapes hour-over-hour comparisons.

04. Review prompt

Derive the formula for Population Stability Index (PSI) and explain why each term is non-negative. Why do statistical tests like Kolmogorov-Smirnov produce microscopic p-values on large production datasets even when feature distributions are practically identical? How do you prevent alert fatigue?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check