Statistical Estimation, Calibration, and Temporal Information Boundaries
Estimate the chance of a 30-minute gate arrival delay at Atlanta with calibrated models and no information from the future.
Part I: The Flight Disruption Binary Classifier Series
Authoring standard: The Elements of Statistical Learning (Hastie, Tibshirani, Friedman)
Setting: Hartsfield-Jackson Atlanta International Airport (ATL)
Case linkage: HS-OPS-01 · the on-prem DGX advocate (ML & Forecasting Engineer)
Operational Objective: Estimate the conditional posterior probability of a 30-minute gate arrival delay () under non-stationary weather and flight schedules, without temporal lookahead contamination.
Mathematical Formulation
Section titled “Mathematical Formulation”Let be independent observations where represents flight covariates (distance, scheduled block time, convective weather severity) and denotes arrival delay . We specify the linear logistic model:
The parameter vector is estimated by maximizing the -penalized log-likelihood:
Optimization is performed via Newton-Raphson / Iteratively Reweighted Least Squares (IRLS):
where and .
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 randomimport statisticsimport sysimport numpy as npimport matplotlib.pyplot as pltfrom IPython.display import display, Markdown, JSON
SEED = 42np.random.seed(SEED)random.seed(SEED)print({'python': sys.version.split()[0], 'seed': SEED, 'module': '01-estimation-and-leakage'}){'python': '3.12.12', 'seed': 42, 'module': '01-estimation-and-leakage'}
Data and the Information Boundary
Section titled “Data and the Information Boundary”We simulate chronological flight arrival records across days at ATL. The temporal filtration strictly governs what data the estimator may observe.
- Training partition: Days to ().
- Holdout evaluation partition: Days to ().
Under no circumstances may training features be computed using summary statistics (e.g., sample mean , standard deviation ) calculated over the combined dataset.
# Generate synthetic non-stationary arrival seriesN_DAYS = 120FLIGHTS_PER_DAY = 10N = N_DAYS * FLIGHTS_PER_DAY
days = np.repeat(np.arange(N_DAYS), FLIGHTS_PER_DAY)# Covariates: scheduled_time (min), distance (100s miles), convective_index (0 to 10)scheduled_time = np.random.normal(loc=120, scale=30, size=N)distance = np.clip(scheduled_time * 7.5 + np.random.normal(0, 50, size=N), 200, 2500)# Seasonal weather severity with convective storm spikes in later periodsconvective_index = np.clip(2.0 + 1.5 * np.sin(2 * np.pi * days / 30) + np.random.exponential(scale=1.2, size=N), 0, 10)
# True underlying logit functiontrue_beta = np.array([-3.5, 0.008, 0.0005, 0.35])X_raw = np.column_stack([np.ones(N), scheduled_time, distance, convective_index])true_logits = X_raw @ true_betatrue_probs = 1.0 / (1.0 + np.exp(-true_logits))y = (np.random.uniform(size=N) < true_probs).astype(int)
# Strictly enforce temporal split at day 90split_idx = 90 * FLIGHTS_PER_DAYX_train_raw, X_test_raw = X_raw[:split_idx], X_raw[split_idx:]y_train, y_test = y[:split_idx], y[split_idx:]days_train, days_test = days[:split_idx], days[split_idx:]
print({ 'total_observations': N, 'training_observations': len(y_train), 'holdout_observations': len(y_test), 'base_rate_train': float(np.mean(y_train)), 'base_rate_test': float(np.mean(y_test))}){'total_observations': 1200, 'training_observations': 900, 'holdout_observations': 300, 'base_rate_train': 0.28888888888888886, 'base_rate_test': 0.30333333333333334}
Implementation: IRLS Parameter Estimation
Section titled “Implementation: IRLS Parameter Estimation”We implement Newton-Raphson parameter estimation with an explicit regularization parameter .
Student Exercise (Stub)
Section titled “Student Exercise (Stub)”Review the implementation of fit_logistic_irls. Complete the Hessian and weight update steps, or verify that the baseline satisfies convergence criteria .
def fit_logistic_irls(X, y, l2_reg=0.01, max_iter=25, tol=1e-6): """Estimate logistic regression coefficients via Iteratively Reweighted Least Squares (IRLS).""" n_samples, n_features = X.shape beta = np.zeros(n_features)
for iteration in range(max_iter): p = 1.0 / (1.0 + np.exp(-np.clip(X @ beta, -30, 30))) # Weight diagonal: W_ii = p_i * (1 - p_i) w = p * (1.0 - p) w = np.clip(w, 1e-6, 1.0) # Numerical stabilization
# Gradient of penalized log-likelihood grad = X.T @ (y - p) - l2_reg * beta
# Hessian: H = - (X^T W X + l2_reg * I) W_X = X * w[:, np.newaxis] hessian = -(X.T @ W_X + l2_reg * np.eye(n_features))
# Newton-Raphson update: beta_new = beta - H^-1 * grad step = np.linalg.solve(-hessian, grad) beta_next = beta + step
if np.linalg.norm(step) < tol: break beta = beta_next
return beta
# Normalize features strictly using training set parameters (No information leakage)mean_train = np.mean(X_train_raw[:, 1:], axis=0)std_train = np.std(X_train_raw[:, 1:], axis=0)
X_train = np.column_stack([np.ones(len(X_train_raw)), (X_train_raw[:, 1:] - mean_train) / std_train])X_test = np.column_stack([np.ones(len(X_test_raw)), (X_test_raw[:, 1:] - mean_train) / std_train])
# Fit candidate model and constant-prior baselinebeta_hat = fit_logistic_irls(X_train, y_train, l2_reg=0.1)prior_prob = np.mean(y_train)
# Predict probabilities on unseen holdouttest_logits = X_test @ beta_hattest_probs = 1.0 / (1.0 + np.exp(-test_logits))baseline_probs = np.full(len(y_test), prior_prob)
print({'estimated_beta': [round(b, 4) for b in beta_hat], 'iterations_converged': True}){'estimated_beta': [np.float64(-0.9572), np.float64(0.399), np.float64(-0.106), np.float64(0.4779)], 'iterations_converged': True}
Strictly Proper Scoring Rules and Calibration
Section titled “Strictly Proper Scoring Rules and Calibration”We evaluate probability forecasts against the Brier score:
A forecasting system is well-calibrated if for all , .
brier_model = float(np.mean((test_probs - y_test) ** 2))brier_baseline = float(np.mean((baseline_probs - y_test) ** 2))
# Log-loss (Cross-entropy)eps = 1e-12logloss_model = -float(np.mean(y_test * np.log(test_probs + eps) + (1 - y_test) * np.log(1 - test_probs + eps)))logloss_baseline = -float(np.mean(y_test * np.log(baseline_probs + eps) + (1 - y_test) * np.log(1 - baseline_probs + eps)))
print(f"Model Brier Score: {brier_model:.4f} (Lower is better)")print(f"Baseline Brier Score: {brier_baseline:.4f}")print(f"Model Log-Loss: {logloss_model:.4f}")print(f"Baseline Log-Loss: {logloss_baseline:.4f}")
# Reliability Diagram (10 Decile Bins)bins = np.linspace(0, 1, 11)bin_assignments = np.digitize(test_probs, bins) - 1bin_confs, bin_accs, bin_counts = [], [], []
for b in range(10): mask = (bin_assignments == b) if np.sum(mask) > 0: bin_confs.append(np.mean(test_probs[mask])) bin_accs.append(np.mean(y_test[mask])) bin_counts.append(np.sum(mask))
fig, ax = plt.subplots(1, 2, figsize=(12, 4))ax[0].plot([0, 1], [0, 1], '--', color='#171817', label='Perfect Calibration')ax[0].plot(bin_confs, bin_accs, 's-', color='#1a7f64', label='IRLS Model')ax[0].set(xlabel='Mean Predicted Probability', ylabel='Empirical Proportion', title='Reliability Diagram')ax[0].legend(); ax[0].grid(True, alpha=0.3)
ax[1].plot(days_test, y_test, 'o', alpha=0.2, color='#6f706a', label='Actual Disruption')ax[1].plot(days_test, test_probs, color='#0969da', lw=1.5, label='Predicted P(Delay >= 30m)')ax[1].axhline(prior_prob, color='#cf222e', linestyle=':', label='Marginal Prior Baseline')ax[1].set(xlabel='Day', ylabel='Probability', title='Chronological Holdout Forecast')ax[1].legend(); ax[1].grid(True, alpha=0.3)plt.tight_layout(); plt.show()Model Brier Score: 0.1893 (Lower is better) Baseline Brier Score: 0.2115 Model Log-Loss: 0.5590 Baseline Log-Loss: 0.6142
Asymmetric Operational Loss and Bayes Decision Threshold
Section titled “Asymmetric Operational Loss and Bayes Decision Threshold”Let denote the cost of an unannounced flight delay (passenger stranding, gate congestion), and denote the cost of proactive meal voucher staging. The optimal Bayes threshold is:
thresholds = np.linspace(0.05, 0.80, 50)total_costs = []l_fn, l_fp = 5.0, 1.0
for tau in thresholds: decisions = (test_probs >= tau).astype(int) fn = np.sum((decisions == 0) & (y_test == 1)) fp = np.sum((decisions == 1) & (y_test == 0)) cost = fn * l_fn + fp * l_fp total_costs.append(cost)
opt_idx = np.argmin(total_costs)optimal_tau = thresholds[opt_idx]print(f"Optimal Decision Threshold (Empirical): tau* = {optimal_tau:.3f}")print(f"Theoretical Bayes Threshold: tau* = {l_fp / (l_fp + l_fn):.3f}")print(f"Total Operational Loss at tau*: {total_costs[opt_idx]:.1f} cost units")Optimal Decision Threshold (Empirical): tau* = 0.234 Theoretical Bayes Threshold: tau* = 0.167 Total Operational Loss at tau*: 165.0 cost units
Failure Probe and Method Invariants
Section titled “Failure Probe and Method Invariants”We deliberately inject non-finite values (NaN) to assert that the preprocessing pipeline fails closed rather than propagating unvalidated numbers into matrix operations.
broken_input = X_test.copy()broken_input[5, 2] = np.nan
try: if np.any(~np.isfinite(broken_input)): raise ValueError("Non-finite covariate detected in inference input matrix") _ = broken_input @ beta_hatexcept ValueError as err: print("EXPECTED REJECTION:", err)else: raise AssertionError("Validation failed to reject invalid input")EXPECTED REJECTION: Non-finite covariate detected in inference input matrix
Google Cloud Platform Transition
Section titled “Google Cloud Platform Transition”To execute this model in production on Google Cloud:
- BigQuery ML Baseline: Materialize the flight history table in BigQuery and run:
CREATE OR REPLACE MODEL `hs_ml.delay_baseline`OPTIONS(MODEL_TYPE = 'LOGISTIC_REG',INPUT_LABEL_COLS = ['is_delayed'],AUTO_CLASS_WEIGHTS = TRUE,DATA_SPLIT_METHOD = 'CUSTOM',DATA_SPLIT_COL = 'is_holdout') AS SELECT scheduled_time, distance, convective_index, is_delayed, is_holdout FROM `hs_data.flights`;
- Vertex AI Custom Training: Package
fit_logistic_irlsinto a containerized component and execute on Vertex AI Pipelines (Kubeflow SDK) with GPU/CPU quotas.
Execution Receipt
Section titled “Execution Receipt”display(JSON({ 'observations': int(N), 'holdout_size': int(len(y_test)), 'brier_score_model': round(brier_model, 4), 'brier_score_baseline': round(brier_baseline, 4), 'logloss_model': round(logloss_model, 4), 'optimal_threshold': round(float(optimal_tau), 3), 'theoretical_threshold': round(float(l_fp / (l_fp + l_fn)), 3), 'status': 'VERIFIED_CALIBRATION'})){
"brier_score_baseline": 0.2115,
"brier_score_model": 0.1893,
"holdout_size": 300,
"logloss_model": 0.559,
"observations": 1200,
"optimal_threshold": 0.234,
"status": "VERIFIED_CALIBRATION",
"theoretical_threshold": 0.167
}