{"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":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30664,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import 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 TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\n\nimport joblib\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-18T01:00:10.851718Z","iopub.execute_input":"2024-03-18T01:00:10.852177Z","iopub.status.idle":"2024-03-18T01:00:16.067034Z","shell.execute_reply.started":"2024-03-18T01:00:10.852131Z","shell.execute_reply":"2024-03-18T01:00:16.065580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.Int64))\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.Float64))\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                \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:\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):\n                    df = df.drop(col)\n\n        return df","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:00:16.071221Z","iopub.execute_input":"2024-03-18T01:00:16.072417Z","iopub.status.idle":"2024-03-18T01:00:16.089096Z","shell.execute_reply.started":"2024-03-18T01:00:16.072356Z","shell.execute_reply":"2024-03-18T01:00:16.087510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-18T01:00:16.090902Z","iopub.execute_input":"2024-03-18T01:00:16.091388Z","iopub.status.idle":"2024-03-18T01:00:16.106169Z","shell.execute_reply.started":"2024-03-18T01:00:16.091312Z","shell.execute_reply":"2024-03-18T01:00:16.104635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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        chunks.append(pl.read_parquet(path).pipe(Pipeline.set_table_dtypes))\n        \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:00:16.109038Z","iopub.execute_input":"2024-03-18T01:00:16.109538Z","iopub.status.idle":"2024-03-18T01:00:16.121693Z","shell.execute_reply.started":"2024-03-18T01:00:16.109497Z","shell.execute_reply":"2024-03-18T01:00:16.120297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Time to visualize DATA","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-18T01:00:16.123366Z","iopub.execute_input":"2024-03-18T01:00:16.123786Z","iopub.status.idle":"2024-03-18T01:00:16.133989Z","shell.execute_reply.started":"2024-03-18T01:00:16.123749Z","shell.execute_reply":"2024-03-18T01:00:16.132549Z"},"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-18T01:00:16.135665Z","iopub.execute_input":"2024-03-18T01:00:16.136039Z","iopub.status.idle":"2024-03-18T01:00:16.151007Z","shell.execute_reply.started":"2024-03-18T01:00:16.136007Z","shell.execute_reply":"2024-03-18T01:00:16.149946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Ahora fusionaremos los archivos:\n\n- Archivos de entrenamiento (profundidad 0): \"train_static_0_0.csv\", \"train_static_0_1.csv\", train_static_cb_0.csv\"\n- Archivos de prueba (profundidad 0): \"test_static_0_0.csv\", \"test_static_0_1.csv\", \"test_static_0_2.csv\",   \"test_static_cb_0.csv\"","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\"","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:00:16.152266Z","iopub.execute_input":"2024-03-18T01:00:16.153126Z","iopub.status.idle":"2024-03-18T01:00:16.162890Z","shell.execute_reply.started":"2024-03-18T01:00:16.153086Z","shell.execute_reply":"2024-03-18T01:00:16.161726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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_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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:00:16.164069Z","iopub.execute_input":"2024-03-18T01:00:16.164573Z","iopub.status.idle":"2024-03-18T01:00:58.135246Z","shell.execute_reply.started":"2024-03-18T01:00:16.164535Z","shell.execute_reply":"2024-03-18T01:00:58.133363Z"},"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-18T01:00:58.137036Z","iopub.execute_input":"2024-03-18T01:00:58.137466Z","iopub.status.idle":"2024-03-18T01:01:06.902506Z","shell.execute_reply.started":"2024-03-18T01:00:58.137431Z","shell.execute_reply":"2024-03-18T01:01:06.901093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:01:06.906569Z","iopub.execute_input":"2024-03-18T01:01:06.907003Z","iopub.status.idle":"2024-03-18T01:01:07.508127Z","shell.execute_reply.started":"2024-03-18T01:01:06.906969Z","shell.execute_reply":"2024-03-18T01:01:07.506526Z"},"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-18T01:01:07.509991Z","iopub.execute_input":"2024-03-18T01:01:07.510557Z","iopub.status.idle":"2024-03-18T01:01:07.557710Z","shell.execute_reply.started":"2024-03-18T01:01:07.510507Z","shell.execute_reply":"2024-03-18T01:01:07.556699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-18T01:01:07.558973Z","iopub.execute_input":"2024-03-18T01:01:07.559705Z","iopub.status.idle":"2024-03-18T01:01:10.435560Z","shell.execute_reply.started":"2024-03-18T01:01:07.559663Z","shell.execute_reply":"2024-03-18T01:01:10.434271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-18T01:01:10.436959Z","iopub.execute_input":"2024-03-18T01:01:10.437605Z","iopub.status.idle":"2024-03-18T01:01:28.430738Z","shell.execute_reply.started":"2024-03-18T01:01:10.437565Z","shell.execute_reply":"2024-03-18T01:01:28.429535Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:01:28.432116Z","iopub.execute_input":"2024-03-18T01:01:28.432593Z","iopub.status.idle":"2024-03-18T01:01:28.566063Z","shell.execute_reply.started":"2024-03-18T01:01:28.432558Z","shell.execute_reply":"2024-03-18T01:01:28.564737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-18T01:01:28.567468Z","iopub.execute_input":"2024-03-18T01:01:28.567827Z","iopub.status.idle":"2024-03-18T01:01:28.639962Z","shell.execute_reply.started":"2024-03-18T01:01:28.567798Z","shell.execute_reply":"2024-03-18T01:01:28.638526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Null / Missing / Duplicate values**","metadata":{}},{"cell_type":"code","source":"df_train.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:02:08.278979Z","iopub.execute_input":"2024-03-18T01:02:08.279788Z","iopub.status.idle":"2024-03-18T01:02:08.989494Z","shell.execute_reply.started":"2024-03-18T01:02:08.279742Z","shell.execute_reply":"2024-03-18T01:02:08.988263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(df_train.shape)\nprint(df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:18:30.108226Z","iopub.execute_input":"2024-03-18T01:18:30.108712Z","iopub.status.idle":"2024-03-18T01:18:30.115363Z","shell.execute_reply.started":"2024-03-18T01:18:30.108673Z","shell.execute_reply":"2024-03-18T01:18:30.113925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Remove Columns > 0.8 nulls\n\ndef removeCols(dframe_train, dframe_test):\n    lsColumnRemove = []\n    for col in df_train.columns:\n        if col not in [\"target\",\"case_id\",\"WEEK_NUM\"]:\n            countNulls = df_train[col].isnull().mean()\n            if countNulls > 0.8:\n                lsColumnRemove.append(col)\n    return lsColumnRemove","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:36:43.855918Z","iopub.execute_input":"2024-03-18T01:36:43.856415Z","iopub.status.idle":"2024-03-18T01:36:43.864613Z","shell.execute_reply.started":"2024-03-18T01:36:43.856374Z","shell.execute_reply":"2024-03-18T01:36:43.862993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rmvCols = removeCols(df_train, df_test)\nfor col in rmvCols:\n    df_train = df_train.drop(col, axis = 1)\n    df_test = df_test.drop(col, axis = 1)\n    \nprint(df_train.shape)\nprint(df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:36:45.368932Z","iopub.execute_input":"2024-03-18T01:36:45.369449Z","iopub.status.idle":"2024-03-18T01:36:45.942497Z","shell.execute_reply.started":"2024-03-18T01:36:45.369407Z","shell.execute_reply":"2024-03-18T01:36:45.941084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[\"birthdate_574D\"].dtype","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:36:47.063928Z","iopub.execute_input":"2024-03-18T01:36:47.064443Z","iopub.status.idle":"2024-03-18T01:36:47.073591Z","shell.execute_reply.started":"2024-03-18T01:36:47.064406Z","shell.execute_reply":"2024-03-18T01:36:47.071923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:36:48.410267Z","iopub.execute_input":"2024-03-18T01:36:48.410748Z","iopub.status.idle":"2024-03-18T01:36:48.444406Z","shell.execute_reply.started":"2024-03-18T01:36:48.410714Z","shell.execute_reply":"2024-03-18T01:36:48.442998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['birthdate_574D'].isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:36:50.101855Z","iopub.execute_input":"2024-03-18T01:36:50.102431Z","iopub.status.idle":"2024-03-18T01:36:50.113910Z","shell.execute_reply.started":"2024-03-18T01:36:50.102390Z","shell.execute_reply":"2024-03-18T01:36:50.112485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-03-18T01:36:23.386402Z","iopub.execute_input":"2024-03-18T01:36:23.386909Z","iopub.status.idle":"2024-03-18T01:36:24.110831Z","shell.execute_reply.started":"2024-03-18T01:36:23.386870Z","shell.execute_reply":"2024-03-18T01:36:24.109078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}