{
 "cells": [
  {
   "id": "cell-00",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# Feature Space Invariance, High-Cardinality Encodings, and Risk Minimization\n",
    "**Part II: The Flight Disruption Binary Classifier Series**\n",
    "\n",
    "**Authoring standard:** *The Elements of Statistical Learning* (Hastie, Tibshirani, Friedman)  \n",
    "**Setting:** Hartsfield-Jackson Atlanta International Airport (ATL)  \n",
    "**Case linkage:** `HS-LOG-04` · Menu and allergen agent (directed by Linh Nguyen)  \n",
    "**Operational Objective:** Encode high-cardinality nominal categories (airlines, terminal concourses) with Bayesian shrinkage to guarantee vector-space invariance under unobserved categories at inference time.\n",
    "\n",
    "### Mathematical Formulation\n",
    "Let categorical feature $c \\in \\mathcal{C}$ have sample frequencies $n_c = \\sum_{i=1}^N \\mathbb{I}(c_i = c)$.\n",
    "Standard one-hot encoding expands $c$ into a sparse vector $\\mathbf{e}_c \\in \\{0, 1\\}^{|\\mathcal{C}|}$. When novel categories arrive at inference time ($c_{\\text{new}} \\notin \\mathcal{C}_{\\text{train}}$), dimension mismatch occurs:\n",
    "\n",
    "$$\\mathbf{x}_{\\text{serving}} \\notin \\text{span}(\\mathbf{X}_{\\text{train}})$$\n",
    "\n",
    "We resolve this via Empirical Bayes target encoding with smoothing parameter $m > 0$:\n",
    "\n",
    "$$\\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}$$\n",
    "\n",
    "where $\\bar{y}_c = \\frac{1}{n_c} \\sum_{i \\in c} y_i$ is the within-category sample mean, and $\\bar{y} = \\frac{1}{N} \\sum_{i=1}^N y_i$ is the global prior. For rare categories ($n_c \\to 0$), $\\hat{S}_c \\to \\bar{y}$; for high-frequency categories ($n_c \\gg m$), $\\hat{S}_c \\to \\bar{y}_c$.\n"
   ]
  },
  {
   "id": "cell-01",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## Prerequisites and support\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "**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.\n"
   ]
  },
  {
   "id": "cell-02",
   "metadata": {},
   "cell_type": "code",
   "execution_count": 2,
   "source": [
    "import sys\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from IPython.display import display, Markdown, JSON\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "SEED = 42\n",
    "np.random.seed(SEED)\n",
    "print({'python': sys.version.split()[0], 'seed': SEED, 'module': '02-encoding-and-invariance'})\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'python': '3.12.12', 'seed': 42, 'module': '02-encoding-and-invariance'}\n"
     ]
    }
   ]
  },
  {
   "id": "cell-03",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## Data and Categorical Long Tails\n",
    "We construct a synthetic dataset of $N=2,000$ flight records featuring 35 distinct carrier codes following a power-law frequency distribution.\n",
    "Carrier frequencies range from major hub carriers ($N_c > 600$) to regional charter operators ($N_c \\le 3$). The evaluation partition deliberately introduces two unobserved carriers.\n"
   ]
  },
  {
   "id": "cell-04",
   "metadata": {},
   "cell_type": "code",
   "execution_count": 3,
   "source": [
    "# 35 airline carriers with heavy-tailed frequency distribution\n",
    "major_carriers = ['DAL', 'SWA', 'AAL', 'UAL']\n",
    "regional_carriers = [f'REG_{i:02d}' for i in range(25)]\n",
    "rare_charters = ['CHTR_A', 'CHTR_B', 'CHTR_C', 'CHTR_D', 'CHTR_NEW1', 'CHTR_NEW2']\n",
    "\n",
    "all_known = major_carriers + regional_carriers + rare_charters[:4]\n",
    "weights = [400, 250, 180, 120] + [15] * 25 + [3, 2, 2, 1]\n",
    "probs = np.array(weights) / sum(weights)\n",
    "\n",
    "N_TRAIN = 1600\n",
    "N_TEST = 400\n",
    "\n",
    "carriers_train = np.random.choice(all_known, size=N_TRAIN, p=probs)\n",
    "# Test set includes unobserved carriers CHTR_NEW1 and CHTR_NEW2\n",
    "test_vocab = all_known + rare_charters[4:]\n",
    "test_weights = list(weights) + [5, 5]\n",
    "test_probs = np.array(test_weights) / sum(test_weights)\n",
    "carriers_test = np.random.choice(test_vocab, size=N_TEST, p=test_probs)\n",
    "\n",
    "# True carrier-specific delay propensity + noise\n",
    "carrier_bias = {c: np.random.normal(loc=0.0, scale=0.8) for c in test_vocab}\n",
    "carrier_bias['DAL'] = -0.4 # Major carrier with low delay rate\n",
    "carrier_bias['CHTR_A'] = 1.2 # High delay rate\n",
    "\n",
    "def generate_outcomes(carriers):\n",
    "    logits = np.array([carrier_bias[c] for c in carriers]) + np.random.normal(0, 0.5, size=len(carriers))\n",
    "    p = 1.0 / (1.0 + np.exp(-logits))\n",
    "    return (np.random.uniform(size=len(carriers)) < p).astype(int)\n",
    "\n",
    "y_train = generate_outcomes(carriers_train)\n",
    "y_test = generate_outcomes(carriers_test)\n",
    "\n",
    "print({\n",
    "    'train_records': N_TRAIN,\n",
    "    'test_records': N_TEST,\n",
    "    'distinct_carriers_train': len(np.unique(carriers_train)),\n",
    "    'distinct_carriers_test': len(np.unique(carriers_test)),\n",
    "    'unseen_test_carriers': list(set(carriers_test) - set(carriers_train))\n",
    "})\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'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')]}\n"
     ]
    }
   ]
  },
  {
   "id": "cell-05",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## Implementation: Empirical Bayes Target Encoding\n",
    "We implement target encoding with $m$-estimate smoothing. Unseen categories naturally collapse to the global prior $\\bar{y}$ without raising dimension mismatch errors.\n",
    "\n",
    "### Student Exercise (Stub)\n",
    "Review `EmpiricalBayesEncoder`. Implement `transform` to ensure that novel categories never trigger key errors and output finite scalar representations.\n"
   ]
  },
  {
   "id": "cell-06",
   "metadata": {},
   "cell_type": "code",
   "execution_count": 4,
   "source": [
    "class EmpiricalBayesEncoder:\n",
    "    def __init__(self, m_smoothing=10.0):\n",
    "        self.m = m_smoothing\n",
    "        self.global_mean = 0.0\n",
    "        self.category_means = {}\n",
    "        self.category_weights = {}\n",
    "\n",
    "    def fit(self, categories, targets):\n",
    "        self.global_mean = float(np.mean(targets))\n",
    "        unique_cats = np.unique(categories)\n",
    "        \n",
    "        for c in unique_cats:\n",
    "            mask = (categories == c)\n",
    "            n_c = np.sum(mask)\n",
    "            mean_c = np.mean(targets[mask])\n",
    "            lambda_c = n_c / (n_c + self.m)\n",
    "            self.category_means[c] = float(lambda_c * mean_c + (1.0 - lambda_c) * self.global_mean)\n",
    "            self.category_weights[c] = n_c\n",
    "        return self\n",
    "\n",
    "    def transform(self, categories):\n",
    "        # Fallback to global_mean for unobserved categories (Invariance Guarantee)\n",
    "        return np.array([self.category_means.get(c, self.global_mean) for c in categories])\n",
    "\n",
    "# Fit encoder strictly on training partition\n",
    "encoder = EmpiricalBayesEncoder(m_smoothing=15.0)\n",
    "encoder.fit(carriers_train, y_train)\n",
    "\n",
    "X_train_encoded = encoder.transform(carriers_train).reshape(-1, 1)\n",
    "X_test_encoded = encoder.transform(carriers_test).reshape(-1, 1)\n",
    "\n",
    "# Fit regularized linear logistic model\n",
    "clf = LogisticRegression(C=1.0)\n",
    "clf.fit(X_train_encoded, y_train)\n",
    "\n",
    "test_preds_prob = clf.predict_proba(X_test_encoded)[:, 1]\n",
    "print({'global_prior': round(encoder.global_mean, 4), 'encoded_shape_test': X_test_encoded.shape})\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'global_prior': 0.4469, 'encoded_shape_test': (400, 1)}\n"
     ]
    }
   ]
  },
  {
   "id": "cell-07",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## Comparison: Empirical Bayes vs One-Hot Encoding\n",
    "We contrast the dimension stability of the Bayesian representation against one-hot encoding under categorical shifts.\n"
   ]
  },
  {
   "id": "cell-08",
   "metadata": {},
   "cell_type": "code",
   "execution_count": 5,
   "source": [
    "# Evaluate one-hot dimension failure\n",
    "unique_train_cats = list(np.unique(carriers_train))\n",
    "one_hot_train = np.column_stack([[int(c == cat) for cat in unique_train_cats] for c in carriers_train])\n",
    "\n",
    "# Attempting one-hot projection on test set\n",
    "unseen_count = sum(1 for c in carriers_test if c not in unique_train_cats)\n",
    "print(f\"Number of test instances with unobserved categories: {unseen_count}\")\n",
    "print(f\"One-Hot Train Feature Space:  R^{one_hot_train.shape[1]}\")\n",
    "print(f\"Target Encoded Feature Space: R^{X_train_encoded.shape[1]} (Invariant)\")\n",
    "\n",
    "brier_eb = float(np.mean((test_preds_prob - y_test) ** 2))\n",
    "print(f\"Empirical Bayes Model Brier Score: {brier_eb:.4f}\")\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of test instances with unobserved categories: 5\n",
      "One-Hot Train Feature Space:  R^1600\n",
      "Target Encoded Feature Space: R^1 (Invariant)\n",
      "Empirical Bayes Model Brier Score: 0.2381\n"
     ]
    }
   ]
  },
  {
   "id": "cell-09",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## Decision Theory: Cost-Weighted Bayes Decision\n",
    "We apply the optimal decision threshold $\\tau^* = \\frac{L_{\\text{FP}}}{L_{\\text{FP}} + L_{\\text{FN}}}$ where $L_{\\text{FN}} = 4.0$ and $L_{\\text{FP}} = 1.0$.\n"
   ]
  },
  {
   "id": "cell-10",
   "metadata": {},
   "cell_type": "code",
   "execution_count": 6,
   "source": [
    "cost_fn, cost_fp = 4.0, 1.0\n",
    "tau_star = cost_fp / (cost_fp + cost_fn)\n",
    "\n",
    "decisions_optimal = (test_preds_prob >= tau_star).astype(int)\n",
    "decisions_default = (test_preds_prob >= 0.50).astype(int)\n",
    "\n",
    "loss_optimal = np.sum((decisions_optimal == 0) & (y_test == 1)) * cost_fn + np.sum((decisions_optimal == 1) & (y_test == 0)) * cost_fp\n",
    "loss_default = np.sum((decisions_default == 0) & (y_test == 1)) * cost_fn + np.sum((decisions_default == 1) & (y_test == 0)) * cost_fp\n",
    "\n",
    "print(f\"Bayes-Optimal Threshold (tau={tau_star:.3f}) Loss: {loss_optimal:.1f} units\")\n",
    "print(f\"Default Heuristic Threshold (tau=0.500) Loss: {loss_default:.1f} units\")\n",
    "print(f\"Loss Reduction: {(loss_default - loss_optimal) / loss_default * 100:.1f}%\")\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bayes-Optimal Threshold (tau=0.200) Loss: 230.0 units\n",
      "Default Heuristic Threshold (tau=0.500) Loss: 553.0 units\n",
      "Loss Reduction: 58.4%\n"
     ]
    }
   ]
  },
  {
   "id": "cell-11",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## Method Invariant and Failure Probe\n",
    "Verify that an unobserved carrier string does not produce `NaN` or unhandled exceptions.\n"
   ]
  },
  {
   "id": "cell-12",
   "metadata": {},
   "cell_type": "code",
   "execution_count": 7,
   "source": [
    "unseen_carrier_vector = np.array(['UNKNOWN_CARRIER_XYZ', 'ANOTHER_NOVEL_AIR'])\n",
    "encoded_val = encoder.transform(unseen_carrier_vector)\n",
    "\n",
    "assert np.all(encoded_val == encoder.global_mean), \"Unseen category failed to collapse to global prior\"\n",
    "print(\"EXPECTED BEHAVIOR: Unseen categories assigned global prior:\", encoded_val)\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EXPECTED BEHAVIOR: Unseen categories assigned global prior: [0.446875 0.446875]\n"
     ]
    }
   ]
  },
  {
   "id": "cell-13",
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## Google Cloud Platform Transition\n",
    "1. **Vertex AI Feature Store:** Register carrier target encodings as aggregate feature views in BigQuery and sync to the online feature store.\n",
    "2. **BigQuery ML:** Implement automated target encoding in SQL via `ML.TARGET_ENCODER` or manual windowed grouping.\n"
   ]
  },
  {
   "id": "cell-14",
   "metadata": {
    "tags": [
     "vit-result"
    ]
   },
   "cell_type": "code",
   "execution_count": 8,
   "source": [
    "display(JSON({\n",
    "    'train_categories': len(np.unique(carriers_train)),\n",
    "    'test_unseen_instances': int(unseen_count),\n",
    "    'brier_score': round(brier_eb, 4),\n",
    "    'bayes_loss_optimal': round(float(loss_optimal), 2),\n",
    "    'bayes_loss_default': round(float(loss_default), 2),\n",
    "    'status': 'VERIFIED_INVARIANCE'\n",
    "}))\n"
   ],
   "outputs": [
    {
     "data": {
      "application/json": {
       "bayes_loss_default": 553,
       "bayes_loss_optimal": 230,
       "brier_score": 0.2381,
       "status": "VERIFIED_INVARIANCE",
       "test_unseen_instances": 5,
       "train_categories": 33
      },
      "text/plain": [
       "<IPython.core.display.JSON object>"
      ]
     },
     "metadata": {
      "application/json": {
       "expanded": false,
       "root": "root"
      }
     },
     "output_type": "display_data"
    }
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12.12"
  },
  "mementropy": {
   "contentKind": "notebook",
   "world": "hungersync",
   "capabilities": [
    "categorical-encoding",
    "inference-validation"
   ],
   "implementations": [
    "NumPy",
    "scikit-learn",
    "Matplotlib",
    "IPython"
   ],
   "evidenceStatus": "executed-example",
   "updatedDate": "2026-10-29"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
