{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30648,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Forked from https://www.kaggle.com/code/greysky/home-credit-baseline","metadata":{}},{"cell_type":"markdown","source":"### Шапка\n\n**ФИО:** Енцов Семен Евгеньевич\n\n**Базовый кёрнел:** https://www.kaggle.com/code/greysky/home-credit-baseline\n\n- Качество базового кёрнела: 0.563 (близко к топу: у первого места 0.596)\n- Качество моего (этого) кёрнела: 0.566 (+ 0.003 :D)\n\n**Улучшения:**\n* Оптимизировал параметры библиотекой hyperopt. Но оптимизация приводила к ухудшению результата (см. старые Submissions), поэтому в конечном кёрнеле я её отключил. Видимо, в базовом кёрнеле параметры уже хорошо оптимизированы. Код оптимизации я оставил в notebook'е.\n* Для признаков \"количество чего-то\" добавил столбцы с их логарифмами.\n* Использовал float32 вместо float64 в данных, чтобы уложиться в лимит по памяти.\n\n**Как ещё улучшить кёрнел?**\n* Провести полноценный EDA, поискать закономерности между признаками, обновить тренировочные данные, пользуясь наблюдениями.\n* Как-то исползовать особенность scoring-функции. Возможно, сменить функцию потерь, чтобы она лучше отражала цель соревнования.\n* Поэкспериментировать с типами модели, попробовать нетривиальные архитектуры нейронной сети.\n* Оптимизировать гиперпараметры, используя ансамбль классификаторов. Сейчас я оптимизирую параметры для одного классификатора.\n\nБольшая часть кода осталась неизменной после форка notebook'а. Существенные изменения в следующих разделах:\n\n- Pipeline (добавил метод `add_cols`)\n- Часть 1. Добавляем признаки\n- Часть 2. Оптимизируем гиперпараметры\n","metadata":{}},{"cell_type":"code","source":"SUBMIT = True\n\nimport os\nimport gc\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\nimport lightgbm as lgb\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-25T14:17:38.211507Z","iopub.execute_input":"2024-03-25T14:17:38.211813Z","iopub.status.idle":"2024-03-25T14:17:41.425680Z","shell.execute_reply.started":"2024-03-25T14:17:38.211788Z","shell.execute_reply":"2024-03-25T14:17:41.424587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pre-Fitted Voting Model","metadata":{}},{"cell_type":"code","source":"class VotingModel(BaseEstimator, ClassifierMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.431107Z","iopub.execute_input":"2024-03-25T14:17:41.431502Z","iopub.status.idle":"2024-03-25T14:17:41.439145Z","shell.execute_reply.started":"2024-03-25T14:17:41.431468Z","shell.execute_reply":"2024-03-25T14:17:41.438241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pipeline","metadata":{}},{"cell_type":"code","source":"class Pipeline:\n    @staticmethod\n    def set_table_dtypes(df):\n        for col in df.columns:\n            if col in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Int32))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col[-1] in (\"P\", \"A\"):\n                df = df.with_columns(pl.col(col).cast(pl.Float32))\n            elif col[-1] in (\"M\",):\n                df = df.with_columns(pl.col(col).cast(pl.String))\n            elif col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col).cast(pl.Date))            \n\n        return df\n    \n    @staticmethod\n    def handle_dates(df):\n        for col in df.columns:\n            if col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col) - pl.col(\"date_decision\"))\n                df = df.with_columns(pl.col(col).dt.total_days())\n                df = df.with_columns(pl.col(col).cast(pl.Float32))\n                \n        df = df.drop(\"date_decision\", \"MONTH\")\n\n        return df\n    \n    @staticmethod\n    def filter_cols(df):\n        for col in df.columns:\n            if col not in [\"target\", \"case_id\", \"WEEK_NUM\"]:\n                isnull = df[col].is_null().mean()\n\n                if isnull > 0.95:  # 0.95 -> 0.8\n                    df = df.drop(col)\n\n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) & (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n\n                if (freq == 1) | (freq > 200):  # 200 -> 100\n                    df = df.drop(col)\n\n        return df\n    \n    @staticmethod\n    def add_cols(df):\n        for col in df.columns:\n            if col not in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"] and col[-1] in (\"A\",):\n                df = df.with_columns(pl.col(col).map(np.log).alias(col + \"_log\"))\n\n        return df","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.440598Z","iopub.execute_input":"2024-03-25T14:17:41.441029Z","iopub.status.idle":"2024-03-25T14:17:41.457426Z","shell.execute_reply.started":"2024-03-25T14:17:41.440998Z","shell.execute_reply":"2024-03-25T14:17:41.456477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Automatic Aggregation","metadata":{}},{"cell_type":"code","source":"class Aggregator:\n    @staticmethod\n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\",)]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n    \n    @staticmethod\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.459979Z","iopub.execute_input":"2024-03-25T14:17:41.460305Z","iopub.status.idle":"2024-03-25T14:17:41.473525Z","shell.execute_reply.started":"2024-03-25T14:17:41.460268Z","shell.execute_reply":"2024-03-25T14:17:41.472636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### File I/O","metadata":{}},{"cell_type":"code","source":"def read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    \n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    \n    return df\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.set_table_dtypes)\n        \n        if depth in [1, 2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        \n        chunks.append(df)\n        \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.474817Z","iopub.execute_input":"2024-03-25T14:17:41.475149Z","iopub.status.idle":"2024-03-25T14:17:41.486916Z","shell.execute_reply.started":"2024-03-25T14:17:41.475118Z","shell.execute_reply":"2024-03-25T14:17:41.486118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Engineering","metadata":{}},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n        \n    for i, df in enumerate(depth_0 + depth_1 + depth_2):\n        df_base = df_base.join(df, how=\"left\", on=\"case_id\", suffix=f\"_{i}\")\n        \n    df_base = df_base.pipe(Pipeline.handle_dates)\n    \n    return df_base","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.488045Z","iopub.execute_input":"2024-03-25T14:17:41.488420Z","iopub.status.idle":"2024-03-25T14:17:41.498398Z","shell.execute_reply.started":"2024-03-25T14:17:41.488398Z","shell.execute_reply":"2024-03-25T14:17:41.497479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    \n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    \n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    \n    return df_data, cat_cols","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.499525Z","iopub.execute_input":"2024-03-25T14:17:41.499845Z","iopub.status.idle":"2024-03-25T14:17:41.513525Z","shell.execute_reply.started":"2024-03-25T14:17:41.499822Z","shell.execute_reply":"2024-03-25T14:17:41.512534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Configuration","metadata":{}},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\nif not SUBMIT:\n    TEST_DIR    = ROOT / \"parquet_files\" / \"train\"","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.515084Z","iopub.execute_input":"2024-03-25T14:17:41.515447Z","iopub.status.idle":"2024-03-25T14:17:41.525023Z","shell.execute_reply.started":"2024-03-25T14:17:41.515417Z","shell.execute_reply":"2024-03-25T14:17:41.524260Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train Files Read & Feature Engineering","metadata":{}},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_2_*.parquet\", 2),\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:17:41.526448Z","iopub.execute_input":"2024-03-25T14:17:41.526771Z","iopub.status.idle":"2024-03-25T14:19:51.183621Z","shell.execute_reply.started":"2024-03-25T14:17:41.526741Z","shell.execute_reply":"2024-03-25T14:19:51.182744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\n\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:19:51.184960Z","iopub.execute_input":"2024-03-25T14:19:51.185434Z","iopub.status.idle":"2024-03-25T14:20:04.417861Z","shell.execute_reply.started":"2024-03-25T14:19:51.185400Z","shell.execute_reply":"2024-03-25T14:20:04.416825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Test Files Read & Feature Engineering","metadata":{}},{"cell_type":"code","source":"def test_path(s):\n    if not SUBMIT:\n        s = \"train\" + s[len(\"test\"):]\n    return s\n\ndata_store = {\n    \"df_base\": read_file(TEST_DIR / test_path(\"test_base.parquet\")),\n    \"depth_0\": [\n        read_file(TEST_DIR / test_path(\"test_static_cb_0.parquet\")),\n        read_files(TEST_DIR / test_path(\"test_static_0_*.parquet\")),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / test_path(\"test_applprev_1_*.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_tax_registry_a_1.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_tax_registry_b_1.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_tax_registry_c_1.parquet\"), 1),\n        read_files(TEST_DIR / test_path(\"test_credit_bureau_a_1_*.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_credit_bureau_b_1.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_other_1.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_person_1.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_deposit_1.parquet\"), 1),\n        read_file(TEST_DIR / test_path(\"test_debitcard_1.parquet\"), 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / test_path(\"test_credit_bureau_b_2.parquet\"), 2),\n        read_files(TEST_DIR / test_path(\"test_credit_bureau_a_2_*.parquet\"), 2),\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:04.419027Z","iopub.execute_input":"2024-03-25T14:20:04.419344Z","iopub.status.idle":"2024-03-25T14:20:05.071060Z","shell.execute_reply.started":"2024-03-25T14:20:04.419318Z","shell.execute_reply":"2024-03-25T14:20:05.070241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\n\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:05.072321Z","iopub.execute_input":"2024-03-25T14:20:05.072705Z","iopub.status.idle":"2024-03-25T14:20:05.116213Z","shell.execute_reply.started":"2024-03-25T14:20:05.072670Z","shell.execute_reply":"2024-03-25T14:20:05.115299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Elimination","metadata":{}},{"cell_type":"code","source":"df_train = df_train.pipe(Pipeline.filter_cols)\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:05.120135Z","iopub.execute_input":"2024-03-25T14:20:05.120440Z","iopub.status.idle":"2024-03-25T14:20:07.955607Z","shell.execute_reply.started":"2024-03-25T14:20:05.120415Z","shell.execute_reply":"2024-03-25T14:20:07.954459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Часть 1. Добавляем признаки","metadata":{}},{"cell_type":"code","source":"df_train = df_train.pipe(Pipeline.add_cols)\ndf_test = df_test.pipe(Pipeline.add_cols)","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:07.956779Z","iopub.execute_input":"2024-03-25T14:20:07.957054Z","iopub.status.idle":"2024-03-25T14:20:11.562989Z","shell.execute_reply.started":"2024-03-25T14:20:07.957031Z","shell.execute_reply":"2024-03-25T14:20:11.561585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pandas Conversion","metadata":{}},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:11.564770Z","iopub.execute_input":"2024-03-25T14:20:11.565046Z","iopub.status.idle":"2024-03-25T14:20:30.967481Z","shell.execute_reply.started":"2024-03-25T14:20:11.565022Z","shell.execute_reply":"2024-03-25T14:20:30.966648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Garbage Collection","metadata":{}},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:30.968687Z","iopub.execute_input":"2024-03-25T14:20:30.968999Z","iopub.status.idle":"2024-03-25T14:20:31.105519Z","shell.execute_reply.started":"2024-03-25T14:20:30.968973Z","shell.execute_reply":"2024-03-25T14:20:31.104582Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### EDA","metadata":{}},{"cell_type":"code","source":"print(\"Train is duplicated:\\t\", df_train[\"case_id\"].duplicated().any())\nprint(\"Train Week Range:\\t\", (df_train[\"WEEK_NUM\"].min(), df_train[\"WEEK_NUM\"].max()))\n\nprint()\n\nprint(\"Test is duplicated:\\t\", df_test[\"case_id\"].duplicated().any())\nprint(\"Test Week Range:\\t\", (df_test[\"WEEK_NUM\"].min(), df_test[\"WEEK_NUM\"].max()))","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:31.106633Z","iopub.execute_input":"2024-03-25T14:20:31.106910Z","iopub.status.idle":"2024-03-25T14:20:31.139610Z","shell.execute_reply.started":"2024-03-25T14:20:31.106876Z","shell.execute_reply":"2024-03-25T14:20:31.138730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.lineplot(\n    data=df_train,\n    x=\"WEEK_NUM\",\n    y=\"target\",\n)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:31.140585Z","iopub.execute_input":"2024-03-25T14:20:31.140840Z","iopub.status.idle":"2024-03-25T14:20:48.443573Z","shell.execute_reply.started":"2024-03-25T14:20:31.140818Z","shell.execute_reply":"2024-03-25T14:20:48.442705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Часть 2. Подбираем гиперпараметры","metadata":{}},{"cell_type":"code","source":"import lightgbm as lgb\nimport numpy as np\nfrom hyperopt import hp, tpe, Trials, fmin\nfrom copy import copy\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, auc","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:48.444614Z","iopub.execute_input":"2024-03-25T14:20:48.444895Z","iopub.status.idle":"2024-03-25T14:20:49.084981Z","shell.execute_reply.started":"2024-03-25T14:20:48.444870Z","shell.execute_reply":"2024-03-25T14:20:49.084194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.05,\n    \"n_estimators\": 1000,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"device\": \"gpu\",\n}\n\n# Run optimization in a loop to retry when encountering non-deterministic errors\n# caused by 2 different bugs in hyperopt >:(\nis_done = False\nwhile False:\n    try:\n        X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n        y = df_train[\"target\"]\n        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)\n        X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.1)\n\n        def objective(params):\n            model = lgb.LGBMClassifier(**params)\n            model.fit(\n                X_train, y_train,\n                eval_set=[(X_valid, y_valid)],\n                callbacks=[lgb.log_evaluation(100), lgb.early_stopping(100)],\n            )\n\n            y_pred = model.predict_proba(X_test)[:,-1]\n            # TODO: consider using gini_stability score\n            auc = roc_auc_score(list(y_test), list(y_pred))\n            return -auc\n\n        space = {\n            \"boosting_type\": \"gbdt\",\n            \"objective\": \"binary\",\n            \"metric\": \"auc\",\n            \"max_depth\": hp.uniformint(\"max_depth\", 3, 10),\n            \"learning_rate\": hp.uniform(\"learning_rate\", 0.1, 2),\n            \"n_estimators\": 1000,\n            \"colsample_bytree\": hp.uniform(\"colsample_bytree\", 0.4, 1),\n            \"colsample_bynode\": hp.uniform(\"colsample_bynode\", 0.4, 1),\n            \"verbose\": -1,\n            \"random_state\": 42,\n            \"device\": \"gpu\",\n            \"max_bins\": 63,\n        }\n\n        trials = Trials()\n        best = fmin(\n            fn=objective,\n            space=space,\n            algo=tpe.suggest,\n            max_evals=10,\n            trials=trials,\n            rstate=np.random.default_rng(45),\n        )\n        is_done = True\n    except lgb.basic.LightGBMError as e:\n        gc.collect()\n        print(f\"Stopped with exception: {e}\")\n        print(\"Restarting...\")","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:49.086319Z","iopub.execute_input":"2024-03-25T14:20:49.086951Z","iopub.status.idle":"2024-03-25T14:20:49.099681Z","shell.execute_reply.started":"2024-03-25T14:20:49.086915Z","shell.execute_reply":"2024-03-25T14:20:49.098705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": None,\n    \"learning_rate\": None,\n    \"n_estimators\": 1000,\n    \"colsample_bytree\": None,\n    \"colsample_bynode\": None,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"device\": \"gpu\",\n    \"max_bins\": 63,\n}\nparams.update(best)\nparams[\"max_depth\"] = int(params[\"max_depth\"])\n# params[\"n_estimators\"] = int(params[\"n_estimators\"])","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:49.100728Z","iopub.execute_input":"2024-03-25T14:20:49.100967Z","iopub.status.idle":"2024-03-25T14:20:49.116424Z","shell.execute_reply.started":"2024-03-25T14:20:49.100946Z","shell.execute_reply":"2024-03-25T14:20:49.115493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:49.117414Z","iopub.execute_input":"2024-03-25T14:20:49.117647Z","iopub.status.idle":"2024-03-25T14:20:49.132613Z","shell.execute_reply.started":"2024-03-25T14:20:49.117628Z","shell.execute_reply":"2024-03-25T14:20:49.131680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:49.134070Z","iopub.execute_input":"2024-03-25T14:20:49.134417Z","iopub.status.idle":"2024-03-25T14:20:49.267271Z","shell.execute_reply.started":"2024-03-25T14:20:49.134394Z","shell.execute_reply":"2024-03-25T14:20:49.266167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"cell_type":"code","source":"model = None\n\nis_done = False\nwhile not is_done:\n    try:\n        X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n        y = df_train[\"target\"]\n        weeks = df_train[\"WEEK_NUM\"]\n\n        cv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\n        fitted_models = []\n\n        for idx_train, idx_valid in cv.split(X, y, groups=weeks):\n            X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n            X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n            model = lgb.LGBMClassifier(**params)\n            model.fit(\n                X_train, y_train,\n                eval_set=[(X_valid, y_valid)],\n                callbacks=[lgb.log_evaluation(100), lgb.early_stopping(100)]\n            )\n\n            fitted_models.append(model)\n\n        model = VotingModel(fitted_models)\n        is_done = True\n    except lgb.basic.LightGBMError as e:\n        gc.collect()\n        print(f\"Stopped with exception: {e}\")\n        print(\"Restarting...\")","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:20:49.268509Z","iopub.execute_input":"2024-03-25T14:20:49.268813Z","iopub.status.idle":"2024-03-25T14:39:30.758263Z","shell.execute_reply.started":"2024-03-25T14:20:49.268785Z","shell.execute_reply":"2024-03-25T14:39:30.757154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:39:30.759992Z","iopub.execute_input":"2024-03-25T14:39:30.760314Z","iopub.status.idle":"2024-03-25T14:39:30.905042Z","shell.execute_reply.started":"2024-03-25T14:39:30.760289Z","shell.execute_reply":"2024-03-25T14:39:30.903949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction","metadata":{}},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\n\ny_pred = pd.Series(model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:39:30.906662Z","iopub.execute_input":"2024-03-25T14:39:30.907087Z","iopub.status.idle":"2024-03-25T14:39:31.207293Z","shell.execute_reply.started":"2024-03-25T14:39:30.907053Z","shell.execute_reply":"2024-03-25T14:39:31.206159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submission","metadata":{}},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:39:31.211023Z","iopub.execute_input":"2024-03-25T14:39:31.211357Z","iopub.status.idle":"2024-03-25T14:39:31.236135Z","shell.execute_reply.started":"2024-03-25T14:39:31.211331Z","shell.execute_reply":"2024-03-25T14:39:31.235340Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Check null: \", df_subm[\"score\"].isnull().any())\n\ndf_subm.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:39:31.237313Z","iopub.execute_input":"2024-03-25T14:39:31.237615Z","iopub.status.idle":"2024-03-25T14:39:31.252453Z","shell.execute_reply.started":"2024-03-25T14:39:31.237590Z","shell.execute_reply":"2024-03-25T14:39:31.251365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-25T14:39:31.254068Z","iopub.execute_input":"2024-03-25T14:39:31.254405Z","iopub.status.idle":"2024-03-25T14:39:31.261073Z","shell.execute_reply.started":"2024-03-25T14:39:31.254378Z","shell.execute_reply":"2024-03-25T14:39:31.260212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}