Feature Space Invariance, High-Cardinality Encodings, and Risk Minimization
Encode high-cardinality categories such as airlines and concourses with Bayesian shrinkage, so unseen categories stay safe at inference time.
Part II: 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-LOG-04 · Menu and allergen agent (directed by Linh Nguyen)
Operational Objective: Encode high-cardinality nominal categories (airlines, terminal concourses) with Bayesian shrinkage to guarantee vector-space invariance under unobserved categories at inference time.
Mathematical Formulation
Section titled “Mathematical Formulation”Let categorical feature have sample frequencies . Standard one-hot encoding expands into a sparse vector . When novel categories arrive at inference time (), dimension mismatch occurs:
We resolve this via Empirical Bayes target encoding with smoothing parameter :
where is the within-category sample mean, and is the global prior. For rare categories (), ; for high-frequency categories (), .
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, scikit-learn, 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 sysimport numpy as npimport matplotlib.pyplot as pltfrom IPython.display import display, Markdown, JSONfrom sklearn.linear_model import LogisticRegression
SEED = 42np.random.seed(SEED)print({'python': sys.version.split()[0], 'seed': SEED, 'module': '02-encoding-and-invariance'}){'python': '3.12.12', 'seed': 42, 'module': '02-encoding-and-invariance'}
Data and Categorical Long Tails
Section titled “Data and Categorical Long Tails”We construct a synthetic dataset of flight records featuring 35 distinct carrier codes following a power-law frequency distribution. Carrier frequencies range from major hub carriers () to regional charter operators (). The evaluation partition deliberately introduces two unobserved carriers.
# 35 airline carriers with heavy-tailed frequency distributionmajor_carriers = ['DAL', 'SWA', 'AAL', 'UAL']regional_carriers = [f'REG_{i:02d}' for i in range(25)]rare_charters = ['CHTR_A', 'CHTR_B', 'CHTR_C', 'CHTR_D', 'CHTR_NEW1', 'CHTR_NEW2']
all_known = major_carriers + regional_carriers + rare_charters[:4]weights = [400, 250, 180, 120] + [15] * 25 + [3, 2, 2, 1]probs = np.array(weights) / sum(weights)
N_TRAIN = 1600N_TEST = 400
carriers_train = np.random.choice(all_known, size=N_TRAIN, p=probs)# Test set includes unobserved carriers CHTR_NEW1 and CHTR_NEW2test_vocab = all_known + rare_charters[4:]test_weights = list(weights) + [5, 5]test_probs = np.array(test_weights) / sum(test_weights)carriers_test = np.random.choice(test_vocab, size=N_TEST, p=test_probs)
# True carrier-specific delay propensity + noisecarrier_bias = {c: np.random.normal(loc=0.0, scale=0.8) for c in test_vocab}carrier_bias['DAL'] = -0.4 # Major carrier with low delay ratecarrier_bias['CHTR_A'] = 1.2 # High delay rate
def generate_outcomes(carriers): logits = np.array([carrier_bias[c] for c in carriers]) + np.random.normal(0, 0.5, size=len(carriers)) p = 1.0 / (1.0 + np.exp(-logits)) return (np.random.uniform(size=len(carriers)) < p).astype(int)
y_train = generate_outcomes(carriers_train)y_test = generate_outcomes(carriers_test)
print({ 'train_records': N_TRAIN, 'test_records': N_TEST, 'distinct_carriers_train': len(np.unique(carriers_train)), 'distinct_carriers_test': len(np.unique(carriers_test)), 'unseen_test_carriers': list(set(carriers_test) - set(carriers_train))}){'train_records': 1600, 'test_records': 400, 'distinct_carriers_train': 33, 'distinct_carriers_test': 32, 'unseen_test_carriers': [np.str_('CHTR_NEW1'), np.str_('CHTR_NEW2')]}
Implementation: Empirical Bayes Target Encoding
Section titled “Implementation: Empirical Bayes Target Encoding”We implement target encoding with -estimate smoothing. Unseen categories naturally collapse to the global prior without raising dimension mismatch errors.
Student Exercise (Stub)
Section titled “Student Exercise (Stub)”Review EmpiricalBayesEncoder. Implement transform to ensure that novel categories never trigger key errors and output finite scalar representations.
class EmpiricalBayesEncoder: def __init__(self, m_smoothing=10.0): self.m = m_smoothing self.global_mean = 0.0 self.category_means = {} self.category_weights = {}
def fit(self, categories, targets): self.global_mean = float(np.mean(targets)) unique_cats = np.unique(categories)
for c in unique_cats: mask = (categories == c) n_c = np.sum(mask) mean_c = np.mean(targets[mask]) lambda_c = n_c / (n_c + self.m) self.category_means[c] = float(lambda_c * mean_c + (1.0 - lambda_c) * self.global_mean) self.category_weights[c] = n_c return self
def transform(self, categories): # Fallback to global_mean for unobserved categories (Invariance Guarantee) return np.array([self.category_means.get(c, self.global_mean) for c in categories])
# Fit encoder strictly on training partitionencoder = EmpiricalBayesEncoder(m_smoothing=15.0)encoder.fit(carriers_train, y_train)
X_train_encoded = encoder.transform(carriers_train).reshape(-1, 1)X_test_encoded = encoder.transform(carriers_test).reshape(-1, 1)
# Fit regularized linear logistic modelclf = LogisticRegression(C=1.0)clf.fit(X_train_encoded, y_train)
test_preds_prob = clf.predict_proba(X_test_encoded)[:, 1]print({'global_prior': round(encoder.global_mean, 4), 'encoded_shape_test': X_test_encoded.shape}){'global_prior': 0.4469, 'encoded_shape_test': (400, 1)}
Comparison: Empirical Bayes vs One-Hot Encoding
Section titled “Comparison: Empirical Bayes vs One-Hot Encoding”We contrast the dimension stability of the Bayesian representation against one-hot encoding under categorical shifts.
# Evaluate one-hot dimension failureunique_train_cats = list(np.unique(carriers_train))one_hot_train = np.column_stack([[int(c == cat) for cat in unique_train_cats] for c in carriers_train])
# Attempting one-hot projection on test setunseen_count = sum(1 for c in carriers_test if c not in unique_train_cats)print(f"Number of test instances with unobserved categories: {unseen_count}")print(f"One-Hot Train Feature Space: R^{one_hot_train.shape[1]}")print(f"Target Encoded Feature Space: R^{X_train_encoded.shape[1]} (Invariant)")
brier_eb = float(np.mean((test_preds_prob - y_test) ** 2))print(f"Empirical Bayes Model Brier Score: {brier_eb:.4f}")Number of test instances with unobserved categories: 5 One-Hot Train Feature Space: R^1600 Target Encoded Feature Space: R^1 (Invariant) Empirical Bayes Model Brier Score: 0.2381
Decision Theory: Cost-Weighted Bayes Decision
Section titled “Decision Theory: Cost-Weighted Bayes Decision”We apply the optimal decision threshold where and .
cost_fn, cost_fp = 4.0, 1.0tau_star = cost_fp / (cost_fp + cost_fn)
decisions_optimal = (test_preds_prob >= tau_star).astype(int)decisions_default = (test_preds_prob >= 0.50).astype(int)
loss_optimal = np.sum((decisions_optimal == 0) & (y_test == 1)) * cost_fn + np.sum((decisions_optimal == 1) & (y_test == 0)) * cost_fploss_default = np.sum((decisions_default == 0) & (y_test == 1)) * cost_fn + np.sum((decisions_default == 1) & (y_test == 0)) * cost_fp
print(f"Bayes-Optimal Threshold (tau={tau_star:.3f}) Loss: {loss_optimal:.1f} units")print(f"Default Heuristic Threshold (tau=0.500) Loss: {loss_default:.1f} units")print(f"Loss Reduction: {(loss_default - loss_optimal) / loss_default * 100:.1f}%")Bayes-Optimal Threshold (tau=0.200) Loss: 230.0 units Default Heuristic Threshold (tau=0.500) Loss: 553.0 units Loss Reduction: 58.4%
Method Invariant and Failure Probe
Section titled “Method Invariant and Failure Probe”Verify that an unobserved carrier string does not produce NaN or unhandled exceptions.
unseen_carrier_vector = np.array(['UNKNOWN_CARRIER_XYZ', 'ANOTHER_NOVEL_AIR'])encoded_val = encoder.transform(unseen_carrier_vector)
assert np.all(encoded_val == encoder.global_mean), "Unseen category failed to collapse to global prior"print("EXPECTED BEHAVIOR: Unseen categories assigned global prior:", encoded_val)EXPECTED BEHAVIOR: Unseen categories assigned global prior: [0.446875 0.446875]
Google Cloud Platform Transition
Section titled “Google Cloud Platform Transition”- Vertex AI Feature Store: Register carrier target encodings as aggregate feature views in BigQuery and sync to the online feature store.
- BigQuery ML: Implement automated target encoding in SQL via
ML.TARGET_ENCODERor manual windowed grouping.
display(JSON({ 'train_categories': len(np.unique(carriers_train)), 'test_unseen_instances': int(unseen_count), 'brier_score': round(brier_eb, 4), 'bayes_loss_optimal': round(float(loss_optimal), 2), 'bayes_loss_default': round(float(loss_default), 2), 'status': 'VERIFIED_INVARIANCE'})){
"bayes_loss_default": 553,
"bayes_loss_optimal": 230,
"brier_score": 0.2381,
"status": "VERIFIED_INVARIANCE",
"test_unseen_instances": 5,
"train_categories": 33
}