{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8fa7ddcb",
   "metadata": {},
   "source": [
    "# ¿Quién no va a llegar a su cita?\n",
    "\n",
    "Modelo de riesgo de inasistencia para una IPS ambulatoria. Caso demostrativo de [Telar](https://telar.site): la IPS y los datos son sintéticos, el método es el que usaríamos con datos reales.\n",
    "\n",
    "**Pregunta de negocio.** Cerca de una de cada cinco citas queda vacía porque el paciente no llega ni avisa. Recepción puede llamar a unos 30 pacientes al día para confirmar. ¿A cuáles llamar?\n",
    "\n",
    "**Decisiones de diseño.**\n",
    "- Partición temporal: entrenamos con las citas hasta mayo de 2026 y evaluamos con las de junio en adelante, como se usaría en la práctica.\n",
    "- Comparamos una regresión logística, que se puede explicar factor por factor, con un modelo de *gradient boosting*.\n",
    "- Revisamos la calibración (que un 30 % de riesgo signifique de verdad 30 %) y el comportamiento por régimen de afiliación."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4e65ba42",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T01:50:24.092382Z",
     "iopub.status.busy": "2026-10-30T01:50:24.092020Z",
     "iopub.status.idle": "2026-10-30T01:50:25.255613Z",
     "shell.execute_reply": "2026-10-30T01:50:25.254443Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20,503 citas entre 01/03/2025 y 21/10/2026\n",
      "Tasa de inasistencia: 20.7%\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>fecha</th>\n",
       "      <th>dia_semana</th>\n",
       "      <th>hora</th>\n",
       "      <th>especialidad</th>\n",
       "      <th>edad</th>\n",
       "      <th>sexo</th>\n",
       "      <th>regimen</th>\n",
       "      <th>dias_anticipacion</th>\n",
       "      <th>primera_vez</th>\n",
       "      <th>inasistencias_previas</th>\n",
       "      <th>confirmo_whatsapp</th>\n",
       "      <th>distancia_km</th>\n",
       "      <th>lluvia</th>\n",
       "      <th>no_asistio</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>17</td>\n",
       "      <td>Medicina general</td>\n",
       "      <td>63</td>\n",
       "      <td>F</td>\n",
       "      <td>Contributivo</td>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>6.4</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>8</td>\n",
       "      <td>Medicina general</td>\n",
       "      <td>44</td>\n",
       "      <td>F</td>\n",
       "      <td>Contributivo</td>\n",
       "      <td>6</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>6.8</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>13</td>\n",
       "      <td>Medicina general</td>\n",
       "      <td>75</td>\n",
       "      <td>F</td>\n",
       "      <td>Subsidiado</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>4.1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>17</td>\n",
       "      <td>Ginecología</td>\n",
       "      <td>53</td>\n",
       "      <td>F</td>\n",
       "      <td>Subsidiado</td>\n",
       "      <td>5</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>16.3</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2025-03-01</td>\n",
       "      <td>5</td>\n",
       "      <td>9</td>\n",
       "      <td>Nutrición</td>\n",
       "      <td>65</td>\n",
       "      <td>F</td>\n",
       "      <td>Particular</td>\n",
       "      <td>11</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>3.7</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       fecha  dia_semana  hora      especialidad  edad sexo       regimen  \\\n",
       "0 2025-03-01           5    17  Medicina general    63    F  Contributivo   \n",
       "1 2025-03-01           5     8  Medicina general    44    F  Contributivo   \n",
       "2 2025-03-01           5    13  Medicina general    75    F    Subsidiado   \n",
       "3 2025-03-01           5    17       Ginecología    53    F    Subsidiado   \n",
       "4 2025-03-01           5     9         Nutrición    65    F    Particular   \n",
       "\n",
       "   dias_anticipacion  primera_vez  inasistencias_previas  confirmo_whatsapp  \\\n",
       "0                  4            0                      1                  0   \n",
       "1                  6            0                      0                  0   \n",
       "2                  3            0                      1                  1   \n",
       "3                  5            0                      0                  0   \n",
       "4                 11            0                      0                  0   \n",
       "\n",
       "   distancia_km  lluvia  no_asistio  \n",
       "0           6.4       0           0  \n",
       "1           6.8       0           0  \n",
       "2           4.1       0           0  \n",
       "3          16.3       0           1  \n",
       "4           3.7       0           0  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.ensemble import HistGradientBoostingClassifier\n",
    "from sklearn.metrics import roc_auc_score, brier_score_loss, average_precision_score\n",
    "\n",
    "df = pd.read_csv('citas_historico.csv', parse_dates=['fecha'])\n",
    "print(f'{len(df):,} citas entre {df.fecha.min():%d/%m/%Y} y {df.fecha.max():%d/%m/%Y}')\n",
    "print(f'Tasa de inasistencia: {df.no_asistio.mean():.1%}')\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8fc8e0e",
   "metadata": {},
   "source": [
    "## Variables\n",
    "\n",
    "Convertimos cada cita en variables que la recepción conoce el día anterior. Agrupamos la edad, la hora y el día de la semana en franjas porque su efecto no es lineal: los muy jóvenes y la primera hora de la mañana faltan más."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "33fe7327",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T01:50:25.257769Z",
     "iopub.status.busy": "2026-10-30T01:50:25.257590Z",
     "iopub.status.idle": "2026-10-30T01:50:25.286739Z",
     "shell.execute_reply": "2026-10-30T01:50:25.285757Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Entrenamiento: 15,678 citas · Prueba: 4,825 citas\n"
     ]
    }
   ],
   "source": [
    "def variables(d: pd.DataFrame) -> pd.DataFrame:\n",
    "    X = pd.DataFrame(index=d.index)\n",
    "    X['dias_anticipacion'] = d.dias_anticipacion\n",
    "    X['inasistencias_previas'] = d.inasistencias_previas.clip(upper=4)\n",
    "    X['falto_antes'] = (d.inasistencias_previas >= 1).astype(int)\n",
    "    X['confirmo_whatsapp'] = d.confirmo_whatsapp\n",
    "    X['primera_vez'] = d.primera_vez\n",
    "    X['distancia_km'] = d.distancia_km\n",
    "    X['lluvia'] = d.lluvia\n",
    "    X['hora_7am'] = (d.hora <= 7).astype(int)\n",
    "    X['hora_tarde'] = (d.hora >= 16).astype(int)\n",
    "    X['lunes'] = (d.dia_semana == 0).astype(int)\n",
    "    X['sabado'] = (d.dia_semana == 5).astype(int)\n",
    "    X['edad_menor_25'] = (d.edad < 25).astype(int)\n",
    "    X['edad_65_mas'] = (d.edad >= 65).astype(int)\n",
    "    X['hombre'] = (d.sexo == 'M').astype(int)\n",
    "    for e in ['Odontología', 'Psicología', 'Pediatría', 'Ginecología', 'Nutrición', 'Fisioterapia']:\n",
    "        X['esp_' + e] = (d.especialidad == e).astype(int)\n",
    "    X['reg_Subsidiado'] = (d.regimen == 'Subsidiado').astype(int)\n",
    "    X['reg_Particular'] = (d.regimen == 'Particular').astype(int)\n",
    "    return X\n",
    "\n",
    "corte = pd.Timestamp('2026-06-01')\n",
    "tr, te = df[df.fecha < corte], df[df.fecha >= corte]\n",
    "Xtr, Xte, ytr, yte = variables(tr), variables(te), tr.no_asistio, te.no_asistio\n",
    "print(f'Entrenamiento: {len(tr):,} citas · Prueba: {len(te):,} citas')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "218e1067",
   "metadata": {},
   "source": [
    "## Dos modelos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "78da7a14",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T01:50:25.288472Z",
     "iopub.status.busy": "2026-10-30T01:50:25.288314Z",
     "iopub.status.idle": "2026-10-30T01:50:25.677749Z",
     "shell.execute_reply": "2026-10-30T01:50:25.676856Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>auc</th>\n",
       "      <th>ap</th>\n",
       "      <th>brier</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Regresión logística</th>\n",
       "      <td>0.715</td>\n",
       "      <td>0.416</td>\n",
       "      <td>0.149</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Gradient boosting</th>\n",
       "      <td>0.704</td>\n",
       "      <td>0.396</td>\n",
       "      <td>0.151</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       auc     ap  brier\n",
       "Regresión logística  0.715  0.416  0.149\n",
       "Gradient boosting    0.704  0.396  0.151"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lr = LogisticRegression(C=1.0, max_iter=2000).fit(Xtr, ytr)\n",
    "gb_cols = ['dias_anticipacion', 'inasistencias_previas', 'confirmo_whatsapp', 'primera_vez', 'distancia_km', 'lluvia']\n",
    "Gtr = tr[gb_cols + ['hora', 'dia_semana', 'edad']].assign(sexo=(tr.sexo == 'M').astype(int), esp=tr.especialidad.astype('category').cat.codes, reg=tr.regimen.astype('category').cat.codes)\n",
    "Gte = te[gb_cols + ['hora', 'dia_semana', 'edad']].assign(sexo=(te.sexo == 'M').astype(int), esp=te.especialidad.astype('category').cat.codes, reg=te.regimen.astype('category').cat.codes)\n",
    "gb = HistGradientBoostingClassifier(max_iter=300, learning_rate=.05, max_leaf_nodes=15, categorical_features=[Gtr.columns.get_loc('esp'), Gtr.columns.get_loc('reg')], random_state=0).fit(Gtr, ytr)\n",
    "\n",
    "p_lr, p_gb = lr.predict_proba(Xte)[:, 1], gb.predict_proba(Gte)[:, 1]\n",
    "metricas = {}\n",
    "for nombre, p in [('Regresión logística', p_lr), ('Gradient boosting', p_gb)]:\n",
    "    metricas[nombre] = dict(auc=roc_auc_score(yte, p), ap=average_precision_score(yte, p), brier=brier_score_loss(yte, p))\n",
    "pd.DataFrame(metricas).T.round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f422da16",
   "metadata": {},
   "source": [
    "Los dos modelos discriminan casi igual. Nos quedamos con la regresión logística: la diferencia es mínima y a cambio podemos decirle a la recepcionista por qué una cita salió en riesgo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a61e5f68",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T01:50:25.679629Z",
     "iopub.status.busy": "2026-10-30T01:50:25.679415Z",
     "iopub.status.idle": "2026-10-30T01:50:25.696350Z",
     "shell.execute_reply": "2026-10-30T01:50:25.695535Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>predicho</th>\n",
       "      <th>observado</th>\n",
       "      <th>n</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>decil</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.060</td>\n",
       "      <td>0.066</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.082</td>\n",
       "      <td>0.077</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.104</td>\n",
       "      <td>0.133</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.128</td>\n",
       "      <td>0.114</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.155</td>\n",
       "      <td>0.153</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.185</td>\n",
       "      <td>0.203</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.220</td>\n",
       "      <td>0.228</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>0.267</td>\n",
       "      <td>0.280</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.338</td>\n",
       "      <td>0.349</td>\n",
       "      <td>482</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>0.486</td>\n",
       "      <td>0.511</td>\n",
       "      <td>483</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       predicho  observado    n\n",
       "decil                          \n",
       "0         0.060      0.066  483\n",
       "1         0.082      0.077  482\n",
       "2         0.104      0.133  483\n",
       "3         0.128      0.114  482\n",
       "4         0.155      0.153  483\n",
       "5         0.185      0.203  482\n",
       "6         0.220      0.228  482\n",
       "7         0.267      0.280  483\n",
       "8         0.338      0.349  482\n",
       "9         0.486      0.511  483"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "calib = (pd.DataFrame({'p': p_lr, 'y': yte.values}).assign(decil=lambda d: pd.qcut(d.p, 10, labels=False))\n",
    "         .groupby('decil').agg(predicho=('p', 'mean'), observado=('y', 'mean'), n=('y', 'size')))\n",
    "calib.round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43e6f6e4",
   "metadata": {},
   "source": [
    "## ¿Cuántas llamadas y cuántas citas salvadas?\n",
    "\n",
    "Para cada umbral de riesgo calculamos qué parte de las citas se marcaría para llamar, qué parte de ellas efectivamente iba a faltar (precisión) y qué parte de todas las inasistencias se alcanza a cubrir (sensibilidad)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f98d2116",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T01:50:25.698487Z",
     "iopub.status.busy": "2026-10-30T01:50:25.698298Z",
     "iopub.status.idle": "2026-10-30T01:50:25.721588Z",
     "shell.execute_reply": "2026-10-30T01:50:25.720466Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>umbral</th>\n",
       "      <th>marcadas</th>\n",
       "      <th>precision</th>\n",
       "      <th>sensibilidad</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.10</td>\n",
       "      <td>0.766</td>\n",
       "      <td>0.252</td>\n",
       "      <td>0.913</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.15</td>\n",
       "      <td>0.566</td>\n",
       "      <td>0.295</td>\n",
       "      <td>0.790</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>0.20</td>\n",
       "      <td>0.403</td>\n",
       "      <td>0.340</td>\n",
       "      <td>0.648</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>0.25</td>\n",
       "      <td>0.279</td>\n",
       "      <td>0.383</td>\n",
       "      <td>0.505</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>0.30</td>\n",
       "      <td>0.201</td>\n",
       "      <td>0.428</td>\n",
       "      <td>0.407</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25</th>\n",
       "      <td>0.35</td>\n",
       "      <td>0.131</td>\n",
       "      <td>0.493</td>\n",
       "      <td>0.306</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>0.40</td>\n",
       "      <td>0.087</td>\n",
       "      <td>0.530</td>\n",
       "      <td>0.219</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>35</th>\n",
       "      <td>0.45</td>\n",
       "      <td>0.058</td>\n",
       "      <td>0.553</td>\n",
       "      <td>0.153</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>40</th>\n",
       "      <td>0.50</td>\n",
       "      <td>0.034</td>\n",
       "      <td>0.640</td>\n",
       "      <td>0.103</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>45</th>\n",
       "      <td>0.55</td>\n",
       "      <td>0.020</td>\n",
       "      <td>0.602</td>\n",
       "      <td>0.058</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50</th>\n",
       "      <td>0.60</td>\n",
       "      <td>0.012</td>\n",
       "      <td>0.667</td>\n",
       "      <td>0.037</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>55</th>\n",
       "      <td>0.65</td>\n",
       "      <td>0.005</td>\n",
       "      <td>0.731</td>\n",
       "      <td>0.019</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    umbral  marcadas  precision  sensibilidad\n",
       "0     0.10     0.766      0.252         0.913\n",
       "5     0.15     0.566      0.295         0.790\n",
       "10    0.20     0.403      0.340         0.648\n",
       "15    0.25     0.279      0.383         0.505\n",
       "20    0.30     0.201      0.428         0.407\n",
       "25    0.35     0.131      0.493         0.306\n",
       "30    0.40     0.087      0.530         0.219\n",
       "35    0.45     0.058      0.553         0.153\n",
       "40    0.50     0.034      0.640         0.103\n",
       "45    0.55     0.020      0.602         0.058\n",
       "50    0.60     0.012      0.667         0.037\n",
       "55    0.65     0.005      0.731         0.019"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "umbrales = []\n",
    "for u in np.round(np.arange(.10, .66, .01), 2):\n",
    "    m = p_lr >= u\n",
    "    umbrales.append(dict(umbral=float(u), marcadas=float(m.mean()), precision=float(yte[m].mean()) if m.any() else 0.0,\n",
    "                         sensibilidad=float((m & (yte == 1)).sum() / (yte == 1).sum())))\n",
    "pd.DataFrame(umbrales).iloc[::5].round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aae93dfd",
   "metadata": {},
   "source": [
    "## Equidad por régimen\n",
    "\n",
    "El régimen subsidiado tiene más inasistencias en los datos, y el modelo lo usa como variable. Revisamos que eso no se traduzca en marcar de más a esos pacientes respecto a su riesgo real. Llamar no es una sanción, pero si la clínica usara el modelo para hacer sobrecupos sí habría que vigilar este punto."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "aa5c47d3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T01:50:25.723512Z",
     "iopub.status.busy": "2026-10-30T01:50:25.723307Z",
     "iopub.status.idle": "2026-10-30T01:50:25.735700Z",
     "shell.execute_reply": "2026-10-30T01:50:25.733960Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>regimen</th>\n",
       "      <th>citas</th>\n",
       "      <th>tasa_real</th>\n",
       "      <th>riesgo_promedio</th>\n",
       "      <th>marcadas</th>\n",
       "      <th>precision</th>\n",
       "      <th>sensibilidad</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Contributivo</td>\n",
       "      <td>2651</td>\n",
       "      <td>0.197</td>\n",
       "      <td>0.191</td>\n",
       "      <td>0.107</td>\n",
       "      <td>0.458</td>\n",
       "      <td>0.249</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Subsidiado</td>\n",
       "      <td>1599</td>\n",
       "      <td>0.247</td>\n",
       "      <td>0.238</td>\n",
       "      <td>0.197</td>\n",
       "      <td>0.530</td>\n",
       "      <td>0.423</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Particular</td>\n",
       "      <td>575</td>\n",
       "      <td>0.177</td>\n",
       "      <td>0.157</td>\n",
       "      <td>0.059</td>\n",
       "      <td>0.441</td>\n",
       "      <td>0.147</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        regimen  citas  tasa_real  riesgo_promedio  marcadas  precision  \\\n",
       "0  Contributivo   2651      0.197            0.191     0.107      0.458   \n",
       "1    Subsidiado   1599      0.247            0.238     0.197      0.530   \n",
       "2    Particular    575      0.177            0.157     0.059      0.441   \n",
       "\n",
       "   sensibilidad  \n",
       "0         0.249  \n",
       "1         0.423  \n",
       "2         0.147  "
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "U = .35\n",
    "equidad = []\n",
    "for r in ['Contributivo', 'Subsidiado', 'Particular']:\n",
    "    s = (te.regimen == r).values\n",
    "    m = p_lr[s] >= U; y = yte.values[s]\n",
    "    equidad.append(dict(regimen=r, citas=int(s.sum()), tasa_real=float(y.mean()), riesgo_promedio=float(p_lr[s].mean()),\n",
    "                        marcadas=float(m.mean()), precision=float(y[m].mean()), sensibilidad=float((m & (y == 1)).sum() / (y == 1).sum())))\n",
    "pd.DataFrame(equidad).round(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aadf6115",
   "metadata": {},
   "source": [
    "## Exportar el modelo\n",
    "\n",
    "Guardamos los coeficientes para que la herramienta de recepción calcule el riesgo en el navegador, sin enviar datos de pacientes a ningún servidor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "18250258",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-30T01:50:25.737656Z",
     "iopub.status.busy": "2026-10-30T01:50:25.737482Z",
     "iopub.status.idle": "2026-10-30T01:50:25.750241Z",
     "shell.execute_reply": "2026-10-30T01:50:25.749231Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "confirmo_whatsapp        0.38\n",
       "edad_65_mas              0.71\n",
       "esp_Pediatría            0.73\n",
       "reg_Particular           0.73\n",
       "esp_Ginecología          1.00\n",
       "dias_anticipacion        1.03\n",
       "hombre                   1.03\n",
       "distancia_km             1.04\n",
       "esp_Fisioterapia         1.08\n",
       "reg_Subsidiado           1.16\n",
       "esp_Nutrición            1.18\n",
       "lluvia                   1.22\n",
       "lunes                    1.23\n",
       "esp_Odontología          1.25\n",
       "primera_vez              1.30\n",
       "hora_7am                 1.36\n",
       "hora_tarde               1.37\n",
       "sabado                   1.45\n",
       "inasistencias_previas    1.45\n",
       "esp_Psicología           1.47\n",
       "falto_antes              1.53\n",
       "edad_menor_25            1.58\n",
       "Name: razón de momios, dtype: float64"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coef = dict(zip(Xtr.columns, lr.coef_[0].round(5)))\n",
    "modelo = dict(intercepto=float(lr.intercept_[0]), coeficientes={k: float(v) for k, v in coef.items()},\n",
    "              media_entrenamiento={k: float(v) for k, v in Xtr.mean().round(4).items()},\n",
    "              metricas={k: {m: round(float(v), 4) for m, v in d.items()} for k, d in metricas.items()},\n",
    "              calibracion=calib.reset_index().round(4).to_dict('records'), umbrales=umbrales, equidad=equidad, umbral_equidad=U,\n",
    "              n_entrenamiento=len(tr), n_prueba=len(te), tasa_base=float(df.no_asistio.mean()),\n",
    "              periodo=[f'{df.fecha.min():%Y-%m-%d}', f'{df.fecha.max():%Y-%m-%d}'], corte=f'{corte:%Y-%m-%d}')\n",
    "json.dump(modelo, open('modelo_inasistencia.json', 'w'), ensure_ascii=False, indent=1)\n",
    "pd.Series(np.exp(lr.coef_[0]), index=Xtr.columns).sort_values().round(2).rename('razón de momios')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
