Skip to content
Mementropy
SolutionshungersyncNotebookExecuted example

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.

By Ryan HammangUpdated

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 (Y=1Y=1) under non-stationary weather and flight schedules, without temporal lookahead contamination.

Let (xi,yi)(\mathbf{x}_i, y_i) be independent observations where xi∈Rd\mathbf{x}_i \in \mathbb{R}^d represents flight covariates (distance, scheduled block time, convective weather severity) and yi∈{0,1}y_i \in \{0, 1\} denotes arrival delay Di≥30 minutesD_i \ge 30\text{ minutes}. We specify the linear logistic model:

logit(p(xi;β))=ln⁡(p(xi)1−p(xi))=β0+xiTβ\text{logit}(p(\mathbf{x}_i; \boldsymbol{\beta})) = \ln\left(\frac{p(\mathbf{x}_i)}{1 - p(\mathbf{x}_i)}\right) = \beta_0 + \mathbf{x}_i^T \boldsymbol{\beta}

The parameter vector β\boldsymbol{\beta} is estimated by maximizing the L2L_2-penalized log-likelihood:

ℓ(β)=∑i=1N[yiln⁡p(xi;β)+(1−yi)ln⁡(1−p(xi;β))]−λ2∥β∥22\ell(\boldsymbol{\beta}) = \sum_{i=1}^N \left[ y_i \ln p(\mathbf{x}_i; \boldsymbol{\beta}) + (1 - y_i) \ln(1 - p(\mathbf{x}_i; \boldsymbol{\beta})) \right] - \frac{\lambda}{2} \|\boldsymbol{\beta}\|_2^2

Optimization is performed via Newton-Raphson / Iteratively Reweighted Least Squares (IRLS):

β(t+1)=(XTW(t)X+λI)−1XTW(t)z(t)\boldsymbol{\beta}^{(t+1)} = \left( \mathbf{X}^T \mathbf{W}^{(t)} \mathbf{X} + \lambda \mathbf{I} \right)^{-1} \mathbf{X}^T \mathbf{W}^{(t)} \mathbf{z}^{(t)}

where Wii=pi(1−pi)W_{ii} = p_i(1 - p_i) and z=Xβ+W−1(y−p)\mathbf{z} = \mathbf{X}\boldsymbol{\beta} + \mathbf{W}^{-1}(\mathbf{y} - \mathbf{p}).

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 random
import statistics
import sys
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, Markdown, JSON
SEED = 42
np.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'}

We simulate N=1,200N=1,200 chronological flight arrival records across T=120T=120 days at ATL. The temporal filtration Ft=σ({(xs,ys):s≤t})\mathcal{F}_t = \sigma(\{(\mathbf{x}_s, y_s) : s \le t\}) strictly governs what data the estimator may observe.

  • Training partition: Days 11 to 9090 (Ntrain=900N_{\text{train}} = 900).
  • Holdout evaluation partition: Days 9191 to 120120 (Ntest=300N_{\text{test}} = 300).

Under no circumstances may training features be computed using summary statistics (e.g., sample mean xˉ\bar{x}, standard deviation ss) calculated over the combined dataset.

# Generate synthetic non-stationary arrival series
N_DAYS = 120
FLIGHTS_PER_DAY = 10
N = 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 periods
convective_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 function
true_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_beta
true_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 90
split_idx = 90 * FLIGHTS_PER_DAY
X_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}

We implement Newton-Raphson parameter estimation with an explicit L2L_2 regularization parameter λ=10−2\lambda = 10^{-2}.

Review the implementation of fit_logistic_irls. Complete the Hessian and weight update steps, or verify that the baseline satisfies convergence criteria ∥β(t+1)−β(t)∥2<ϵ\|\boldsymbol{\beta}^{(t+1)} - \boldsymbol{\beta}^{(t)}\|_2 < \epsilon.

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 baseline
beta_hat = fit_logistic_irls(X_train, y_train, l2_reg=0.1)
prior_prob = np.mean(y_train)
# Predict probabilities on unseen holdout
test_logits = X_test @ beta_hat
test_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:

BS=1N∑i=1N(p^i−yi)2\text{BS} = \frac{1}{N} \sum_{i=1}^N (\hat{p}_i - y_i)^2

A forecasting system is well-calibrated if for all p∈[0,1]p \in [0, 1], P(Y=1∣p^=p)=pP(Y = 1 \mid \hat{p} = p) = p.

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-12
logloss_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) - 1
bin_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
0.0 0.2 0.4 0.6 0.8 1.0 Mean Predicted Probability 0.0 0.2 0.4 0.6 0.8 1.0 Empirical Proportion Reliability Diagram Perfect Calibration IRLS Model 90 95 100 105 110 115 120 Day 0.0 0.2 0.4 0.6 0.8 1.0 Probability Chronological Holdout Forecast Actual Disruption Predicted P(Delay >= 30m) Marginal Prior Baseline

Asymmetric Operational Loss and Bayes Decision Threshold

Section titled “Asymmetric Operational Loss and Bayes Decision Threshold”

Let LFN=5L_{\text{FN}} = 5 denote the cost of an unannounced flight delay (passenger stranding, gate congestion), and LFP=1L_{\text{FP}} = 1 denote the cost of proactive meal voucher staging. The optimal Bayes threshold is:

τ∗=LFPLFP+LFN=11+5≈0.1667\tau^* = \frac{L_{\text{FP}}}{L_{\text{FP}} + L_{\text{FN}}} = \frac{1}{1 + 5} \approx 0.1667
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

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_hat
except 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

To execute this model in production on Google Cloud:

  1. 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`;
  2. Vertex AI Custom Training: Package fit_logistic_irls into a containerized component and execute on Vertex AI Pipelines (Kubeflow SDK) with GPU/CPU quotas.
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
}