{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9b3bc0f4",
   "metadata": {},
   "source": [
    "# Rearrest from a small table\n",
    "\n",
    "Made-up data: 2,000 people to learn from and 1,000 to predict. Compares NVIDIA's Kumo Tabular (the optional download in Local models) with logistic regression and LightGBM."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5bc38e8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "rng = np.random.default_rng(7)\n",
    "n = 3000\n",
    "people = pd.DataFrame({\n",
    "    'age': rng.integers(18, 60, n),\n",
    "    'priors': rng.poisson(2, n),\n",
    "    'program': rng.integers(0, 2, n),\n",
    "    'beat': rng.choice(['A', 'B', 'C'], n),\n",
    "})\n",
    "logit = (-1 + 0.3 * people['priors'] - 0.03 * (people['age'] - 30)\n",
    "         + 0.5 * (people['beat'] == 'B'))\n",
    "people['y'] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)\n",
    "train, test = people.iloc[:2000].copy(), people.iloc[2000:].copy()\n",
    "x_vars = ['age', 'priors', 'program', 'beat']\n",
    "rate = people['y'].mean()\n",
    "print(f'{len(train):,} to learn from, {len(test):,} to predict, {rate:.0%} rearrested')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a437eeab",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "import sdm\n",
    "import torch\n",
    "from sklearn.metrics import roc_auc_score\n",
    "\n",
    "start = time.time()\n",
    "model = sdm.models.KumoTabular(task='classification', size='small', device='cpu')\n",
    "both = pd.concat([train[x_vars], test[x_vars]], ignore_index=True)\n",
    "both['y'] = pd.array([str(v) for v in train['y']] + [None] * len(test), dtype='string')\n",
    "numeric = pd.api.types.is_numeric_dtype\n",
    "stypes = {c: 'numerical' if numeric(both[c]) else 'categorical' for c in x_vars}\n",
    "stypes['y'] = 'categorical'\n",
    "table = sdm.TableTensor.from_pandas(both, stypes, device='cpu')\n",
    "k = len(train)\n",
    "with torch.no_grad():\n",
    "    out = model(x_context=table[:k].drop_columns('y'), y_context=table[:k, 'y'],\n",
    "                x_query=table[k:].drop_columns('y'), num_estimators=1,\n",
    "                generator=torch.Generator().manual_seed(1))\n",
    "labels = [str(c) for c in out.columns[sdm.Stype.numerical]]\n",
    "test['Kumo'] = out.numerical.float().numpy()[:, labels.index('1')]\n",
    "auc = roc_auc_score(test['y'], test['Kumo'])\n",
    "print(f'Kumo Tabular AUC {auc:.3f} ({time.time() - start:.0f} seconds)')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dff527d",
   "metadata": {},
   "source": [
    "The same people with the usual models:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e8e4949",
   "metadata": {},
   "outputs": [],
   "source": [
    "import lightgbm as lgb\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "X_train = pd.get_dummies(train[x_vars], columns=['beat'], dtype=float)\n",
    "X_test = pd.get_dummies(test[x_vars], columns=['beat'], dtype=float)\n",
    "logistic = LogisticRegression(max_iter=1000).fit(X_train, train['y'])\n",
    "test['Logit'] = logistic.predict_proba(X_test)[:, 1]\n",
    "boost = lgb.LGBMClassifier(n_estimators=300, learning_rate=0.05, verbose=-1)\n",
    "test['LightGBM'] = boost.fit(X_train, train['y']).predict_proba(X_test)[:, 1]\n",
    "for name in ['Kumo', 'Logit', 'LightGBM']:\n",
    "    print(f\"{name} AUC {roc_auc_score(test['y'], test[name]):.3f}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
