Skip to content
Mementropy
SolutionshungersyncNotebookExecuted example

In-Situ Warehouse Modeling, Automated Pipelines, and Distributional Drift

Detect covariate drift with the Population Stability Index and set automated retraining boundaries for a warehouse-native model.

By Ryan HammangUpdated

Part IV: The Flight Disruption Binary Classifier Series

Authoring standard: Hidden Technical Debt in Machine Learning Systems (Sculley et al.)
Setting: Hartsfield-Jackson Atlanta International Airport (ATL)
Case linkage: HS-OPS-09 · the sensor tinkerer (Edge Ingestion & BLE Privacy)
Operational Objective: Detect non-stationary covariate shift via Population Stability Index (PSI) and establish automated retraining boundaries in BigQuery ML and Vertex AI.

Let P(X)P(X) be the reference training distribution and Q(X)Q(X) be the empirical serving distribution observed across operational window WW. The symmetric Population Stability Index (PSI) partitioned over BB quantile bins is:

PSI=∑b=1B(qb−pb)ln⁡(qbpb)\text{PSI} = \sum_{b=1}^B (q_b - p_b) \ln\left(\frac{q_b}{p_b}\right)

where pbp_b is the reference proportion in bin bb, and qbq_b is the serving proportion. Operational decision policy:

  • PSI<0.10\text{PSI} < 0.10: Distribution stable; no action.
  • 0.10≤PSI<0.250.10 \le \text{PSI} < 0.25: Marginal shift; queue diagnostic pipeline.
  • PSI≥0.25\text{PSI} \ge 0.25: Significant covariate shift; trigger automated retraining DAG.

The saved environment reports Python 3.12.12. For the public download, use an isolated Python environment with JupyterLab and NumPy, Matplotlib, IPython. These are package prerequisites, not a locked or newly tested environment. The Python examples generate their own teaching data and do not require cloud credentials or a pretrained model.

The public download omits the site-only mementropy.mplstyle setup cell; use Matplotlib’s default style. No style file or environment lock is bundled. The cloud, SQL and deployment discussion is explanatory material, not evidence that a service was deployed by this notebook. If a rerun differs, record package versions and compare to the saved outputs rather than treating them as a guaranteed result.

Evidence: these are saved outputs from an earlier execution, not rerun for the 2026-10-29 editorial update. Rendering displays saved cells; it does not execute them. The public download is not a locked environment or a production validation.

import math
import sys
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, Markdown, JSON
SEED = 42
np.random.seed(SEED)
print({'python': sys.version.split()[0], 'seed': SEED, 'module': '04-pipeline-and-drift'})
{'python': '3.12.12', 'seed': 42, 'module': '04-pipeline-and-drift'}

Baseline vs Non-Stationary Serving Distribution

Section titled “Baseline vs Non-Stationary Serving Distribution”

We simulate N=2,000N=2,000 baseline training records and 8 consecutive weekly serving windows (Nw=500N_w = 500 each). Between Week 4 and Week 8, a seasonal weather transition modifies the distribution of convective storms and flight transit times.

N_BASE = 2000
N_WINDOW = 500
NUM_WINDOWS = 8
# Baseline training distribution
baseline_weather = np.random.gamma(shape=2.0, scale=1.5, size=N_BASE)
# Serving windows with progressive drift starting at window 4
serving_windows = []
for w in range(NUM_WINDOWS):
drift_factor = max(0.0, (w - 3) * 0.4)
# Mean shifts rightward, variance expands
w_data = np.random.gamma(shape=2.0 + drift_factor, scale=1.5 + drift_factor * 0.3, size=N_WINDOW)
serving_windows.append(w_data)
print({
'baseline_records': N_BASE,
'monitoring_windows': NUM_WINDOWS,
'window_size': N_WINDOW
})
{'baseline_records': 2000, 'monitoring_windows': 8, 'window_size': 500}

Implementation: Population Stability Index Calculator

Section titled “Implementation: Population Stability Index Calculator”

We compute PSI across 10 empirical quantile bins established on the baseline dataset.

Review compute_psi. Verify that zero-count buckets are handled via Laplace smoothing (ϵ=10−4\epsilon = 10^{-4}) to prevent numerical divergence.

def compute_psi(reference, target, num_bins=10, epsilon=1e-4):
"""Compute Population Stability Index (PSI) between two empirical distributions."""
# Quantile bins derived strictly from reference distribution
quantiles = np.linspace(0, 100, num_bins + 1)
bin_edges = np.percentile(reference, quantiles)
bin_edges[0] = -np.inf
bin_edges[-1] = np.inf
# Bucket counts
ref_counts = np.histogram(reference, bins=bin_edges)[0]
tgt_counts = np.histogram(target, bins=bin_edges)[0]
# Proportions with Laplace smoothing
p = np.maximum(ref_counts / len(reference), epsilon)
q = np.maximum(tgt_counts / len(target), epsilon)
# PSI sum
psi_value = np.sum((q - p) * np.log(q / p))
return float(psi_value)
# Evaluate PSI trajectory over operational windows
psi_series = [compute_psi(baseline_weather, w_data) for w_data in serving_windows]
for w, val in enumerate(psi_series):
print(f"Window {w+1} PSI: {val:.4f} ({'STABLE' if val < 0.1 else ('WARNING' if val < 0.25 else 'CRITICAL_DRIFT')})")
Window 1 PSI: 0.0183 (STABLE)
Window 2 PSI: 0.0245 (STABLE)
Window 3 PSI: 0.0091 (STABLE)
Window 4 PSI: 0.0192 (STABLE)
Window 5 PSI: 0.1427 (WARNING)
Window 6 PSI: 0.6782 (CRITICAL_DRIFT)
Window 7 PSI: 1.7507 (CRITICAL_DRIFT)
Window 8 PSI: 2.0185 (CRITICAL_DRIFT)

We contrast the baseline density against Week 8 drifted density and plot the PSI alarm threshold.

fig, ax = plt.subplots(1, 2, figsize=(12, 4))
# Density comparison
ax[0].hist(baseline_weather, bins=30, density=True, alpha=0.5, color='#1a7f64', label='Baseline P(X)')
ax[0].hist(serving_windows[-1], bins=30, density=True, alpha=0.5, color='#cf222e', label='Window 8 Q(X)')
ax[0].set(xlabel='Convective Severity Metric', ylabel='Density', title='Covariate Distribution Shift')
ax[0].legend(); ax[0].grid(True, alpha=0.3)
# PSI Trajectory
ax[1].plot(range(1, NUM_WINDOWS + 1), psi_series, 'o-', color='#0969da', lw=2)
ax[1].axhline(0.10, color='#b35900', linestyle='--', label='Warning (0.10)')
ax[1].axhline(0.25, color='#cf222e', linestyle='--', label='Retrain Trigger (0.25)')
ax[1].set(xlabel='Operational Window (Weeks)', ylabel='PSI', title='Population Stability Index Over Time')
ax[1].legend(); ax[1].grid(True, alpha=0.3)
plt.tight_layout(); plt.show()
0 5 10 15 20 Convective Severity Metric 0.00 0.05 0.10 0.15 0.20 Density Covariate Distribution Shift Baseline P(X) Window 8 Q(X) 1 2 3 4 5 6 7 8 Operational Window (Weeks) 0.00 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 PSI Population Stability Index Over Time Warning (0.10) Retrain Trigger (0.25)

When PSI≥0.25\text{PSI} \ge 0.25, the monitoring engine issues an automated dispatch event triggering model retraining on Vertex AI Pipelines.

trigger_window = next((w + 1 for w, psi in enumerate(psi_series) if psi >= 0.25), None)
print(f"Automated Pipeline Action: Retrain triggered at Window {trigger_window} (PSI = {psi_series[trigger_window-1]:.4f})")
Automated Pipeline Action: Retrain triggered at Window 6 (PSI = 0.6782)

Assert that identical distributions produce PSI≈0\text{PSI} \approx 0 within numerical tolerance.

psi_zero = compute_psi(baseline_weather, baseline_weather)
assert psi_zero < 0.001, f"Self-PSI must be zero, got {psi_zero}"
print(f"EXPECTED BEHAVIOR: Identity PSI = {psi_zero:.6f}")
EXPECTED BEHAVIOR: Identity PSI = 0.000000
  1. BigQuery ML: Retrain model on fresh table partition via scheduled queries.
  2. Vertex AI Model Monitoring: Configure ModelDeploymentMonitoringJob with drift threshold 0.20 to automate alert publication to Cloud Pub/Sub.
display(JSON({
'baseline_records': N_BASE,
'total_windows_evaluated': NUM_WINDOWS,
'retrain_triggered_at_window': trigger_window,
'terminal_psi': round(psi_series[-1], 4),
'status': 'VERIFIED_DRIFT_DETECTION'
}))
{
  "baseline_records": 2000,
  "retrain_triggered_at_window": 6,
  "status": "VERIFIED_DRIFT_DETECTION",
  "terminal_psi": 2.0185,
  "total_windows_evaluated": 8
}