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.
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.
Mathematical Formulation
Section titled “Mathematical Formulation”Let be the reference training distribution and be the empirical serving distribution observed across operational window . The symmetric Population Stability Index (PSI) partitioned over quantile bins is:
where is the reference proportion in bin , and is the serving proportion. Operational decision policy:
- : Distribution stable; no action.
- : Marginal shift; queue diagnostic pipeline.
- : Significant covariate shift; trigger automated retraining DAG.
Prerequisites and support
Section titled “Prerequisites and support”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 mathimport sysimport numpy as npimport matplotlib.pyplot as pltfrom IPython.display import display, Markdown, JSON
SEED = 42np.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 baseline training records and 8 consecutive weekly serving windows ( each). Between Week 4 and Week 8, a seasonal weather transition modifies the distribution of convective storms and flight transit times.
N_BASE = 2000N_WINDOW = 500NUM_WINDOWS = 8
# Baseline training distributionbaseline_weather = np.random.gamma(shape=2.0, scale=1.5, size=N_BASE)
# Serving windows with progressive drift starting at window 4serving_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.
Student Exercise (Stub)
Section titled “Student Exercise (Stub)”Review compute_psi. Verify that zero-count buckets are handled via Laplace smoothing () 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 windowspsi_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)
Distributional Drift Visualization
Section titled “Distributional Drift Visualization”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 comparisonax[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 Trajectoryax[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()Automated Retraining Boundary
Section titled “Automated Retraining Boundary”When , 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)
Method Invariant and Failure Probe
Section titled “Method Invariant and Failure Probe”Assert that identical distributions produce 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
Google Cloud Platform Transition
Section titled “Google Cloud Platform Transition”- BigQuery ML: Retrain model on fresh table partition via scheduled queries.
- Vertex AI Model Monitoring: Configure
ModelDeploymentMonitoringJobwith drift threshold0.20to 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
}