Skip to content
Mementropy
SolutionshungersyncNotebookExecuted example

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.

By Ryan HammangUpdated

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.

Let categorical feature c∈Cc \in \mathcal{C} have sample frequencies nc=∑i=1NI(ci=c)n_c = \sum_{i=1}^N \mathbb{I}(c_i = c). Standard one-hot encoding expands cc into a sparse vector ec∈{0,1}∣C∣\mathbf{e}_c \in \{0, 1\}^{|\mathcal{C}|}. When novel categories arrive at inference time (cnew∉Ctrainc_{\text{new}} \notin \mathcal{C}_{\text{train}}), dimension mismatch occurs:

xserving∉span(Xtrain)\mathbf{x}_{\text{serving}} \notin \text{span}(\mathbf{X}_{\text{train}})

We resolve this via Empirical Bayes target encoding with smoothing parameter m>0m > 0:

S^c=λ(nc)yˉc+(1−λ(nc))yˉ,λ(nc)=ncnc+m\hat{S}_c = \lambda(n_c) \bar{y}_c + (1 - \lambda(n_c)) \bar{y}, \quad \lambda(n_c) = \frac{n_c}{n_c + m}

where yˉc=1nc∑i∈cyi\bar{y}_c = \frac{1}{n_c} \sum_{i \in c} y_i is the within-category sample mean, and yˉ=1N∑i=1Nyi\bar{y} = \frac{1}{N} \sum_{i=1}^N y_i is the global prior. For rare categories (nc→0n_c \to 0), S^c→yˉ\hat{S}_c \to \bar{y}; for high-frequency categories (nc≫mn_c \gg m), S^c→yˉc\hat{S}_c \to \bar{y}_c.

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

We construct a synthetic dataset of N=2,000N=2,000 flight records featuring 35 distinct carrier codes following a power-law frequency distribution. Carrier frequencies range from major hub carriers (Nc>600N_c > 600) to regional charter operators (Nc≤3N_c \le 3). The evaluation partition deliberately introduces two unobserved carriers.

# 35 airline carriers with heavy-tailed frequency distribution
major_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 = 1600
N_TEST = 400
carriers_train = np.random.choice(all_known, size=N_TRAIN, p=probs)
# Test set includes unobserved carriers CHTR_NEW1 and CHTR_NEW2
test_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 + noise
carrier_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 rate
carrier_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 mm-estimate smoothing. Unseen categories naturally collapse to the global prior yˉ\bar{y} without raising dimension mismatch errors.

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 partition
encoder = 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 model
clf = 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 failure
unique_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 set
unseen_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 τ∗=LFPLFP+LFN\tau^* = \frac{L_{\text{FP}}}{L_{\text{FP}} + L_{\text{FN}}} where LFN=4.0L_{\text{FN}} = 4.0 and LFP=1.0L_{\text{FP}} = 1.0.

cost_fn, cost_fp = 4.0, 1.0
tau_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_fp
loss_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%

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]
  1. Vertex AI Feature Store: Register carrier target encodings as aggregate feature views in BigQuery and sync to the online feature store.
  2. BigQuery ML: Implement automated target encoding in SQL via ML.TARGET_ENCODER or 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
}