{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e403b0dd",
   "metadata": {},
   "source": [
    "# Proyecto final: el predictor de hits de PyRitmo (solución de referencia)\n",
    "\n",
    "Solución de referencia del proyecto final del curso. El objetivo: a partir del CSV **sucio** de canciones, construir\n",
    "un modelo que, **antes del lanzamiento**, estime la probabilidad de que una canción entre al Top 50 semanal en su\n",
    "primer mes, y decidir a partir de qué probabilidad el equipo editorial la promueve.\n",
    "\n",
    "Consulta este notebook después de intentar el proyecto por tu cuenta. Cada sección corresponde a un requisito del\n",
    "enunciado, en el mismo orden.\n",
    "\n",
    "**Plan**\n",
    "\n",
    "0. Datos sucios y cifras de control.\n",
    "1. Limpieza con la función `limpiar`.\n",
    "2. `X` e `y` sin fuga y partición (el test no se toca hasta el paso 7).\n",
    "3. Pipeline con imputación.\n",
    "4. Línea base y comparación de un modelo lineal, uno de margen (SVM), Random Forest y XGBoost con validación cruzada.\n",
    "5. XGBoost: early stopping con una validación separada y búsqueda aleatoria de hiperparámetros.\n",
    "6. Umbral de decisión (o `scale_pos_weight`) según el costo de dejar pasar un hit.\n",
    "7. Evaluación final en test, una sola vez.\n",
    "8. Una canción nueva.\n",
    "9. Extras: regresión de popularidad, estilo como característica e importancia por permutación.\n",
    "\n",
    "Requiere `pip install xgboost` (en Colab ya viene instalado)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b660e3d",
   "metadata": {},
   "source": [
    "## 0. Los datos\n",
    "\n",
    "La celda copia `generar_canciones`, `ensuciar` y las listas del curso (iguales en todos los notebooks)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0a1200e7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:42.057416Z",
     "iopub.status.busy": "2026-10-18T17:51:42.057416Z",
     "iopub.status.idle": "2026-10-18T17:51:44.981588Z",
     "shell.execute_reply": "2026-10-18T17:51:44.980582Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python 3.12.10 | scikit-learn 1.9.1 | pandas 3.0.6 | NumPy 2.5.4 | xgboost 3.4.1\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "import warnings\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import sklearn\n",
    "import xgboost\n",
    "from scipy.stats import loguniform, randint, uniform\n",
    "from sklearn.base import BaseEstimator, TransformerMixin\n",
    "from sklearn.cluster import KMeans\n",
    "from sklearn.compose import ColumnTransformer\n",
    "from sklearn.dummy import DummyClassifier, DummyRegressor\n",
    "from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\n",
    "from sklearn.impute import SimpleImputer\n",
    "from sklearn.inspection import permutation_importance\n",
    "from sklearn.linear_model import LinearRegression, LogisticRegression\n",
    "from sklearn.metrics import (accuracy_score, confusion_matrix, mean_absolute_error, precision_score, r2_score,\n",
    "                             recall_score, roc_auc_score)\n",
    "from sklearn.model_selection import (RandomizedSearchCV, StratifiedKFold, cross_val_predict, cross_val_score,\n",
    "                                     train_test_split)\n",
    "from sklearn.pipeline import Pipeline, make_pipeline\n",
    "from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "pd.set_option(\"display.width\", 120)\n",
    "\n",
    "print(\"Python\", sys.version.split()[0], \"| scikit-learn\", sklearn.__version__, \"| pandas\", pd.__version__,\n",
    "      \"| NumPy\", np.__version__, \"| xgboost\", xgboost.__version__)\n",
    "\n",
    "# Datos del curso (iguales en todos los notebooks): canciones de PyRitmo, una app de streaming ficticia\n",
    "GENEROS = [\"pop\", \"reguetón\", \"rock\", \"electrónica\", \"regional\"]\n",
    "ESTILOS = [\"acustica\", \"bailable\", \"energica\", \"ambiental\"]\n",
    "DIAS = [\"lun\", \"mar\", \"mie\", \"jue\", \"vie\", \"sab\", \"dom\"]\n",
    "\n",
    "\n",
    "def _beta(rng, media, k, n):\n",
    "    return rng.beta(media * k, (1 - media) * k, n)\n",
    "\n",
    "\n",
    "def generar_canciones(n=1500, semilla=42):\n",
    "    rng = np.random.default_rng(semilla)\n",
    "    estilo = rng.choice(ESTILOS, n, p=[0.25, 0.35, 0.28, 0.12])\n",
    "    gen_p = {\n",
    "        \"acustica\":  [0.40, 0.05, 0.20, 0.00, 0.35],\n",
    "        \"bailable\":  [0.35, 0.45, 0.00, 0.10, 0.10],\n",
    "        \"energica\":  [0.15, 0.05, 0.50, 0.25, 0.05],\n",
    "        \"ambiental\": [0.10, 0.00, 0.05, 0.85, 0.00],\n",
    "    }\n",
    "    genero = np.array([rng.choice(GENEROS, p=gen_p[e]) for e in estilo])\n",
    "    perfil = {  # energia, bailabilidad, acustica, tempo, duracion\n",
    "        \"acustica\":  (0.30, 0.40, 0.75, 82, 215),\n",
    "        \"bailable\":  (0.70, 0.80, 0.15, 98, 190),\n",
    "        \"energica\":  (0.88, 0.50, 0.06, 138, 225),\n",
    "        \"ambiental\": (0.40, 0.35, 0.30, 115, 380),\n",
    "    }\n",
    "    P = np.array([perfil[e] for e in estilo])\n",
    "    energia = np.clip(P[:, 0] + rng.normal(0, 0.08, n), 0.02, 0.99).round(2)\n",
    "    bailabilidad = np.clip(P[:, 1] + rng.normal(0, 0.08, n), 0.05, 0.98).round(2)\n",
    "    acustica = np.clip(P[:, 2] + rng.normal(0, 0.08, n), 0.0, 0.99).round(2)\n",
    "    tempo = np.clip(P[:, 3] + rng.normal(0, 10, n), 60, 190).round(0)\n",
    "    duracion = np.clip(P[:, 4] + rng.normal(0, 35, n), 95, 600).round(0)\n",
    "    seguidores = np.round(rng.lognormal(4.5, 1.3, n), 1)            # miles de seguidores del artista\n",
    "    colaboracion = (rng.random(n) < np.where(estilo == \"bailable\", 0.45, 0.15)).astype(int)\n",
    "    explicita = (rng.random(n) < np.where(np.isin(genero, [\"reguetón\", \"rock\"]), 0.5, 0.1)).astype(int)\n",
    "    en_playlist = (rng.random(n) < 0.3).astype(int)                  # entró a una playlist editorial\n",
    "    largo_titulo = rng.integers(3, 40, n)\n",
    "    dia_lanzamiento = rng.choice(DIAS, n)\n",
    "\n",
    "    log_seg = np.log10(seguidores)\n",
    "    popularidad = (\n",
    "        8\n",
    "        + 11 * log_seg\n",
    "        + 12 * bailabilidad\n",
    "        + 9 * energia\n",
    "        + 10 * en_playlist\n",
    "        + 6 * colaboracion\n",
    "        - 0.03 * np.maximum(duracion - 240, 0)\n",
    "        + np.select([genero == \"reguetón\", genero == \"pop\", genero == \"regional\"], [6, 4, 3], 0)\n",
    "        + rng.normal(0, 6, n)\n",
    "    )\n",
    "    popularidad = np.clip(popularidad, 0, 100).round(0)\n",
    "\n",
    "    # entrar al Top 50: reglas con umbrales e interacciones (lo que los árboles capturan bien)\n",
    "    logit = (\n",
    "        -3.2\n",
    "        + 1.4 * (log_seg - 1.95)\n",
    "        + 2.0 * en_playlist\n",
    "        + 2.2 * colaboracion * (bailabilidad > 0.65)\n",
    "        + 1.6 * (energia > 0.6) * (duracion < 210)\n",
    "        - 2.0 * (duracion > 300)\n",
    "        + 1.2 * (genero == \"reguetón\")\n",
    "        + rng.normal(0, 0.6, n)\n",
    "    )\n",
    "    top50 = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)\n",
    "    reproducciones = np.round(10 ** (1.5 + 0.035 * popularidad + 0.5 * top50 + rng.normal(0, 0.15, n)), 1)\n",
    "\n",
    "    df = pd.DataFrame({\n",
    "        \"energia\": energia,\n",
    "        \"bailabilidad\": bailabilidad,\n",
    "        \"acustica\": acustica,\n",
    "        \"tempo_bpm\": tempo,\n",
    "        \"duracion_seg\": duracion,\n",
    "        \"seguidores_miles\": seguidores,\n",
    "        \"colaboracion\": colaboracion,\n",
    "        \"explicita\": explicita,\n",
    "        \"en_playlist\": en_playlist,\n",
    "        \"genero\": genero,\n",
    "        \"largo_titulo\": largo_titulo,\n",
    "        \"dia_lanzamiento\": dia_lanzamiento,\n",
    "        \"reproducciones_mes1\": reproducciones,   # miles; FUGA\n",
    "        \"popularidad\": popularidad,\n",
    "        \"top50\": top50,\n",
    "    })\n",
    "    return df, estilo\n",
    "\n",
    "\n",
    "def ensuciar(df, semilla=7):\n",
    "    \"\"\"Versión sucia: tempo y seguidores faltantes, géneros mal escritos, duraciones en ms y duplicados.\"\"\"\n",
    "    rng = np.random.default_rng(semilla)\n",
    "    d = df.copy()\n",
    "    n = len(d)\n",
    "    d.loc[rng.random(n) < 0.06, \"tempo_bpm\"] = np.nan\n",
    "    d.loc[rng.random(n) < 0.04, \"seguidores_miles\"] = np.nan\n",
    "    variantes = {\"pop\": [\"Pop\", \"POP\", \"pop \"], \"reguetón\": [\"reggaeton\", \"Reguetón\", \"regueton\"],\n",
    "                 \"rock\": [\"Rock\", \"rock \"], \"electrónica\": [\"electronica\", \"Electrónica\"],\n",
    "                 \"regional\": [\"Regional\", \"regional mexicano\"]}\n",
    "    for i in np.where(rng.random(n) < 0.08)[0]:\n",
    "        d.at[i, \"genero\"] = rng.choice(variantes[d.at[i, \"genero\"]])\n",
    "    ms = np.where(rng.random(n) < 0.01)[0]\n",
    "    d.loc[ms, \"duracion_seg\"] = d.loc[ms, \"duracion_seg\"] * 1000   # vino en milisegundos\n",
    "    dup = d.sample(25, random_state=semilla)\n",
    "    return pd.concat([d, dup], ignore_index=True)\n",
    "\n",
    "\n",
    "NUMERICAS = [\"energia\", \"bailabilidad\", \"acustica\", \"tempo_bpm\", \"duracion_seg\", \"seguidores_miles\",\n",
    "             \"colaboracion\", \"explicita\", \"en_playlist\"]\n",
    "CATEGORICAS = [\"genero\"]\n",
    "AUDIO = [\"energia\", \"bailabilidad\", \"acustica\", \"tempo_bpm\", \"duracion_seg\"]\n",
    "RUIDO = [\"largo_titulo\", \"dia_lanzamiento\"]\n",
    "FUGA = [\"reproducciones_mes1\"]\n",
    "\n",
    "\n",
    "def probar(nombre, pruebas, estricto=False):\n",
    "    \"\"\"Corre las pruebas de un ejercicio. Si aún no está resuelto, imprime 'pendiente' sin detener el notebook.\"\"\"\n",
    "    try:\n",
    "        pruebas()\n",
    "    except (AssertionError, NotImplementedError, TypeError, AttributeError, KeyError, ValueError,\n",
    "            IndexError) as e:\n",
    "        if estricto:\n",
    "            raise\n",
    "        print(f\"{nombre}: pendiente ({type(e).__name__})\")\n",
    "    else:\n",
    "        print(f\"{nombre}: correcto\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "75a6706c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:44.985595Z",
     "iopub.status.busy": "2026-10-18T17:51:44.984592Z",
     "iopub.status.idle": "2026-10-18T17:51:45.050289Z",
     "shell.execute_reply": "2026-10-18T17:51:45.049284Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1525, 15)\n",
      "25\n",
      "17\n"
     ]
    }
   ],
   "source": [
    "df, _ = generar_canciones(n=1500, semilla=42)   # el segundo valor (estilos latentes) no se usa\n",
    "sucio = ensuciar(df, semilla=7)\n",
    "print(sucio.shape)                    # (1525, 15)\n",
    "print(sucio.duplicated().sum())       # 25\n",
    "print(sucio[\"genero\"].nunique())      # 17"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4f0738a",
   "metadata": {},
   "source": [
    "Las tres cifras de control coinciden con el enunciado. Antes de limpiar conviene ver los problemas uno por uno:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8e2b7812",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:45.052792Z",
     "iopub.status.busy": "2026-10-18T17:51:45.052792Z",
     "iopub.status.idle": "2026-10-18T17:51:45.061662Z",
     "shell.execute_reply": "2026-10-18T17:51:45.060655Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "géneros: [np.str_('Electrónica'), np.str_('POP'), np.str_('Pop'), np.str_('Regional'), np.str_('Reguetón'), np.str_('Rock'), np.str_('electronica'), 'electrónica', 'pop', np.str_('pop '), np.str_('reggaeton'), 'regional', np.str_('regional mexicano'), np.str_('regueton'), 'reguetón', 'rock', np.str_('rock ')]\n",
      "\n",
      "faltantes: {'tempo_bpm': 86, 'seguidores_miles': 60}\n",
      "duración máxima: 419000.0 | filas con más de 1000 'segundos': 19\n"
     ]
    }
   ],
   "source": [
    "print(\"géneros:\", sorted(sucio[\"genero\"].unique()))\n",
    "print()\n",
    "print(\"faltantes:\", sucio.isna().sum()[lambda s: s > 0].to_dict())\n",
    "print(\"duración máxima:\", sucio[\"duracion_seg\"].max(), \"| filas con más de 1000 'segundos':\",\n",
    "      (sucio[\"duracion_seg\"] > 1000).sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0f423c1",
   "metadata": {},
   "source": [
    "- 17 escrituras de género para 5 géneros reales (`POP`, `Pop`, `pop ` con espacio, `reggaeton`, `regional mexicano`…).\n",
    "- Faltantes en `tempo_bpm` y `seguidores_miles`.\n",
    "- Duraciones de cientos de miles de «segundos»: venían en milisegundos.\n",
    "- 25 filas duplicadas.\n",
    "\n",
    "## 1. Limpieza\n",
    "\n",
    "`limpiar` quita duplicados, unifica los géneros con `str.strip().str.lower()` más un diccionario, y divide entre 1000\n",
    "las duraciones mayores a 1000 (ninguna canción dura más de 1000 segundos). Los faltantes **no** se borran: se\n",
    "imputan dentro del pipeline (paso 3), así la mediana se calcula solo con los datos de entrenamiento de cada pliegue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "19271742",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:45.065670Z",
     "iopub.status.busy": "2026-10-18T17:51:45.065670Z",
     "iopub.status.idle": "2026-10-18T17:51:45.090457Z",
     "shell.execute_reply": "2026-10-18T17:51:45.088451Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "forma: (1500, 15)\n",
      "hits: 412 (27.5%)\n",
      "duraciones corregidas: 19 | duración máxima: 446.0\n",
      "géneros: {'pop': 400, 'electrónica': 312, 'rock': 305, 'reguetón': 271, 'regional': 212}\n",
      "faltantes: {'tempo_bpm': 85, 'seguidores_miles': 59}\n"
     ]
    }
   ],
   "source": [
    "MAPA_GENERO = {\"pop\": \"pop\", \"reggaeton\": \"reguetón\", \"regueton\": \"reguetón\", \"reguetón\": \"reguetón\",\n",
    "               \"rock\": \"rock\", \"electronica\": \"electrónica\", \"electrónica\": \"electrónica\",\n",
    "               \"regional\": \"regional\", \"regional mexicano\": \"regional\"}\n",
    "\n",
    "\n",
    "def limpiar(sucio):\n",
    "    d = sucio.drop_duplicates().copy()\n",
    "    d[\"genero\"] = d[\"genero\"].str.strip().str.lower().map(MAPA_GENERO)\n",
    "    en_ms = d[\"duracion_seg\"] > 1000\n",
    "    d.loc[en_ms, \"duracion_seg\"] = d.loc[en_ms, \"duracion_seg\"] / 1000\n",
    "    return d.reset_index(drop=True)\n",
    "\n",
    "\n",
    "limpio = limpiar(sucio)\n",
    "print(\"forma:\", limpio.shape)\n",
    "print(\"hits:\", limpio[\"top50\"].sum(), f\"({limpio['top50'].mean():.1%})\")\n",
    "print(\"duraciones corregidas:\", (sucio.drop_duplicates()[\"duracion_seg\"] > 1000).sum(),\n",
    "      \"| duración máxima:\", limpio[\"duracion_seg\"].max())\n",
    "print(\"géneros:\", limpio[\"genero\"].value_counts().to_dict())\n",
    "print(\"faltantes:\", limpio.isna().sum()[lambda s: s > 0].to_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "496326a8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:45.093963Z",
     "iopub.status.busy": "2026-10-18T17:51:45.093458Z",
     "iopub.status.idle": "2026-10-18T17:51:45.102882Z",
     "shell.execute_reply": "2026-10-18T17:51:45.101873Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "limpieza correcta\n"
     ]
    }
   ],
   "source": [
    "# comprobaciones del requisito 1\n",
    "assert limpio.shape == (1500, 15)\n",
    "assert limpio[\"top50\"].sum() == 412\n",
    "assert limpio[\"duracion_seg\"].max() == 446\n",
    "assert limpio[\"genero\"].nunique() == 5 and limpio[\"genero\"].isna().sum() == 0\n",
    "assert limpio[\"tempo_bpm\"].isna().sum() == 85 and limpio[\"seguidores_miles\"].isna().sum() == 59\n",
    "print(\"limpieza correcta\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9964faeb",
   "metadata": {},
   "source": [
    "1500 canciones, 412 hits (27.5 %), duración máxima de 446 segundos tras corregir 19 duraciones, y quedan 85 faltantes\n",
    "en `tempo_bpm` y 59 en `seguidores_miles`.\n",
    "\n",
    "## 2. X e y sin fuga, y partición\n",
    "\n",
    "`reproducciones_mes1` y `popularidad` se conocen **después** del lanzamiento (y casi definen el Top 50): usarlas como\n",
    "entrada daría un modelo que parece excelente pero que no se puede usar el día en que el sello entrega la canción.\n",
    "Tampoco entran `largo_titulo` ni `dia_lanzamiento`, que en el curso resultaron ruido."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8da606ac",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:45.106512Z",
     "iopub.status.busy": "2026-10-18T17:51:45.105882Z",
     "iopub.status.idle": "2026-10-18T17:51:45.175481Z",
     "shell.execute_reply": "2026-10-18T17:51:45.173956Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "train"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " (1125, 10) | test (375, 10)\n",
      "hits en train: 0.275 | hits en test: 0.275 -> 103 hits\n"
     ]
    }
   ],
   "source": [
    "X = limpio[NUMERICAS + CATEGORICAS]\n",
    "y = limpio[\"top50\"]\n",
    "X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)\n",
    "print(\"train\", X_tr.shape, \"| test\", X_te.shape)\n",
    "print(\"hits en train:\", round(y_tr.mean(), 3), \"| hits en test:\", round(y_te.mean(), 3), \"->\", y_te.sum(), \"hits\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad2cc0e1",
   "metadata": {},
   "source": [
    "1125 canciones en train y 375 en test, con 27.5 % de hits en ambos gracias a `stratify`. Desde aquí el test queda\n",
    "guardado hasta el paso 7.\n",
    "\n",
    "## 3. Pipeline con imputación\n",
    "\n",
    "Numéricas: mediana para los faltantes y luego `StandardScaler`. Género: el valor más frecuente para los faltantes\n",
    "(aquí no hay, pero el pipeline queda listo para datos futuros) y luego `OneHotEncoder(handle_unknown=\"ignore\")`.\n",
    "Todo va dentro del pipeline con el modelo, así la validación cruzada repite la imputación en cada pliegue sin fuga."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f7579882",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:45.178483Z",
     "iopub.status.busy": "2026-10-18T17:51:45.178483Z",
     "iopub.status.idle": "2026-10-18T17:51:45.296500Z",
     "shell.execute_reply": "2026-10-18T17:51:45.295492Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>.sk-global {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: #000;\n",
       "  --sklearn-color-text-muted: #666;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "}\n",
       "\n",
       ".sk-global.light {\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: black;\n",
       "  --sklearn-color-background: white;\n",
       "  --sklearn-color-border-box: black;\n",
       "  --sklearn-color-icon: #696969;\n",
       "}\n",
       "\n",
       ".sk-global.dark {\n",
       "  --sklearn-color-text-on-default-background: white;\n",
       "  --sklearn-color-background: #111;\n",
       "  --sklearn-color-border-box: white;\n",
       "  --sklearn-color-icon: #878787;\n",
       "}\n",
       "\n",
       ".sk-global {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       ".sk-global pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       ".sk-global input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip-path: inset(100%);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       ".sk-global div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       ".sk-global div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       ".sk-global div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       ".sk-global label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: flex;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "  align-items: center;\n",
       "  justify-content: center;\n",
       "  gap: 0.5em;\n",
       "}\n",
       "\n",
       ".sk-global label.sk-toggleable__label .caption {\n",
       "  font-size: 0.6rem;\n",
       "  font-weight: lighter;\n",
       "  color: var(--sklearn-color-text-muted);\n",
       "}\n",
       "\n",
       ".sk-global label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       ".sk-global label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       ".sk-global div.sk-toggleable__content {\n",
       "  display: none;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       ".sk-global input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  overflow: visible;\n",
       "}\n",
       "\n",
       ".sk-global input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       ".sk-global div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       ".sk-global div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-label label.sk-toggleable__label,\n",
       ".sk-global div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       ".sk-global div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       ".sk-global div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       ".sk-global div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       ".sk-global div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       ".sk-global div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       ".sk-global div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       ".sk-global div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 0.5em;\n",
       "  text-align: center;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-3) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  border: var(--sklearn-color-fitted-level-0) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-0);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  border: var(--sklearn-color-fitted-level-0) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-0);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       ".sk-global a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       ".sk-global a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       ".sk-global a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       ".sk-global a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-top-container.sk-global {\n",
       "  /* pydata-sphinx-theme hides overflow, so scrolling is disabled.\n",
       "   We need to set it to !important and add tabindex=\"0\" in the HTML\n",
       "   to allow keyboard-only users to navigate the display. */\n",
       "  overflow-x: scroll !important;\n",
       "  max-width: 100%;\n",
       "}\n",
       "\n",
       ".estimator-table {\n",
       "    font-family: monospace;\n",
       "}\n",
       "\n",
       ".estimator-table summary {\n",
       "    padding: .5rem;\n",
       "    cursor: pointer;\n",
       "}\n",
       "\n",
       ".estimator-table summary::marker {\n",
       "    font-size: 0.7rem;\n",
       "}\n",
       "\n",
       ".estimator-table details[open] {\n",
       "    padding-left: 0.1rem;\n",
       "    padding-right: 0.1rem;\n",
       "    padding-bottom: 0.3rem;\n",
       "}\n",
       "\n",
       ".estimator-table .parameters-table {\n",
       "    margin-left: auto !important;\n",
       "    margin-right: auto !important;\n",
       "    margin-top: 0;\n",
       "}\n",
       "\n",
       ".estimator-table .parameters-table tr:nth-child(odd) {\n",
       "    background-color: #fff;\n",
       "}\n",
       "\n",
       ".estimator-table .parameters-table tr:nth-child(even) {\n",
       "    background-color: #f6f6f6;\n",
       "}\n",
       "\n",
       ".estimator-table .parameters-table tr:hover td {\n",
       "    background-color: #e0e0e0;\n",
       "}\n",
       "\n",
       ".estimator-table table :is(td, th) {\n",
       "    border: 1px solid rgba(106, 105, 104, 0.232);\n",
       "}\n",
       "\n",
       "/*\n",
       "    `table td`is set in notebook with right text-align.\n",
       "    We need to overwrite it.\n",
       "*/\n",
       ".estimator-table table td.param {\n",
       "    text-align: left;\n",
       "    position: relative;\n",
       "    padding: 0;\n",
       "}\n",
       "\n",
       ".user-set td {\n",
       "    color:rgb(255, 94, 0);\n",
       "    text-align: left !important;\n",
       "}\n",
       "\n",
       ".user-set td.value {\n",
       "    color:rgb(255, 94, 0);\n",
       "    background-color: transparent;\n",
       "}\n",
       "\n",
       ".default td, .estimator-table th {\n",
       "    color: black;\n",
       "    text-align: left !important;\n",
       "}\n",
       "\n",
       ".user-set td i,\n",
       ".default td i {\n",
       "    color: black;\n",
       "}\n",
       "\n",
       "td.fitted-att-type {\n",
       "    white-space: preserve nowrap;\n",
       "}\n",
       "\n",
       "/*\n",
       "    Styles for parameter documentation links\n",
       "    We need styling for visited so jupyter doesn't overwrite it\n",
       "*/\n",
       "a.param-doc-link,\n",
       "a.param-doc-link:link,\n",
       "a.param-doc-link:visited {\n",
       "    text-decoration: underline dashed;\n",
       "    text-underline-offset: .3em;\n",
       "    color: inherit;\n",
       "    display: block;\n",
       "    padding: .5em;\n",
       "}\n",
       "\n",
       "@supports(anchor-name: --doc-link) {\n",
       "    a.param-doc-link,\n",
       "    a.param-doc-link:link,\n",
       "    a.param-doc-link:visited {\n",
       "    anchor-name: --doc-link;\n",
       "    }\n",
       "}\n",
       "\n",
       "/* \"hack\" to make the entire area of the cell containing the link clickable */\n",
       "a.param-doc-link::before {\n",
       "    position: absolute;\n",
       "    content: \"\";\n",
       "    inset: 0;\n",
       "}\n",
       "\n",
       ".param-doc-description {\n",
       "    display: none;\n",
       "    position: absolute;\n",
       "    z-index: 9999;\n",
       "    left: 0;\n",
       "    padding: .5ex;\n",
       "    margin-left: 1.5em;\n",
       "    color: var(--sklearn-color-text);\n",
       "    box-shadow: .3em .3em .4em #999;\n",
       "    width: max-content;\n",
       "    text-align: left;\n",
       "    max-height: 10em;\n",
       "    overflow-y: auto;\n",
       "\n",
       "    /* unfitted */\n",
       "    background: var(--sklearn-color-unfitted-level-0);\n",
       "    border: thin solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       "@supports(position-area: center right) {\n",
       "    .param-doc-description {\n",
       "    position-area: center right;\n",
       "    position: fixed;\n",
       "    margin-left: 0;\n",
       "    }\n",
       "}\n",
       "\n",
       "/* Fitted state for parameter tooltips */\n",
       ".fitted .param-doc-description {\n",
       "    /* fitted */\n",
       "    background: var(--sklearn-color-fitted-level-0);\n",
       "    border: thin solid var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".param-doc-link:hover .param-doc-description {\n",
       "    display: block;\n",
       "}\n",
       "\n",
       ".copy-paste-icon {\n",
       "    background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0NDggNTEyIj48IS0tIUZvbnQgQXdlc29tZSBGcmVlIDYuNy4yIGJ5IEBmb250YXdlc29tZSAtIGh0dHBzOi8vZm9udGF3ZXNvbWUuY29tIExpY2Vuc2UgLSBodHRwczovL2ZvbnRhd2Vzb21lLmNvbS9saWNlbnNlL2ZyZWUgQ29weXJpZ2h0IDIwMjUgRm9udGljb25zLCBJbmMuLS0+PHBhdGggZD0iTTIwOCAwTDMzMi4xIDBjMTIuNyAwIDI0LjkgNS4xIDMzLjkgMTQuMWw2Ny45IDY3LjljOSA5IDE0LjEgMjEuMiAxNC4xIDMzLjlMNDQ4IDMzNmMwIDI2LjUtMjEuNSA0OC00OCA0OGwtMTkyIDBjLTI2LjUgMC00OC0yMS41LTQ4LTQ4bDAtMjg4YzAtMjYuNSAyMS41LTQ4IDQ4LTQ4ek00OCAxMjhsODAgMCAwIDY0LTY0IDAgMCAyNTYgMTkyIDAgMC0zMiA2NCAwIDAgNDhjMCAyNi41LTIxLjUgNDgtNDggNDhMNDggNTEyYy0yNi41IDAtNDgtMjEuNS00OC00OEwwIDE3NmMwLTI2LjUgMjEuNS00OCA0OC00OHoiLz48L3N2Zz4=);\n",
       "    background-repeat: no-repeat;\n",
       "    background-size: 14px 14px;\n",
       "    background-position: 0;\n",
       "    display: inline-block;\n",
       "    width: 14px;\n",
       "    height: 14px;\n",
       "    cursor: pointer;\n",
       "    border: none;\n",
       "    padding: 0;\n",
       "    background-color: transparent;\n",
       "}\n",
       "\n",
       ".copy-paste-icon:focus-visible {\n",
       "    outline: 1px solid currentColor;\n",
       "    outline-offset: 1px;\n",
       "}\n",
       "\n",
       ".features {\n",
       "  font-family: monospace;\n",
       "  cursor: pointer;\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: .20em;\n",
       "  margin-bottom: 0.5em;\n",
       "  font-size: inherit; /* Needed for jupyter */\n",
       "}\n",
       "\n",
       ".features.fitted {\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       ".features summary {\n",
       "  cursor: pointer;\n",
       "  display: flex;\n",
       "  margin-bottom: 0;\n",
       "  text-align: center;\n",
       "  align-items: center;\n",
       "  justify-content: center;\n",
       "  gap: 0.5em;\n",
       "  padding: .25em;\n",
       "}\n",
       "\n",
       ".features details[open] > summary {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "  border-radius: .20em 0 0 0;\n",
       "}\n",
       "\n",
       ".features.fitted details[open] > summary {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "  border-radius: .20em 0 0 0;\n",
       "}\n",
       "\n",
       ".features details > summary .arrow::before {\n",
       "  content: \"▸\";\n",
       "  color: grey;\n",
       "}\n",
       "\n",
       ".features details[open] > summary .arrow::before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       ".features details:hover > summary {\n",
       "  margin: 0;\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       ".features.fitted details:hover > summary {\n",
       "  margin: 0;\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       ".features .features-container {\n",
       "  max-height: 10em;\n",
       "  overflow: auto;\n",
       "  scrollbar-width: thin;\n",
       "  padding: .25em 0.1rem;\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "  border-radius: 0 0 .5em .5em;\n",
       "}\n",
       "\n",
       ".features.fitted .features-container {\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       ".features .image-container {\n",
       "  block-size: 1em;\n",
       "  inline-size: 1em;\n",
       "  padding: 0;\n",
       "  margin: 0%;\n",
       "  display: flex;\n",
       "  justify-content: center;\n",
       "  align-items: center;\n",
       "}\n",
       "\n",
       ".features .copy-paste-icon {\n",
       "  background-size: 1em 1em;\n",
       "  width: 1em;\n",
       "  height: 1em;\n",
       "  filter: grayscale(100%) opacity(60%);\n",
       "}\n",
       "\n",
       ".features .features-container table {\n",
       "  width: 100%;\n",
       "  margin: 0.01em;\n",
       "}\n",
       "\n",
       ".features .features-container table tr:nth-child(odd) {\n",
       "  background-color: #fff;\n",
       "}\n",
       "\n",
       ".features .features-container table tr:nth-child(even) {\n",
       "  background-color: #f6f6f6;\n",
       "}\n",
       "\n",
       ".features .features-container table tr:hover {\n",
       "  background-color: #e0e0e0;\n",
       "}\n",
       "\n",
       ".features .features-container table {\n",
       "  table-layout: inherit;\n",
       "}\n",
       "\n",
       ".features .features-container table td {\n",
       "  text-align: left;\n",
       "  padding: 0 0.5em;\n",
       "  border: 1px solid rgba(106, 105, 104, 0.232);\n",
       "  white-space: nowrap;\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       ".total_features {\n",
       "  display: flex;\n",
       "  justify-content: center;\n",
       "  margin-top: 0.5em;\n",
       "}\n",
       "</style><body><div id=\"sk-container-id-1\" tabindex=\"0\" class=\"sk-top-container sk-global\"><div class=\"sk-text-repr-fallback\"><pre>ColumnTransformer(transformers=[(&#x27;num&#x27;,\n",
       "                                 Pipeline(steps=[(&#x27;simpleimputer&#x27;,\n",
       "                                                  SimpleImputer(strategy=&#x27;median&#x27;)),\n",
       "                                                 (&#x27;standardscaler&#x27;,\n",
       "                                                  StandardScaler())]),\n",
       "                                 [&#x27;energia&#x27;, &#x27;bailabilidad&#x27;, &#x27;acustica&#x27;,\n",
       "                                  &#x27;tempo_bpm&#x27;, &#x27;duracion_seg&#x27;,\n",
       "                                  &#x27;seguidores_miles&#x27;, &#x27;colaboracion&#x27;,\n",
       "                                  &#x27;explicita&#x27;, &#x27;en_playlist&#x27;]),\n",
       "                                (&#x27;cat&#x27;,\n",
       "                                 Pipeline(steps=[(&#x27;simpleimputer&#x27;,\n",
       "                                                  SimpleImputer(strategy=&#x27;most_frequent&#x27;)),\n",
       "                                                 (&#x27;onehotencoder&#x27;,\n",
       "                                                  OneHotEncoder(handle_unknown=&#x27;ignore&#x27;))]),\n",
       "                                 [&#x27;genero&#x27;])])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label  sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually sk-global\" id=\"sk-estimator-id-1\" type=\"checkbox\" ><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label  sk-toggleable__label-arrow\"><div><div>ColumnTransformer</div></div><div><a class=\"sk-estimator-doc-link \" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html\">?<span>Documentation for ColumnTransformer</span></a><span class=\"sk-estimator-doc-link \">i<span>Not fitted</span></span></div></label><div class=\"sk-toggleable__content \" data-param-prefix=\"\">\n",
       "        <div class=\"estimator-table\">\n",
       "            <details>\n",
       "                <summary>Parameters</summary>\n",
       "                <table class=\"parameters-table\">\n",
       "                  <tbody>\n",
       "                    \n",
       "        <tr class=\"user-set\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy transformers to clipboard\"\n",
       "                 onclick=\"copyToClipboard('transformers',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-transformers;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html#:~:text=transformers,-list%20of%20tuples\">\n",
       "            transformers\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-transformers;\">\n",
       "            transformers: list of tuples<br><br>List of (name, transformer, columns) tuples specifying the<br>transformer objects to be applied to subsets of the data.<br><br>name : str<br>    Like in Pipeline and FeatureUnion, this allows the transformer and<br>    its parameters to be set using ``set_params`` and searched in grid<br>    search.<br>transformer : {&#x27;drop&#x27;, &#x27;passthrough&#x27;} or estimator<br>    Estimator must support :term:`fit` and :term:`transform`.<br>    Special-cased strings &#x27;drop&#x27; and &#x27;passthrough&#x27; are accepted as<br>    well, to indicate to drop the columns or to pass them through<br>    untransformed, respectively.<br>columns :  str, array-like of str, int, array-like of int,                 array-like of bool, slice or callable<br>    Indexes the data on its second axis. Integers are interpreted as<br>    positional columns, while strings can reference DataFrame columns<br>    by name.  A scalar string or int should be used where<br>    ``transformer`` expects X to be a 1d array-like (vector),<br>    otherwise a 2d array will be passed to the transformer.<br>    A callable is passed the input data `X` and can return any of the<br>    above. To select multiple columns by name or dtype, you can use<br>    :obj:`make_column_selector`.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">[(&#x27;num&#x27;, ...), (&#x27;cat&#x27;, ...)]</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy remainder to clipboard\"\n",
       "                 onclick=\"copyToClipboard('remainder',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-remainder;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html#:~:text=remainder,-%7B%27drop%27%2C%20%27passthrough%27%7D%20or%20estimator%2C%20default%3D%27drop%27\">\n",
       "            remainder\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-remainder;\">\n",
       "            remainder: {&#x27;drop&#x27;, &#x27;passthrough&#x27;} or estimator, default=&#x27;drop&#x27;<br><br>By default, only the specified columns in `transformers` are<br>transformed and combined in the output, and the non-specified<br>columns are dropped. (default of ``&#x27;drop&#x27;``).<br>By specifying ``remainder=&#x27;passthrough&#x27;``, all remaining columns that<br>were not specified in `transformers`, but present in the data passed<br>to `fit` will be automatically passed through. This subset of columns<br>is concatenated with the output of the transformers. For dataframes,<br>extra columns not seen during `fit` will be excluded from the output<br>of `transform`.<br>By setting ``remainder`` to be an estimator, the remaining<br>non-specified columns will use the ``remainder`` estimator. The<br>estimator must support :term:`fit` and :term:`transform`.<br>Note that using this feature requires that the DataFrame columns<br>input at :term:`fit` and :term:`transform` have identical order.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">&#x27;drop&#x27;</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy sparse_threshold to clipboard\"\n",
       "                 onclick=\"copyToClipboard('sparse_threshold',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-sparse_threshold;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html#:~:text=sparse_threshold,-float%2C%20default%3D0.3\">\n",
       "            sparse_threshold\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-sparse_threshold;\">\n",
       "            sparse_threshold: float, default=0.3<br><br>If the output of the different transformers contains sparse matrices,<br>these will be stacked as a sparse matrix if the overall density is<br>lower than this value. Use ``sparse_threshold=0`` to always return<br>dense.  When the transformed output consists of all dense data, the<br>stacked result will be dense, and this keyword will be ignored.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">0.3</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy n_jobs to clipboard\"\n",
       "                 onclick=\"copyToClipboard('n_jobs',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-n_jobs;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html#:~:text=n_jobs,-int%2C%20default%3DNone\">\n",
       "            n_jobs\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-n_jobs;\">\n",
       "            n_jobs: int, default=None<br><br>Number of jobs to run in parallel.<br>``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.<br>``-1`` means using all processors. See :term:`Glossary &lt;n_jobs&gt;`<br>for more details.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">None</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy transformer_weights to clipboard\"\n",
       "                 onclick=\"copyToClipboard('transformer_weights',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-transformer_weights;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html#:~:text=transformer_weights,-dict%2C%20default%3DNone\">\n",
       "            transformer_weights\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-transformer_weights;\">\n",
       "            transformer_weights: dict, default=None<br><br>Multiplicative weights for features per transformer. The output of the<br>transformer is multiplied by these weights. Keys are transformer names,<br>values the weights.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">None</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy verbose to clipboard\"\n",
       "                 onclick=\"copyToClipboard('verbose',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-verbose;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html#:~:text=verbose,-bool%2C%20default%3DFalse\">\n",
       "            verbose\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-verbose;\">\n",
       "            verbose: bool, default=False<br><br>If True, the time elapsed while fitting each transformer will be<br>printed as it is completed.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">False</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy verbose_feature_names_out to clipboard\"\n",
       "                 onclick=\"copyToClipboard('verbose_feature_names_out',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-verbose_feature_names_out;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.compose.ColumnTransformer.html#:~:text=verbose_feature_names_out,-bool%2C%20str%20or%20Callable%5B%5Bstr%2C%20str%5D%2C%20str%5D%2C%20default%3DTrue\">\n",
       "            verbose_feature_names_out\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-verbose_feature_names_out;\">\n",
       "            verbose_feature_names_out: bool, str or Callable[[str, str], str], default=True<br><br>- If True, :meth:`ColumnTransformer.get_feature_names_out` will prefix<br>  all feature names with the name of the transformer that generated that<br>  feature. It is equivalent to setting<br>  `verbose_feature_names_out=&quot;{transformer_name}__{feature_name}&quot;`.<br>- If False, :meth:`ColumnTransformer.get_feature_names_out` will not<br>  prefix any feature names and will error if feature names are not<br>  unique.<br>- If ``Callable[[str, str], str]``,<br>  :meth:`ColumnTransformer.get_feature_names_out` will rename all the features<br>  using the name of the transformer. The first argument of the callable is the<br>  transformer name and the second argument is the feature name. The returned<br>  string will be the new feature name.<br>- If ``str``, it must be a string ready for formatting. The given string will<br>  be formatted using two field names: ``transformer_name`` and ``feature_name``.<br>  e.g. ``&quot;{feature_name}__{transformer_name}&quot;``. See :meth:`str.format` method<br>  from the standard library for more info.<br><br>.. versionadded:: 1.0<br><br>.. versionchanged:: 1.6<br>    `verbose_feature_names_out` can be a callable or a string to be formatted.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">True</td>\n",
       "        </tr>\n",
       "    \n",
       "                  </tbody>\n",
       "                </table>\n",
       "            </details>\n",
       "        </div>\n",
       "    </div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label  sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually sk-global\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label  sk-toggleable__label-arrow\"><div><div>num</div></div></label><div class=\"sk-toggleable__content \" data-param-prefix=\"num__\"><pre>[&#x27;energia&#x27;, &#x27;bailabilidad&#x27;, &#x27;acustica&#x27;, &#x27;tempo_bpm&#x27;, &#x27;duracion_seg&#x27;, &#x27;seguidores_miles&#x27;, &#x27;colaboracion&#x27;, &#x27;explicita&#x27;, &#x27;en_playlist&#x27;]</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator  sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually sk-global\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label  sk-toggleable__label-arrow\"><div><div>SimpleImputer</div></div><div><a class=\"sk-estimator-doc-link \" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html\">?<span>Documentation for SimpleImputer</span></a></div></label><div class=\"sk-toggleable__content \" data-param-prefix=\"num__simpleimputer__\">\n",
       "        <div class=\"estimator-table\">\n",
       "            <details>\n",
       "                <summary>Parameters</summary>\n",
       "                <table class=\"parameters-table\">\n",
       "                  <tbody>\n",
       "                    \n",
       "        <tr class=\"user-set\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy strategy to clipboard\"\n",
       "                 onclick=\"copyToClipboard('strategy',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-strategy;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=strategy,-str%20or%20Callable%2C%20default%3D%27mean%27\">\n",
       "            strategy\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-strategy;\">\n",
       "            strategy: str or Callable, default=&#x27;mean&#x27;<br><br>The imputation strategy.<br><br>- If &quot;mean&quot;, then replace missing values using the mean along<br>  each column. Can only be used with numeric data.<br>- If &quot;median&quot;, then replace missing values using the median along<br>  each column. Can only be used with numeric data.<br>- If &quot;most_frequent&quot;, then replace missing using the most frequent<br>  value along each column. Can be used with strings or numeric data.<br>  If there is more than one such value, only the smallest is returned.<br>- If &quot;constant&quot;, then replace missing values with fill_value. Can be<br>  used with strings or numeric data.<br>- If an instance of Callable, then replace missing values using the<br>  scalar statistic returned by running the callable over a dense 1d<br>  array containing non-missing values of each column.<br><br>.. versionadded:: 0.20<br>   strategy=&quot;constant&quot; for fixed value imputation.<br><br>.. versionadded:: 1.5<br>   strategy=callable for custom value imputation.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">&#x27;median&#x27;</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy missing_values to clipboard\"\n",
       "                 onclick=\"copyToClipboard('missing_values',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-missing_values;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=missing_values,-int%2C%20float%2C%20str%2C%20np.nan%2C%20None%20or%20pandas.NA%2C%20default%3Dnp.nan\">\n",
       "            missing_values\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-missing_values;\">\n",
       "            missing_values: int, float, str, np.nan, None or pandas.NA, default=np.nan<br><br>The placeholder for the missing values. All occurrences of<br>`missing_values` will be imputed. For pandas&#x27; dataframes with<br>nullable integer dtypes with missing values, `missing_values`<br>can be set to either `np.nan` or `pd.NA`.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">nan</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy fill_value to clipboard\"\n",
       "                 onclick=\"copyToClipboard('fill_value',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-fill_value;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=fill_value,-str%20or%20numerical%20value%2C%20default%3DNone\">\n",
       "            fill_value\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-fill_value;\">\n",
       "            fill_value: str or numerical value, default=None<br><br>When strategy == &quot;constant&quot;, `fill_value` is used to replace all<br>occurrences of missing_values. For string or object data types,<br>`fill_value` must be a string.<br>If `None`, `fill_value` will be 0 when imputing numerical<br>data and &quot;missing_value&quot; for strings or object data types.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">None</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy copy to clipboard\"\n",
       "                 onclick=\"copyToClipboard('copy',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-copy;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=copy,-bool%2C%20default%3DTrue\">\n",
       "            copy\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-copy;\">\n",
       "            copy: bool, default=True<br><br>If True, a copy of X will be created. If False, imputation will<br>be done in-place whenever possible. Note that, in the following cases,<br>a new copy will always be made, even if `copy=False`:<br><br>- If `X` is not an array of floating values;<br>- If `X` is encoded as a CSR matrix;<br>- If `add_indicator=True`.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">True</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy add_indicator to clipboard\"\n",
       "                 onclick=\"copyToClipboard('add_indicator',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-add_indicator;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=add_indicator,-bool%2C%20default%3DFalse\">\n",
       "            add_indicator\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-add_indicator;\">\n",
       "            add_indicator: bool, default=False<br><br>If True, a :class:`MissingIndicator` transform will stack onto output<br>of the imputer&#x27;s transform. This allows a predictive estimator<br>to account for missingness despite imputation. If a feature has no<br>missing values at fit/train time, the feature won&#x27;t appear on<br>the missing indicator even if there are missing values at<br>transform/test time.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">False</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy keep_empty_features to clipboard\"\n",
       "                 onclick=\"copyToClipboard('keep_empty_features',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-keep_empty_features;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=keep_empty_features,-bool%2C%20default%3DFalse\">\n",
       "            keep_empty_features\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-keep_empty_features;\">\n",
       "            keep_empty_features: bool, default=False<br><br>If True, features that consist exclusively of missing values when<br>`fit` is called are returned in results when `transform` is called.<br>The imputed value is always `0` except when `strategy=&quot;constant&quot;`<br>in which case `fill_value` will be used instead.<br><br>.. versionadded:: 1.2</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">False</td>\n",
       "        </tr>\n",
       "    \n",
       "                  </tbody>\n",
       "                </table>\n",
       "            </details>\n",
       "        </div>\n",
       "    </div></div></div><div class=\"sk-item\"><div class=\"sk-estimator  sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually sk-global\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label  sk-toggleable__label-arrow\"><div><div>StandardScaler</div></div><div><a class=\"sk-estimator-doc-link \" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.StandardScaler.html\">?<span>Documentation for StandardScaler</span></a></div></label><div class=\"sk-toggleable__content \" data-param-prefix=\"num__standardscaler__\">\n",
       "        <div class=\"estimator-table\">\n",
       "            <details>\n",
       "                <summary>Parameters</summary>\n",
       "                <table class=\"parameters-table\">\n",
       "                  <tbody>\n",
       "                    \n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy copy to clipboard\"\n",
       "                 onclick=\"copyToClipboard('copy',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-copy;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.StandardScaler.html#:~:text=copy,-bool%2C%20default%3DTrue\">\n",
       "            copy\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-copy;\">\n",
       "            copy: bool, default=True<br><br>If False, try to avoid a copy and do inplace scaling instead.<br>This is not guaranteed to always work inplace; e.g. if the data is<br>not a NumPy array or scipy.sparse CSR matrix, a copy may still be<br>returned.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">True</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy with_mean to clipboard\"\n",
       "                 onclick=\"copyToClipboard('with_mean',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-with_mean;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.StandardScaler.html#:~:text=with_mean,-bool%2C%20default%3DTrue\">\n",
       "            with_mean\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-with_mean;\">\n",
       "            with_mean: bool, default=True<br><br>If True, center the data before scaling.<br>This does not work (and will raise an exception) when attempted on<br>sparse matrices, because centering them entails building a dense<br>matrix which in common use cases is likely to be too large to fit in<br>memory.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">True</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy with_std to clipboard\"\n",
       "                 onclick=\"copyToClipboard('with_std',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-with_std;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.StandardScaler.html#:~:text=with_std,-bool%2C%20default%3DTrue\">\n",
       "            with_std\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-with_std;\">\n",
       "            with_std: bool, default=True<br><br>If True, scale the data to unit variance (or equivalently,<br>unit standard deviation).</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">True</td>\n",
       "        </tr>\n",
       "    \n",
       "                  </tbody>\n",
       "                </table>\n",
       "            </details>\n",
       "        </div>\n",
       "    </div></div></div></div></div></div></div></div><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label  sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually sk-global\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label  sk-toggleable__label-arrow\"><div><div>cat</div></div></label><div class=\"sk-toggleable__content \" data-param-prefix=\"cat__\"><pre>[&#x27;genero&#x27;]</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator  sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually sk-global\" id=\"sk-estimator-id-6\" type=\"checkbox\" ><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label  sk-toggleable__label-arrow\"><div><div>SimpleImputer</div></div><div><a class=\"sk-estimator-doc-link \" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html\">?<span>Documentation for SimpleImputer</span></a></div></label><div class=\"sk-toggleable__content \" data-param-prefix=\"cat__simpleimputer__\">\n",
       "        <div class=\"estimator-table\">\n",
       "            <details>\n",
       "                <summary>Parameters</summary>\n",
       "                <table class=\"parameters-table\">\n",
       "                  <tbody>\n",
       "                    \n",
       "        <tr class=\"user-set\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy strategy to clipboard\"\n",
       "                 onclick=\"copyToClipboard('strategy',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-strategy;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=strategy,-str%20or%20Callable%2C%20default%3D%27mean%27\">\n",
       "            strategy\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-strategy;\">\n",
       "            strategy: str or Callable, default=&#x27;mean&#x27;<br><br>The imputation strategy.<br><br>- If &quot;mean&quot;, then replace missing values using the mean along<br>  each column. Can only be used with numeric data.<br>- If &quot;median&quot;, then replace missing values using the median along<br>  each column. Can only be used with numeric data.<br>- If &quot;most_frequent&quot;, then replace missing using the most frequent<br>  value along each column. Can be used with strings or numeric data.<br>  If there is more than one such value, only the smallest is returned.<br>- If &quot;constant&quot;, then replace missing values with fill_value. Can be<br>  used with strings or numeric data.<br>- If an instance of Callable, then replace missing values using the<br>  scalar statistic returned by running the callable over a dense 1d<br>  array containing non-missing values of each column.<br><br>.. versionadded:: 0.20<br>   strategy=&quot;constant&quot; for fixed value imputation.<br><br>.. versionadded:: 1.5<br>   strategy=callable for custom value imputation.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">&#x27;most_frequent&#x27;</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy missing_values to clipboard\"\n",
       "                 onclick=\"copyToClipboard('missing_values',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-missing_values;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=missing_values,-int%2C%20float%2C%20str%2C%20np.nan%2C%20None%20or%20pandas.NA%2C%20default%3Dnp.nan\">\n",
       "            missing_values\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-missing_values;\">\n",
       "            missing_values: int, float, str, np.nan, None or pandas.NA, default=np.nan<br><br>The placeholder for the missing values. All occurrences of<br>`missing_values` will be imputed. For pandas&#x27; dataframes with<br>nullable integer dtypes with missing values, `missing_values`<br>can be set to either `np.nan` or `pd.NA`.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">nan</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy fill_value to clipboard\"\n",
       "                 onclick=\"copyToClipboard('fill_value',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-fill_value;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=fill_value,-str%20or%20numerical%20value%2C%20default%3DNone\">\n",
       "            fill_value\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-fill_value;\">\n",
       "            fill_value: str or numerical value, default=None<br><br>When strategy == &quot;constant&quot;, `fill_value` is used to replace all<br>occurrences of missing_values. For string or object data types,<br>`fill_value` must be a string.<br>If `None`, `fill_value` will be 0 when imputing numerical<br>data and &quot;missing_value&quot; for strings or object data types.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">None</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy copy to clipboard\"\n",
       "                 onclick=\"copyToClipboard('copy',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-copy;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=copy,-bool%2C%20default%3DTrue\">\n",
       "            copy\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-copy;\">\n",
       "            copy: bool, default=True<br><br>If True, a copy of X will be created. If False, imputation will<br>be done in-place whenever possible. Note that, in the following cases,<br>a new copy will always be made, even if `copy=False`:<br><br>- If `X` is not an array of floating values;<br>- If `X` is encoded as a CSR matrix;<br>- If `add_indicator=True`.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">True</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy add_indicator to clipboard\"\n",
       "                 onclick=\"copyToClipboard('add_indicator',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-add_indicator;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=add_indicator,-bool%2C%20default%3DFalse\">\n",
       "            add_indicator\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-add_indicator;\">\n",
       "            add_indicator: bool, default=False<br><br>If True, a :class:`MissingIndicator` transform will stack onto output<br>of the imputer&#x27;s transform. This allows a predictive estimator<br>to account for missingness despite imputation. If a feature has no<br>missing values at fit/train time, the feature won&#x27;t appear on<br>the missing indicator even if there are missing values at<br>transform/test time.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">False</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy keep_empty_features to clipboard\"\n",
       "                 onclick=\"copyToClipboard('keep_empty_features',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-keep_empty_features;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.impute.SimpleImputer.html#:~:text=keep_empty_features,-bool%2C%20default%3DFalse\">\n",
       "            keep_empty_features\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-keep_empty_features;\">\n",
       "            keep_empty_features: bool, default=False<br><br>If True, features that consist exclusively of missing values when<br>`fit` is called are returned in results when `transform` is called.<br>The imputed value is always `0` except when `strategy=&quot;constant&quot;`<br>in which case `fill_value` will be used instead.<br><br>.. versionadded:: 1.2</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">False</td>\n",
       "        </tr>\n",
       "    \n",
       "                  </tbody>\n",
       "                </table>\n",
       "            </details>\n",
       "        </div>\n",
       "    </div></div></div><div class=\"sk-item\"><div class=\"sk-estimator  sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually sk-global\" id=\"sk-estimator-id-7\" type=\"checkbox\" ><label for=\"sk-estimator-id-7\" class=\"sk-toggleable__label  sk-toggleable__label-arrow\"><div><div>OneHotEncoder</div></div><div><a class=\"sk-estimator-doc-link \" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html\">?<span>Documentation for OneHotEncoder</span></a></div></label><div class=\"sk-toggleable__content \" data-param-prefix=\"cat__onehotencoder__\">\n",
       "        <div class=\"estimator-table\">\n",
       "            <details>\n",
       "                <summary>Parameters</summary>\n",
       "                <table class=\"parameters-table\">\n",
       "                  <tbody>\n",
       "                    \n",
       "        <tr class=\"user-set\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy handle_unknown to clipboard\"\n",
       "                 onclick=\"copyToClipboard('handle_unknown',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-handle_unknown;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=handle_unknown,-%7B%27error%27%2C%20%27ignore%27%2C%20%27infrequent_if_exist%27%2C%20%27warn%27%7D%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20default%3D%27error%27\">\n",
       "            handle_unknown\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-handle_unknown;\">\n",
       "            handle_unknown: {&#x27;error&#x27;, &#x27;ignore&#x27;, &#x27;infrequent_if_exist&#x27;, &#x27;warn&#x27;},                      default=&#x27;error&#x27;<br><br>Specifies the way unknown categories are handled during :meth:`transform`.<br><br>- &#x27;error&#x27; : Raise an error if an unknown category is present during transform.<br>- &#x27;ignore&#x27; : When an unknown category is encountered during<br>  transform, the resulting one-hot encoded columns for this feature<br>  will be all zeros. In the inverse transform, an unknown category<br>  will be denoted as None.<br>- &#x27;infrequent_if_exist&#x27; : When an unknown category is encountered<br>  during transform, the resulting one-hot encoded columns for this<br>  feature will map to the infrequent category if it exists. The<br>  infrequent category will be mapped to the last position in the<br>  encoding. During inverse transform, an unknown category will be<br>  mapped to the category denoted `&#x27;infrequent&#x27;` if it exists. If the<br>  `&#x27;infrequent&#x27;` category does not exist, then :meth:`transform` and<br>  :meth:`inverse_transform` will handle an unknown category as with<br>  `handle_unknown=&#x27;ignore&#x27;`. Infrequent categories exist based on<br>  `min_frequency` and `max_categories`. Read more in the<br>  :ref:`User Guide &lt;encoder_infrequent_categories&gt;`.<br>- &#x27;warn&#x27; : When an unknown category is encountered during transform<br>  a warning is issued, and the encoding then proceeds as described for<br>  `handle_unknown=&quot;infrequent_if_exist&quot;`.<br><br>.. versionchanged:: 1.1<br>    `&#x27;infrequent_if_exist&#x27;` was added to automatically handle unknown<br>    categories and infrequent categories.<br><br>.. versionadded:: 1.6<br>   The option `&quot;warn&quot;` was added in 1.6.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">&#x27;ignore&#x27;</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy categories to clipboard\"\n",
       "                 onclick=\"copyToClipboard('categories',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-categories;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=categories,-%27auto%27%20or%20a%20list%20of%20array-like%2C%20default%3D%27auto%27\">\n",
       "            categories\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-categories;\">\n",
       "            categories: &#x27;auto&#x27; or a list of array-like, default=&#x27;auto&#x27;<br><br>Categories (unique values) per feature:<br><br>- &#x27;auto&#x27; : Determine categories automatically from the training data.<br>- list : ``categories[i]`` holds the categories expected in the ith<br>  column. The passed categories should not mix strings and numeric<br>  values within a single feature, and should be sorted in case of<br>  numeric values.<br><br>The used categories can be found in the ``categories_`` attribute.<br><br>.. versionadded:: 0.20</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">&#x27;auto&#x27;</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy drop to clipboard\"\n",
       "                 onclick=\"copyToClipboard('drop',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-drop;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=drop,-%7B%27first%27%2C%20%27if_binary%27%7D%20or%20an%20array-like%20of%20shape%20%28n_features%2C%29%2C%20%20%20%20%20%20%20%20%20%20%20%20%20default%3DNone\">\n",
       "            drop\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-drop;\">\n",
       "            drop: {&#x27;first&#x27;, &#x27;if_binary&#x27;} or an array-like of shape (n_features,),             default=None<br><br>Specifies a methodology to use to drop one of the categories per<br>feature. This is useful in situations where perfectly collinear<br>features cause problems, such as when feeding the resulting data<br>into an unregularized linear regression model.<br><br>However, dropping one category breaks the symmetry of the original<br>representation and can therefore induce a bias in downstream models,<br>for instance for penalized linear classification or regression models.<br><br>- None : retain all features (the default).<br>- &#x27;first&#x27; : drop the first category in each feature. If only one<br>  category is present, the feature will be dropped entirely.<br>- &#x27;if_binary&#x27; : drop the first category in each feature with two<br>  categories. Features with 1 or more than 2 categories are<br>  left intact.<br>- array : ``drop[i]`` is the category in feature ``X[:, i]`` that<br>  should be dropped.<br><br>When `max_categories` or `min_frequency` is configured to group<br>infrequent categories, the dropping behavior is handled after the<br>grouping.<br><br>.. versionadded:: 0.21<br>   The parameter `drop` was added in 0.21.<br><br>.. versionchanged:: 0.23<br>   The option `drop=&#x27;if_binary&#x27;` was added in 0.23.<br><br>.. versionchanged:: 1.1<br>    Support for dropping infrequent categories.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">None</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy sparse_output to clipboard\"\n",
       "                 onclick=\"copyToClipboard('sparse_output',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-sparse_output;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=sparse_output,-bool%2C%20default%3DTrue\">\n",
       "            sparse_output\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-sparse_output;\">\n",
       "            sparse_output: bool, default=True<br><br>When ``True``, it returns a SciPy sparse matrix/array<br>in &quot;Compressed Sparse Row&quot; (CSR) format.<br><br>.. versionadded:: 1.2<br>   `sparse` was renamed to `sparse_output`</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">True</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy dtype to clipboard\"\n",
       "                 onclick=\"copyToClipboard('dtype',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-dtype;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=dtype,-number%20type%2C%20default%3Dnp.float64\">\n",
       "            dtype\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-dtype;\">\n",
       "            dtype: number type, default=np.float64<br><br>Desired dtype of output.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">&lt;class &#x27;numpy.float64&#x27;&gt;</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy min_frequency to clipboard\"\n",
       "                 onclick=\"copyToClipboard('min_frequency',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-min_frequency;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=min_frequency,-int%20or%20float%2C%20default%3DNone\">\n",
       "            min_frequency\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-min_frequency;\">\n",
       "            min_frequency: int or float, default=None<br><br>Specifies the minimum frequency below which a category will be<br>considered infrequent.<br><br>- If `int`, categories with a smaller cardinality will be considered<br>  infrequent.<br><br>- If `float`, categories with a smaller cardinality than<br>  `min_frequency * n_samples`  will be considered infrequent.<br><br>.. versionadded:: 1.1<br>    Read more in the :ref:`User Guide &lt;encoder_infrequent_categories&gt;`.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">None</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy max_categories to clipboard\"\n",
       "                 onclick=\"copyToClipboard('max_categories',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-max_categories;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=max_categories,-int%2C%20default%3DNone\">\n",
       "            max_categories\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-max_categories;\">\n",
       "            max_categories: int, default=None<br><br>Specifies an upper limit to the number of output features for each input<br>feature when considering infrequent categories. If there are infrequent<br>categories, `max_categories` includes the category representing the<br>infrequent categories along with the frequent categories. If `None`,<br>there is no limit to the number of output features.<br><br>.. versionadded:: 1.1<br>    Read more in the :ref:`User Guide &lt;encoder_infrequent_categories&gt;`.</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">None</td>\n",
       "        </tr>\n",
       "    \n",
       "\n",
       "        <tr class=\"default\">\n",
       "            <td><button type=\"button\" class=\"copy-paste-icon\"\n",
       "                 aria-label=\"Copy feature_name_combiner to clipboard\"\n",
       "                 onclick=\"copyToClipboard('feature_name_combiner',\n",
       "                          this.parentElement.nextElementSibling)\"\n",
       "            ></button></td>\n",
       "            <td class=\"param\">\n",
       "        <a class=\"param-doc-link\"\n",
       "            style=\"anchor-name: --doc-link-feature_name_combiner;\"\n",
       "            rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.9/modules/generated/sklearn.preprocessing.OneHotEncoder.html#:~:text=feature_name_combiner,-%22concat%22%20or%20callable%2C%20default%3D%22concat%22\">\n",
       "            feature_name_combiner\n",
       "            <span class=\"param-doc-description\"\n",
       "            style=\"position-anchor: --doc-link-feature_name_combiner;\">\n",
       "            feature_name_combiner: &quot;concat&quot; or callable, default=&quot;concat&quot;<br><br>Callable with signature `def callable(input_feature, category)` that returns a<br>string. This is used to create feature names to be returned by<br>:meth:`get_feature_names_out`.<br><br>`&quot;concat&quot;` concatenates encoded feature name and category with<br>`feature + &quot;_&quot; + str(category)`.E.g. feature X with values 1, 6, 7 create<br>feature names `X_1, X_6, X_7`.<br><br>.. versionadded:: 1.3</span>\n",
       "        </a>\n",
       "    </td>\n",
       "            <td class=\"value\">&#x27;concat&#x27;</td>\n",
       "        </tr>\n",
       "    \n",
       "                  </tbody>\n",
       "                </table>\n",
       "            </details>\n",
       "        </div>\n",
       "    </div></div></div></div></div></div></div></div></div></div></div></div><script>/*  Authors: The scikit-learn developers\n",
       " SPDX-License-Identifier: BSD-3-Clause\n",
       "*/\n",
       "\n",
       "function copyToClipboard(text, element) {\n",
       "    // Get the parameter prefix from the closest toggleable content\n",
       "    const toggleableContent = element.closest('.sk-toggleable__content');\n",
       "    const paramPrefix = toggleableContent ? toggleableContent.dataset.paramPrefix : '';\n",
       "    const fullParamName = paramPrefix ? `${paramPrefix}${text}` : text;\n",
       "\n",
       "    const originalStyle = element.style;\n",
       "    const computedStyle = window.getComputedStyle(element);\n",
       "    const originalWidth = computedStyle.width;\n",
       "    const originalHTML = element.innerHTML.replace('Copied!', '');\n",
       "\n",
       "    navigator.clipboard.writeText(fullParamName)\n",
       "        .then(() => {\n",
       "            element.style.width = originalWidth;\n",
       "            element.style.color = 'green';\n",
       "            element.innerHTML = \"Copied!\";\n",
       "\n",
       "            setTimeout(() => {\n",
       "                element.innerHTML = originalHTML;\n",
       "                element.style = originalStyle;\n",
       "            }, 2000);\n",
       "        })\n",
       "        .catch(err => {\n",
       "            console.error('Failed to copy:', err);\n",
       "            element.style.color = 'red';\n",
       "            element.innerHTML = \"Failed!\";\n",
       "            setTimeout(() => {\n",
       "                element.innerHTML = originalHTML;\n",
       "                element.style = originalStyle;\n",
       "            }, 2000);\n",
       "        });\n",
       "    return false;\n",
       "}\n",
       "\n",
       "document.querySelectorAll('.copy-paste-icon').forEach(function(element) {\n",
       "    const toggleableContent = element.closest('.sk-toggleable__content');\n",
       "    const paramPrefix = toggleableContent ? toggleableContent.dataset.paramPrefix : '';\n",
       "\n",
       "    const parent = element.parentElement;\n",
       "    if (!parent || !parent.nextElementSibling) {\n",
       "        console.warn('Expected copy-paste icon is missing from the DOM structure');\n",
       "        return;\n",
       "    }\n",
       "\n",
       "    const paramName = element.parentElement.nextElementSibling\n",
       "        .textContent.trim().split(' ')[0];\n",
       "    const fullParamName = paramPrefix ? `${paramPrefix}${paramName}` : paramName;\n",
       "\n",
       "    element.setAttribute('title', fullParamName);\n",
       "});\n",
       "\n",
       "/**\n",
       " * Copy the list of feature names formatted as a Python list.\n",
       " *\n",
       " * @param {HTMLElement} element - The copy button inside a `.features` block; its siblings\n",
       " *   contain a `details` element and a table containing feature named.\n",
       " * @returns {boolean} Always returns `false` so callers can prevent the default click behavior.\n",
       " */\n",
       "function copyFeatureNamesToClipboard(element) {\n",
       "    var detailsElem = element.closest('.features').querySelector('details');\n",
       "    var wasOpen = detailsElem.open;\n",
       "    detailsElem.open = true;\n",
       "    var content = element.closest('.features').querySelector('tbody')\n",
       "                  .innerText.trim();\n",
       "    if (!wasOpen) detailsElem.open = false;\n",
       "    const rows = content.split('\\n').map(row => `    \"${row}\"`);\n",
       "    const formattedText = `[\\n${rows.join(',\\n')},\\n]`;\n",
       "    const originalHTML = element.innerHTML.replace('âœ”', '');\n",
       "    const originalStyle = element.style;\n",
       "    const copyMark = document.createElement('span');\n",
       "    copyMark.innerHTML = 'âœ”';\n",
       "    copyMark.style.color = 'blue';\n",
       "    copyMark.style.fontSize = '1em';\n",
       "\n",
       "    navigator.clipboard.writeText(formattedText)\n",
       "        .then(() => {\n",
       "            element.style.display = 'none';\n",
       "            element.parentElement.appendChild(copyMark);\n",
       "\n",
       "            setTimeout(() => {\n",
       "                copyMark.remove();\n",
       "                element.innerHTML = originalHTML;\n",
       "                element.style = originalStyle;\n",
       "            }, 1000);\n",
       "        })\n",
       "        .catch(err => {\n",
       "            console.error('Failed to copy:', err);\n",
       "            element.style.color = 'orange';\n",
       "            element.innerHTML = \"Failed!\";\n",
       "            setTimeout(() => {\n",
       "                element.innerHTML = originalHTML;\n",
       "                element.style = originalStyle;\n",
       "            }, 1000);\n",
       "        });\n",
       "    return false;\n",
       "}\n",
       "/**\n",
       " * Adapted from Skrub\n",
       " * https://github.com/skrub-data/skrub/blob/403466d1d5d4dc76a7ef569b3f8228db59a31dc3/skrub/_reporting/_data/templates/report.js#L789\n",
       " * @returns \"light\" or \"dark\"\n",
       " */\n",
       "function detectTheme(element) {\n",
       "    const body = document.querySelector('body');\n",
       "\n",
       "    // Check VSCode theme\n",
       "    const themeKindAttr = body.getAttribute('data-vscode-theme-kind');\n",
       "    const themeNameAttr = body.getAttribute('data-vscode-theme-name');\n",
       "\n",
       "    if (themeKindAttr && themeNameAttr) {\n",
       "        const themeKind = themeKindAttr.toLowerCase();\n",
       "        const themeName = themeNameAttr.toLowerCase();\n",
       "\n",
       "        if (themeKind.includes(\"dark\") || themeName.includes(\"dark\")) {\n",
       "            return \"dark\";\n",
       "        }\n",
       "        if (themeKind.includes(\"light\") || themeName.includes(\"light\")) {\n",
       "            return \"light\";\n",
       "        }\n",
       "    }\n",
       "\n",
       "    // Check Jupyter theme\n",
       "    if (body.getAttribute('data-jp-theme-light') === 'false') {\n",
       "        return 'dark';\n",
       "    } else if (body.getAttribute('data-jp-theme-light') === 'true') {\n",
       "        return 'light';\n",
       "    }\n",
       "\n",
       "    // Guess based on a parent element's color\n",
       "    const color = window.getComputedStyle(element.parentNode, null).getPropertyValue('color');\n",
       "    const match = color.match(/^rgb\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)\\s*$/i);\n",
       "    if (match) {\n",
       "        const [r, g, b] = [\n",
       "            parseFloat(match[1]),\n",
       "            parseFloat(match[2]),\n",
       "            parseFloat(match[3])\n",
       "        ];\n",
       "\n",
       "        // https://en.wikipedia.org/wiki/HSL_and_HSV#Lightness\n",
       "        const luma = 0.299 * r + 0.587 * g + 0.114 * b;\n",
       "\n",
       "        if (luma > 180) {\n",
       "            // If the text is very bright we have a dark theme\n",
       "            return 'dark';\n",
       "        }\n",
       "        if (luma < 75) {\n",
       "            // If the text is very dark we have a light theme\n",
       "            return 'light';\n",
       "        }\n",
       "        // Otherwise fall back to the next heuristic.\n",
       "    }\n",
       "\n",
       "    // Fallback to system preference\n",
       "    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n",
       "}\n",
       "\n",
       "\n",
       "function forceTheme(elementId) {\n",
       "    const estimatorElement = document.querySelector(`#${elementId}`);\n",
       "    if (estimatorElement === null) {\n",
       "        console.error(`Element with id ${elementId} not found.`);\n",
       "    } else {\n",
       "        const theme = detectTheme(estimatorElement);\n",
       "        estimatorElement.classList.add(theme);\n",
       "    }\n",
       "}\n",
       "\n",
       "forceTheme('sk-container-id-1');</script></body>"
      ],
      "text/plain": [
       "ColumnTransformer(transformers=[('num',\n",
       "                                 Pipeline(steps=[('simpleimputer',\n",
       "                                                  SimpleImputer(strategy='median')),\n",
       "                                                 ('standardscaler',\n",
       "                                                  StandardScaler())]),\n",
       "                                 ['energia', 'bailabilidad', 'acustica',\n",
       "                                  'tempo_bpm', 'duracion_seg',\n",
       "                                  'seguidores_miles', 'colaboracion',\n",
       "                                  'explicita', 'en_playlist']),\n",
       "                                ('cat',\n",
       "                                 Pipeline(steps=[('simpleimputer',\n",
       "                                                  SimpleImputer(strategy='most_frequent')),\n",
       "                                                 ('onehotencoder',\n",
       "                                                  OneHotEncoder(handle_unknown='ignore'))]),\n",
       "                                 ['genero'])])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def crear_pre():\n",
    "    return ColumnTransformer([\n",
    "        (\"num\", make_pipeline(SimpleImputer(strategy=\"median\"), StandardScaler()), NUMERICAS),\n",
    "        (\"cat\", make_pipeline(SimpleImputer(strategy=\"most_frequent\"), OneHotEncoder(handle_unknown=\"ignore\")),\n",
    "         CATEGORICAS),\n",
    "    ])\n",
    "\n",
    "\n",
    "cv = StratifiedKFold(5, shuffle=True, random_state=42)\n",
    "crear_pre()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1b66908",
   "metadata": {},
   "source": [
    "## 4. Línea base y comparación de modelos\n",
    "\n",
    "El enunciado pide al menos un modelo lineal, uno por distancia o SVM, un Random Forest y XGBoost, todos con el mismo\n",
    "preprocesamiento y comparados con validación cruzada de 5 pliegues **sobre train** y `scoring=\"roc_auc\"`. El AUC mide\n",
    "qué tan bien ordena el modelo las canciones (hits arriba) sin depender de un umbral; 0.5 es azar.\n",
    "\n",
    "XGBoost entra aquí con valores razonables y fijos (300 árboles, `learning_rate` 0.05, profundidad 4); se ajusta en el\n",
    "paso 5. Dentro de la búsqueda cada modelo usa un solo hilo (`n_jobs=1`) y la validación cruzada reparte los pliegues\n",
    "entre los núcleos."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7eceddd7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:51:45.300497Z",
     "iopub.status.busy": "2026-10-18T17:51:45.299499Z",
     "iopub.status.idle": "2026-10-18T17:52:05.290182Z",
     "shell.execute_reply": "2026-10-18T17:52:05.288671Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                     AUC media  desviación\n",
      "modelo                                    \n",
      "Dummy                    0.500       0.000\n",
      "Regresión logística      0.828       0.016\n",
      "SVC (kernel RBF)         0.825       0.027\n",
      "Random Forest            0.851       0.019\n",
      "Gradient boosting        0.848       0.019\n",
      "XGBoost                  0.841       0.023\n"
     ]
    }
   ],
   "source": [
    "from sklearn.svm import SVC\n",
    "from xgboost import XGBClassifier\n",
    "\n",
    "XGB_BASE = dict(n_estimators=300, learning_rate=0.05, max_depth=4, subsample=0.8, colsample_bytree=0.8,\n",
    "                random_state=42, n_jobs=1)\n",
    "candidatos = {\n",
    "    \"Dummy\": DummyClassifier(),\n",
    "    \"Regresión logística\": LogisticRegression(max_iter=2000),\n",
    "    \"SVC (kernel RBF)\": SVC(random_state=42),\n",
    "    \"Random Forest\": RandomForestClassifier(n_estimators=300, min_samples_leaf=3, random_state=42),\n",
    "    \"Gradient boosting\": GradientBoostingClassifier(random_state=42),\n",
    "    \"XGBoost\": XGBClassifier(**XGB_BASE),\n",
    "}\n",
    "filas = []\n",
    "for nombre, modelo in candidatos.items():\n",
    "    pipe = Pipeline([(\"pre\", crear_pre()), (\"modelo\", modelo)])\n",
    "    auc = cross_val_score(pipe, X_tr, y_tr, cv=cv, scoring=\"roc_auc\", n_jobs=-1)\n",
    "    filas.append({\"modelo\": nombre, \"AUC media\": round(auc.mean(), 3), \"desviación\": round(auc.std(), 3)})\n",
    "comparacion = pd.DataFrame(filas).set_index(\"modelo\")\n",
    "print(comparacion)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e73ff8b5",
   "metadata": {},
   "source": [
    "| modelo | AUC media (CV) | desviación |\n",
    "|---|---|---|\n",
    "| Dummy | 0.5 | 0.0 |\n",
    "| Regresión logística | 0.828 | 0.016 |\n",
    "| SVC (kernel RBF) | 0.825 | 0.027 |\n",
    "| Random Forest | 0.851 | 0.019 |\n",
    "| Gradient boosting | 0.848 | 0.019 |\n",
    "| XGBoost (sin ajustar) | 0.841 | 0.023 |\n",
    "\n",
    "Los tres ensambles quedan arriba (0.841 a 0.851) y por encima del modelo lineal y del SVC (0.828 y 0.825). Las\n",
    "diferencias entre ensambles son menores que la desviación entre pliegues. Se ajusta XGBoost: con sus valores fijos\n",
    "queda tercero, pero es el que más hiperparámetros ofrece para mejorar (tasa, profundidad, muestreo de filas y\n",
    "columnas, regularización) y además permite early stopping.\n",
    "\n",
    "## 5. XGBoost: early stopping y búsqueda de hiperparámetros\n",
    "\n",
    "### 5.1 ¿Cuántos árboles? Early stopping con una validación separada\n",
    "\n",
    "Primero se averigua un orden de magnitud para `n_estimators`. Se aparta el 20 % de **train** como validación (el test\n",
    "no se toca), se piden hasta 2000 árboles con `learning_rate=0.05` y `early_stopping_rounds=50` detiene el\n",
    "entrenamiento cuando la log-loss de validación deja de mejorar. En xgboost 2.1 o superior, `early_stopping_rounds` y\n",
    "`eval_metric` van en el constructor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "8755025a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:05.294182Z",
     "iopub.status.busy": "2026-10-18T17:52:05.293187Z",
     "iopub.status.idle": "2026-10-18T17:52:05.712197Z",
     "shell.execute_reply": "2026-10-18T17:52:05.710685Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "canciones: ajuste 900 | validación 225\n",
      "best_iteration: 97 | log-loss de validación: 0.4336\n"
     ]
    }
   ],
   "source": [
    "X_fit, X_val, y_fit, y_val = train_test_split(X_tr, y_tr, test_size=0.2, stratify=y_tr, random_state=42)\n",
    "pre_es = crear_pre().fit(X_fit)\n",
    "xgb_es = XGBClassifier(n_estimators=2000, learning_rate=0.05, max_depth=4, subsample=0.8, colsample_bytree=0.8,\n",
    "                       eval_metric=\"logloss\", early_stopping_rounds=50, random_state=42, n_jobs=4)\n",
    "xgb_es.fit(pre_es.transform(X_fit), y_fit, eval_set=[(pre_es.transform(X_val), y_val)], verbose=False)\n",
    "print(\"canciones: ajuste\", len(X_fit), \"| validación\", len(X_val))\n",
    "print(\"best_iteration:\", xgb_es.best_iteration, \"| log-loss de validación:\", round(xgb_es.best_score, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8ec990a",
   "metadata": {},
   "source": [
    "Con 900 canciones de ajuste y 225 de validación, la mejor ronda es la **97** (98 árboles) con log-loss de validación\n",
    "0.4336. Con una tasa de 0.05 bastan unos 100 árboles; con tasas menores harán falta más. Por eso el rango de\n",
    "`n_estimators` de la búsqueda va de 50 a 399 y se busca **junto** con `learning_rate`, nunca por separado.\n",
    "\n",
    "Dentro de la búsqueda no se usa early stopping: con un `eval_set` fijo, cada pliegue de la validación cruzada se\n",
    "detendría mirando datos que en otros pliegues son de entrenamiento, y la comparación deja de ser limpia. El número\n",
    "de árboles pasa a ser un hiperparámetro más.\n",
    "\n",
    "### 5.2 Búsqueda aleatoria\n",
    "\n",
    "`RandomizedSearchCV` prueba 30 combinaciones al azar, cada una con los 5 pliegues: 150 ajustes. Los rangos:\n",
    "\n",
    "- `learning_rate` entre 0.01 y 0.3 en escala logarítmica (`loguniform`): importa el orden de magnitud.\n",
    "- `n_estimators` entre 50 y 399, para que tasas bajas tengan árboles suficientes.\n",
    "- `max_depth` entre 2 y 6: árboles cortos, como es habitual en boosting.\n",
    "- `min_child_weight` entre 1 y 9: hojas con más peso mínimo frenan cortes sobre pocas canciones.\n",
    "- `subsample` y `colsample_bytree` entre 0.6 y 1.0 (`uniform(0.6, 0.4)`): muestrear filas y columnas reduce el\n",
    "  sobreajuste.\n",
    "- `reg_lambda` entre 0.1 y 10 en escala logarítmica: la regularización L2 de los valores de las hojas.\n",
    "\n",
    "Los nombres llevan el prefijo del paso del pipeline: `xgb__learning_rate`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "85aeb6c5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:05.716648Z",
     "iopub.status.busy": "2026-10-18T17:52:05.716648Z",
     "iopub.status.idle": "2026-10-18T17:52:10.471798Z",
     "shell.execute_reply": "2026-10-18T17:52:10.470792Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "combinaciones: 30 | ajustes: 150\n",
      "best_params_: {'xgb__colsample_bytree': 0.6488, 'xgb__learning_rate': 0.0336, 'xgb__max_depth': 2, 'xgb__min_child_weight': 1, 'xgb__n_estimators': 332, 'xgb__reg_lambda': 0.7149, 'xgb__subsample': 0.9272}\n",
      "best_score_: 0.8594\n"
     ]
    }
   ],
   "source": [
    "espacio = {\n",
    "    \"xgb__n_estimators\": randint(50, 400),\n",
    "    \"xgb__learning_rate\": loguniform(0.01, 0.3),\n",
    "    \"xgb__max_depth\": randint(2, 7),\n",
    "    \"xgb__min_child_weight\": randint(1, 10),\n",
    "    \"xgb__subsample\": uniform(0.6, 0.4),\n",
    "    \"xgb__colsample_bytree\": uniform(0.6, 0.4),\n",
    "    \"xgb__reg_lambda\": loguniform(0.1, 10),\n",
    "}\n",
    "pipe_xgb = Pipeline([(\"pre\", crear_pre()), (\"xgb\", XGBClassifier(random_state=42, n_jobs=1))])\n",
    "busqueda = RandomizedSearchCV(pipe_xgb, espacio, n_iter=30, cv=cv, scoring=\"roc_auc\", random_state=42, n_jobs=-1)\n",
    "busqueda.fit(X_tr, y_tr)\n",
    "\n",
    "n_comb = len(busqueda.cv_results_[\"params\"])\n",
    "print(\"combinaciones:\", n_comb, \"| ajustes:\", n_comb * cv.get_n_splits())\n",
    "print(\"best_params_:\", {k: (round(float(v), 4) if isinstance(v, float) else v) for k, v in busqueda.best_params_.items()})\n",
    "print(\"best_score_:\", round(busqueda.best_score_, 4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "ef402182",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:10.475798Z",
     "iopub.status.busy": "2026-10-18T17:52:10.475798Z",
     "iopub.status.idle": "2026-10-18T17:52:10.487947Z",
     "shell.execute_reply": "2026-10-18T17:52:10.486942Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " param_xgb__learning_rate  param_xgb__n_estimators  param_xgb__max_depth  param_xgb__subsample  mean_test_score\n",
      "                   0.0336                    332.0                   2.0                0.9272           0.8594\n",
      "                   0.0592                    112.0                   3.0                0.7901           0.8568\n",
      "                   0.0228                    252.0                   5.0                0.6969           0.8550\n",
      "                   0.0102                    367.0                   4.0                0.6479           0.8548\n",
      "                   0.0143                    335.0                   5.0                0.7297           0.8538\n"
     ]
    }
   ],
   "source": [
    "top = pd.DataFrame(busqueda.cv_results_).sort_values(\"rank_test_score\").head(5)\n",
    "cols = [\"param_xgb__learning_rate\", \"param_xgb__n_estimators\", \"param_xgb__max_depth\", \"param_xgb__subsample\",\n",
    "        \"mean_test_score\"]\n",
    "print(top[cols].astype(float).round(4).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "415f665d",
   "metadata": {},
   "source": [
    "La mejor combinación usa `learning_rate` 0.0336, 332 árboles, `max_depth` 2, `min_child_weight` 1, `subsample`\n",
    "0.927, `colsample_bytree` 0.649 y `reg_lambda` 0.715, con AUC de validación **0.8594** (XGBoost sin ajustar daba\n",
    "0.841 y el Random Forest 0.851). Las cinco mejores combinaciones quedan entre 0.854 y 0.859: no vale la pena buscar\n",
    "más fino. Fíjate en el patrón: tasa baja con muchos árboles poco profundos.\n",
    "\n",
    "## 6. Umbral de decisión o `scale_pos_weight`\n",
    "\n",
    "Con umbral 0.5 el modelo deja pasar muchos hits, y dejar pasar un hit cuesta más que promover una canción que no\n",
    "despega. Hay dos palancas para favorecer el recall: bajar el umbral o subir `scale_pos_weight`. Primero el umbral, con\n",
    "la regla del enunciado: el **umbral más alto que detecte al menos el 70 % de los hits**, elegido **sin mirar el\n",
    "test**. `cross_val_predict` devuelve, para cada canción de train, la probabilidad que le dio un modelo que no la vio\n",
    "al entrenar:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5179c335",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:10.490948Z",
     "iopub.status.busy": "2026-10-18T17:52:10.490948Z",
     "iopub.status.idle": "2026-10-18T17:52:10.680588Z",
     "shell.execute_reply": "2026-10-18T17:52:10.679581Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "        precision  recall  alertas\n",
      "umbral                            \n",
      "0.20        0.497   0.841      523\n",
      "0.25        0.528   0.793      464\n",
      "0.30        0.563   0.748      410\n",
      "0.35        0.614   0.699      352\n",
      "0.40        0.662   0.647      302\n",
      "0.50        0.722   0.537      230"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "umbral elegido: 0.3\n"
     ]
    }
   ],
   "source": [
    "mejor = busqueda.best_estimator_\n",
    "proba_cv = cross_val_predict(mejor, X_tr, y_tr, cv=cv, method=\"predict_proba\", n_jobs=-1)[:, 1]\n",
    "\n",
    "filas = []\n",
    "for u in [0.20, 0.25, 0.30, 0.35, 0.40, 0.50]:\n",
    "    pred = (proba_cv >= u).astype(int)\n",
    "    filas.append({\"umbral\": u, \"precision\": round(precision_score(y_tr, pred), 3),\n",
    "                  \"recall\": round(recall_score(y_tr, pred), 3), \"alertas\": int(pred.sum())})\n",
    "tabla_umbral = pd.DataFrame(filas).set_index(\"umbral\")\n",
    "print(tabla_umbral)\n",
    "\n",
    "UMBRAL = tabla_umbral[tabla_umbral[\"recall\"] >= 0.70].index.max()\n",
    "print(\"\\numbral elegido:\", UMBRAL)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f5c4c4e",
   "metadata": {},
   "source": [
    "Con 0.30 el modelo detecta el 74.8 % de los hits de train con precision 0.563 (410 alertas). Con 0.35 el recall\n",
    "queda justo por debajo del 70 % (0.699), y con 0.25 sube a 0.793 pero se marcan 464 canciones en lugar de 410,\n",
    "demasiadas para un equipo que solo puede promover algunas. Umbral elegido: **0.30**.\n",
    "\n",
    "La otra palanca: `scale_pos_weight` = negativos / positivos de train."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "57ea7da7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:10.683591Z",
     "iopub.status.busy": "2026-10-18T17:52:10.683591Z",
     "iopub.status.idle": "2026-10-18T17:52:10.855286Z",
     "shell.execute_reply": "2026-10-18T17:52:10.854278Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "scale_pos_weight: 2.64\n",
      "con peso y umbral 0.5 -> precision 0.556 | recall 0.751 | alertas 417 | AUC 0.856\n",
      "sin peso, AUC de las mismas predicciones CV: 0.8589\n"
     ]
    }
   ],
   "source": [
    "from sklearn.base import clone\n",
    "\n",
    "negativos, positivos = int((y_tr == 0).sum()), int((y_tr == 1).sum())\n",
    "spw = round(negativos / positivos, 2)\n",
    "con_peso = clone(mejor).set_params(xgb__scale_pos_weight=spw)\n",
    "proba_peso = cross_val_predict(con_peso, X_tr, y_tr, cv=cv, method=\"predict_proba\", n_jobs=-1)[:, 1]\n",
    "pred_peso = (proba_peso >= 0.5).astype(int)\n",
    "print(\"scale_pos_weight:\", spw)\n",
    "print(\"con peso y umbral 0.5 -> precision\", round(precision_score(y_tr, pred_peso), 3),\n",
    "      \"| recall\", round(recall_score(y_tr, pred_peso), 3), \"| alertas\", int(pred_peso.sum()),\n",
    "      \"| AUC\", round(roc_auc_score(y_tr, proba_peso), 4))\n",
    "print(\"sin peso, AUC de las mismas predicciones CV:\", round(roc_auc_score(y_tr, proba_cv), 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "063bf9f2",
   "metadata": {},
   "source": [
    "Con `scale_pos_weight` 2.64 y el umbral 0.5 se llega a un punto casi igual (precision 0.556, recall 0.751, 417\n",
    "alertas) al de umbral 0.30 sin peso, y el AUC no mejora (0.856 contra 0.8589). Las dos palancas hacen lo mismo: mover\n",
    "el punto de corte entre hits y no hits. Se elige el **umbral** y se deja `scale_pos_weight` en 1 por tres razones:\n",
    "las probabilidades siguen siendo interpretables, el umbral se puede cambiar sin reentrenar si cambia la capacidad del\n",
    "equipo editorial, y se evita el error de aplicar las dos palancas a la vez.\n",
    "\n",
    "## 7. Evaluación final, una vez\n",
    "\n",
    "Ahora sí se usa el test, una sola vez, con el modelo de la búsqueda (ya reentrenado con todo train) y el umbral\n",
    "elegido en el paso anterior."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "6235e35d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:10.859284Z",
     "iopub.status.busy": "2026-10-18T17:52:10.858286Z",
     "iopub.status.idle": "2026-10-18T17:52:10.937512Z",
     "shell.execute_reply": "2026-10-18T17:52:10.936506Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AUC test: 0.871\n",
      "umbral 0.5 : {'exactitud': 0.827, 'precision': 0.721, 'recall': 0.602, 'matriz': [[248, 24], [41, 62]]}\n",
      "umbral 0.3: {'exactitud': 0.776, 'precision': 0.568, 'recall': 0.767, 'matriz': [[212, 60], [24, 79]]}\n",
      "Dummy      : {'exactitud': 0.725, 'precision': 0.0, 'recall': 0.0, 'matriz': [[272, 0], [103, 0]]}\n"
     ]
    }
   ],
   "source": [
    "def reporte(y_real, pred):\n",
    "    return {\"exactitud\": round(accuracy_score(y_real, pred), 3),\n",
    "            \"precision\": round(precision_score(y_real, pred, zero_division=0), 3),\n",
    "            \"recall\": round(recall_score(y_real, pred), 3),\n",
    "            \"matriz\": confusion_matrix(y_real, pred).tolist()}\n",
    "\n",
    "\n",
    "proba_te = busqueda.predict_proba(X_te)[:, 1]\n",
    "print(\"AUC test:\", round(roc_auc_score(y_te, proba_te), 4))\n",
    "print(\"umbral 0.5 :\", reporte(y_te, (proba_te >= 0.5).astype(int)))\n",
    "print(f\"umbral {UMBRAL}:\", reporte(y_te, (proba_te >= UMBRAL).astype(int)))\n",
    "\n",
    "dummy = Pipeline([(\"pre\", crear_pre()), (\"modelo\", DummyClassifier())]).fit(X_tr, y_tr)\n",
    "print(\"Dummy      :\", reporte(y_te, dummy.predict(X_te)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89b80d96",
   "metadata": {},
   "source": [
    "| | AUC | exactitud | precision | recall | matriz `[[TN, FP], [FN, TP]]` |\n",
    "|---|---|---|---|---|---|\n",
    "| XGBoost, umbral 0.5 | 0.871 | 0.827 | 0.721 | 0.602 | `[[248, 24], [41, 62]]` |\n",
    "| XGBoost, umbral 0.30 | 0.871 | 0.776 | 0.568 | 0.767 | `[[212, 60], [24, 79]]` |\n",
    "| Dummy | 0.5 | 0.725 | 0 | 0 | `[[272, 0], [103, 0]]` |\n",
    "\n",
    "El Dummy acierta el 72.5 % sin detectar ni un hit: por eso la exactitud sola engaña. Con umbral 0.30 el modelo\n",
    "encuentra 79 de los 103 hits del test en lugar de 62, a cambio de 60 falsas alarmas en lugar de 24. La exactitud baja\n",
    "(0.827 → 0.776), pero eso es lo que se pidió: perder menos hits. El recall de test (0.767) queda cerca del de\n",
    "validación cruzada (0.748) y el AUC de test (0.871) cerca del de validación (0.8594): la búsqueda no se sobreajustó\n",
    "a los pliegues.\n",
    "\n",
    "## 8. Una canción nueva"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "6ce36cea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:10.941839Z",
     "iopub.status.busy": "2026-10-18T17:52:10.940832Z",
     "iopub.status.idle": "2026-10-18T17:52:10.958301Z",
     "shell.execute_reply": "2026-10-18T17:52:10.957294Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "probabilidad de Top 50: 0.951 | ¿promover con umbral 0.3 ? True\n"
     ]
    }
   ],
   "source": [
    "nueva = pd.DataFrame({\"energia\": [0.78], \"bailabilidad\": [0.84], \"acustica\": [0.10], \"tempo_bpm\": [96.0],\n",
    "                      \"duracion_seg\": [185.0], \"seguidores_miles\": [850.0], \"colaboracion\": [1], \"explicita\": [0],\n",
    "                      \"en_playlist\": [1], \"genero\": [\"reguetón\"]})\n",
    "p = busqueda.predict_proba(nueva)[0, 1]\n",
    "print(\"probabilidad de Top 50:\", round(p, 3), \"| ¿promover con umbral\", UMBRAL, \"?\", p >= UMBRAL)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8d491f7",
   "metadata": {},
   "source": [
    "Probabilidad de **0.951**: muy por encima del umbral, se promueve.\n",
    "\n",
    "## 9. Extras\n",
    "\n",
    "### 9.1 Regresión de popularidad con log10 de los seguidores\n",
    "\n",
    "Mismos datos limpios, objetivo `popularidad` y partición sin `stratify`. Los seguidores van de unos pocos miles a\n",
    "millones; con `log10`, cada paso de 10× suma lo mismo a la popularidad. El logaritmo se aplica **dentro** del\n",
    "pipeline con `FunctionTransformer`, después de imputar."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c15f2dca",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:10.961808Z",
     "iopub.status.busy": "2026-10-18T17:52:10.961808Z",
     "iopub.status.idle": "2026-10-18T17:52:11.038184Z",
     "shell.execute_reply": "2026-10-18T17:52:11.036783Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lineal con log10: MAE"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 4.69 | R2 0.716\n",
      "lineal sin log  : R2 -0.059\n",
      "DummyRegressor  : MAE 8.68\n"
     ]
    }
   ],
   "source": [
    "y_pop = limpio[\"popularidad\"]\n",
    "Xr_tr, Xr_te, yr_tr, yr_te = train_test_split(X, y_pop, test_size=0.25, random_state=42)\n",
    "\n",
    "NUM_SIN_SEG = [c for c in NUMERICAS if c != \"seguidores_miles\"]\n",
    "pre_log = ColumnTransformer([\n",
    "    (\"num\", make_pipeline(SimpleImputer(strategy=\"median\"), StandardScaler()), NUM_SIN_SEG),\n",
    "    (\"log_seg\", make_pipeline(SimpleImputer(strategy=\"median\"), FunctionTransformer(np.log10), StandardScaler()),\n",
    "     [\"seguidores_miles\"]),\n",
    "    (\"cat\", make_pipeline(SimpleImputer(strategy=\"most_frequent\"), OneHotEncoder(handle_unknown=\"ignore\")),\n",
    "     CATEGORICAS),\n",
    "])\n",
    "reg = make_pipeline(pre_log, LinearRegression()).fit(Xr_tr, yr_tr)\n",
    "pred_pop = reg.predict(Xr_te)\n",
    "dummy_r = DummyRegressor().fit(Xr_tr, yr_tr)\n",
    "crudo = make_pipeline(crear_pre(), LinearRegression()).fit(Xr_tr, yr_tr)\n",
    "\n",
    "print(\"lineal con log10: MAE\", round(mean_absolute_error(yr_te, pred_pop), 2), \"| R2\", round(r2_score(yr_te, pred_pop), 3))\n",
    "print(\"lineal sin log  : R2\", round(r2_score(yr_te, crudo.predict(Xr_te)), 3))\n",
    "print(\"DummyRegressor  : MAE\", round(mean_absolute_error(yr_te, dummy_r.predict(Xr_te)), 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "168d2e66",
   "metadata": {},
   "source": [
    "Con el logaritmo, la regresión lineal se equivoca en promedio 4.69 puntos de popularidad ($R^2$ 0.716), contra\n",
    "8.68 del Dummy. Sin el logaritmo el $R^2$ cae por debajo de cero (−0.059): los artistas gigantes descomponen la recta.\n",
    "\n",
    "### 9.2 Estilo como característica\n",
    "\n",
    "Idea: ajustar KMeans con k=4 sobre los rasgos de audio escalados y agregar el cluster (en one-hot) como columnas\n",
    "nuevas. Para que no haya fuga, KMeans va **dentro** del pipeline: en cada pliegue se ajusta solo con las canciones de\n",
    "entrenamiento. Como scikit-learn no trae un transformador que devuelva el cluster en one-hot, se escribe uno\n",
    "pequeño."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9432cba0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:11.041696Z",
     "iopub.status.busy": "2026-10-18T17:52:11.040697Z",
     "iopub.status.idle": "2026-10-18T17:52:11.937393Z",
     "shell.execute_reply": "2026-10-18T17:52:11.934881Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sin estilo  | XGBoost ajustado     | AUC CV 0.8594 (desv. 0.013)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sin estilo  | regresión logística  | AUC CV 0.8285 (desv. 0.016)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "con estilo  | XGBoost ajustado     | AUC CV 0.8596 (desv. 0.012)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "con estilo  | regresión logística  | AUC CV 0.8261 (desv. 0.015)\n"
     ]
    }
   ],
   "source": [
    "class EstiloKMeans(BaseEstimator, TransformerMixin):\n",
    "    \"\"\"Ajusta KMeans y devuelve el cluster de cada fila en one-hot (una columna por cluster).\"\"\"\n",
    "\n",
    "    def __init__(self, n_clusters=4):\n",
    "        self.n_clusters = n_clusters\n",
    "\n",
    "    def fit(self, X, y=None):\n",
    "        self.km_ = KMeans(n_clusters=self.n_clusters, n_init=10, random_state=42).fit(X)\n",
    "        return self\n",
    "\n",
    "    def transform(self, X):\n",
    "        return np.eye(self.n_clusters)[self.km_.predict(X)]\n",
    "\n",
    "\n",
    "def crear_pre_con_estilo():\n",
    "    return ColumnTransformer([\n",
    "        (\"num\", make_pipeline(SimpleImputer(strategy=\"median\"), StandardScaler()), NUMERICAS),\n",
    "        (\"cat\", make_pipeline(SimpleImputer(strategy=\"most_frequent\"), OneHotEncoder(handle_unknown=\"ignore\")),\n",
    "         CATEGORICAS),\n",
    "        (\"estilo\", make_pipeline(SimpleImputer(strategy=\"median\"), StandardScaler(), EstiloKMeans(4)), AUDIO),\n",
    "    ])\n",
    "\n",
    "\n",
    "xgb_params = {k.removeprefix(\"xgb__\"): v for k, v in busqueda.best_params_.items()}\n",
    "for nombre, pre in [(\"sin estilo\", crear_pre), (\"con estilo\", crear_pre_con_estilo)]:\n",
    "    for etiqueta, modelo in [(\"XGBoost ajustado\", XGBClassifier(random_state=42, n_jobs=1, **xgb_params)),\n",
    "                             (\"regresión logística\", LogisticRegression(max_iter=2000))]:\n",
    "        auc = cross_val_score(Pipeline([(\"pre\", pre()), (\"modelo\", modelo)]), X_tr, y_tr, cv=cv,\n",
    "                              scoring=\"roc_auc\", n_jobs=-1)\n",
    "        print(f\"{nombre:11s} | {etiqueta:20s} | AUC CV {auc.mean():.4f} (desv. {auc.std():.3f})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb37d5dc",
   "metadata": {},
   "source": [
    "El estilo **no mejora** el modelo: con XGBoost ajustado el AUC de validación pasa de 0.8594 a 0.8596, y con la\n",
    "logística baja de 0.8285 a 0.8261. Las diferencias son mucho menores que la desviación entre pliegues, así que lo\n",
    "honesto es decir que la columna no aporta. Tiene sentido: el cluster resume las mismas 5 columnas de audio que el\n",
    "modelo ya recibe, y los árboles pueden cortarlas directamente.\n",
    "\n",
    "### 9.3 Importancia por permutación\n",
    "\n",
    "Sobre test y con `scoring=\"roc_auc\"`: cuánto baja el AUC cuando se revuelve cada columna."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "32c24dd5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-18T17:52:11.940393Z",
     "iopub.status.busy": "2026-10-18T17:52:11.940393Z",
     "iopub.status.idle": "2026-10-18T17:52:12.261633Z",
     "shell.execute_reply": "2026-10-18T17:52:12.260503Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "duracion_seg        0.0860\n",
      "en_playlist         0.0698\n",
      "colaboracion        0.0382\n",
      "seguidores_miles    0.0361\n",
      "energia             0.0304\n",
      "bailabilidad        0.0177\n",
      "genero              0.0071\n",
      "tempo_bpm           0.0043\n",
      "acustica            0.0016\n",
      "explicita           0.0007\n"
     ]
    }
   ],
   "source": [
    "imp = permutation_importance(busqueda.best_estimator_, X_te, y_te, scoring=\"roc_auc\", n_repeats=10,\n",
    "                             random_state=42, n_jobs=-1)\n",
    "importancias = pd.Series(imp.importances_mean, index=X_te.columns).sort_values(ascending=False)\n",
    "print(importancias.round(4).to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "235176da",
   "metadata": {},
   "source": [
    "Pesan más la duración (el AUC baja 0.086 al revolverla) y estar en una playlist editorial (0.070); después vienen\n",
    "colaboración (0.038), seguidores (0.036) y energía (0.030). La acústica y `explicita` quedan en casi cero: la\n",
    "información de la acústica ya está en la energía, con la que tiene una correlación de −0.833. Recuerda que la\n",
    "importancia por permutación dice qué usa **este** modelo, no qué causa que una canción sea un hit."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ec12a21",
   "metadata": {},
   "source": [
    "## Borrador del informe\n",
    "\n",
    "- **Comparación (AUC CV en train):** Dummy 0.5, logística 0.828, SVC 0.825, Random Forest 0.851, gradient boosting\n",
    "  0.848, XGBoost sin ajustar 0.841.\n",
    "- **XGBoost:** early stopping con validación separada de train: `best_iteration` 97 con `learning_rate` 0.05.\n",
    "  `RandomizedSearchCV`, 30 combinaciones y 150 ajustes: `learning_rate` 0.0336, 332 árboles, `max_depth` 2,\n",
    "  `subsample` 0.927, `colsample_bytree` 0.649, `reg_lambda` 0.715; `best_score_` 0.8594.\n",
    "- **Umbral:** 0.30, el más alto con recall de al menos 70 % en validación cruzada (precision 0.563, recall 0.748).\n",
    "  `scale_pos_weight` 2.64 daba un punto equivalente (0.556 / 0.751); se prefirió el umbral porque se ajusta sin\n",
    "  reentrenar y mantiene las probabilidades interpretables.\n",
    "- **Test:** AUC 0.871. Con 0.30: exactitud 0.776, precision 0.568, recall 0.767 (79 de 103 hits, 60 falsas\n",
    "  alarmas). Con 0.5: 0.827, 0.721 y 0.602. Dummy: 0.725 sin detectar ningún hit.\n",
    "- **Canción nueva:** probabilidad 0.951, se promueve.\n",
    "- **Limitaciones:**\n",
    "  1. Los datos son sintéticos: las cifras muestran el método, no cómo se comportan las canciones reales.\n",
    "  2. El test tiene solo 103 hits; con otra partición las métricas pueden moverse varias centésimas.\n",
    "  3. El umbral depende de cuántas canciones puede promover el equipo; si cambia esa capacidad, hay que volver a\n",
    "     elegirlo con validación cruzada.\n",
    "\n",
    "## Resumen\n",
    "\n",
    "- `limpiar` deja 1500 canciones, 412 hits y 5 géneros; los faltantes se imputan dentro del pipeline.\n",
    "- `reproducciones_mes1` y `popularidad` quedan fuera: se conocen después del lanzamiento.\n",
    "- Los ensambles ganan la comparación; la búsqueda aleatoria sube XGBoost de 0.841 a 0.8594.\n",
    "- El umbral 0.30 se elige con `cross_val_predict` en train y sube el recall de test de 0.602 a 0.767.\n",
    "- El test se usó una sola vez: AUC 0.871.\n",
    "- Extras: la regresión con log10 logra MAE 4.69 y $R^2$ 0.716; el estilo de KMeans como característica no mejora el\n",
    "  AUC (0.8596 contra 0.8594)."
   ]
  }
 ],
 "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.12.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
