{"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":7602123,"sourceType":"competition"},{"sourceId":7584174,"sourceType":"datasetVersion","datasetId":4414761}],"dockerImageVersionId":30648,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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 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-02-24T21:47:50.888662Z","iopub.execute_input":"2024-02-24T21:47:50.888987Z","iopub.status.idle":"2024-02-24T21:47:57.170036Z","shell.execute_reply.started":"2024-02-24T21:47:50.888953Z","shell.execute_reply":"2024-02-24T21:47:57.169231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pre-Fitted Voting Model","metadata":{}},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\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-02-24T21:47:57.171464Z","iopub.execute_input":"2024-02-24T21:47:57.171776Z","iopub.status.idle":"2024-02-24T21:47:57.178359Z","shell.execute_reply.started":"2024-02-24T21:47:57.171751Z","shell.execute_reply":"2024-02-24T21:47:57.177505Z"},"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.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-02-24T21:47:57.179310Z","iopub.execute_input":"2024-02-24T21:47:57.179553Z","iopub.status.idle":"2024-02-24T21:47:57.215640Z","shell.execute_reply.started":"2024-02-24T21:47:57.179531Z","shell.execute_reply":"2024-02-24T21:47:57.214588Z"},"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-02-24T21:47:57.217548Z","iopub.execute_input":"2024-02-24T21:47:57.217825Z","iopub.status.idle":"2024-02-24T21:47:57.230632Z","shell.execute_reply.started":"2024-02-24T21:47:57.217802Z","shell.execute_reply":"2024-02-24T21:47:57.229877Z"},"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        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-02-24T21:47:57.231606Z","iopub.execute_input":"2024-02-24T21:47:57.231879Z","iopub.status.idle":"2024-02-24T21:47:57.244258Z","shell.execute_reply.started":"2024-02-24T21:47:57.231857Z","shell.execute_reply":"2024-02-24T21:47:57.243334Z"},"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-02-24T21:47:57.245309Z","iopub.execute_input":"2024-02-24T21:47:57.245565Z","iopub.status.idle":"2024-02-24T21:47:57.254646Z","shell.execute_reply.started":"2024-02-24T21:47:57.245543Z","shell.execute_reply":"2024-02-24T21:47:57.253777Z"},"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-02-24T21:47:57.255513Z","iopub.execute_input":"2024-02-24T21:47:57.255754Z","iopub.status.idle":"2024-02-24T21:47:57.268700Z","shell.execute_reply.started":"2024-02-24T21:47:57.255733Z","shell.execute_reply":"2024-02-24T21:47:57.267893Z"},"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\"","metadata":{"execution":{"iopub.status.busy":"2024-02-24T21:47:57.269664Z","iopub.execute_input":"2024-02-24T21:47:57.269962Z","iopub.status.idle":"2024-02-24T21:47:57.279077Z","shell.execute_reply.started":"2024-02-24T21:47:57.269939Z","shell.execute_reply":"2024-02-24T21:47:57.278379Z"},"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_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-02-24T21:47:57.280032Z","iopub.execute_input":"2024-02-24T21:47:57.280279Z","iopub.status.idle":"2024-02-24T21:48:25.567392Z","shell.execute_reply.started":"2024-02-24T21:47:57.280257Z","shell.execute_reply":"2024-02-24T21:48:25.566593Z"},"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-02-24T21:48:25.570448Z","iopub.execute_input":"2024-02-24T21:48:25.570758Z","iopub.status.idle":"2024-02-24T21:48:32.350646Z","shell.execute_reply.started":"2024-02-24T21:48:25.570733Z","shell.execute_reply":"2024-02-24T21:48:32.349652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Test Files Read & Feature Engineering","metadata":{}},{"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-02-24T21:48:32.351734Z","iopub.execute_input":"2024-02-24T21:48:32.352021Z","iopub.status.idle":"2024-02-24T21:48:32.734177Z","shell.execute_reply.started":"2024-02-24T21:48:32.351994Z","shell.execute_reply":"2024-02-24T21:48:32.733150Z"},"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-02-24T21:48:32.735398Z","iopub.execute_input":"2024-02-24T21:48:32.735725Z","iopub.status.idle":"2024-02-24T21:48:32.763968Z","shell.execute_reply.started":"2024-02-24T21:48:32.735692Z","shell.execute_reply":"2024-02-24T21:48:32.763102Z"},"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-02-24T21:48:32.764954Z","iopub.execute_input":"2024-02-24T21:48:32.765202Z","iopub.status.idle":"2024-02-24T21:48:34.879253Z","shell.execute_reply.started":"2024-02-24T21:48:32.765180Z","shell.execute_reply":"2024-02-24T21:48:34.878204Z"},"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-02-24T21:48:34.880379Z","iopub.execute_input":"2024-02-24T21:48:34.880719Z","iopub.status.idle":"2024-02-24T21:48:48.478332Z","shell.execute_reply.started":"2024-02-24T21:48:34.880666Z","shell.execute_reply":"2024-02-24T21:48:48.477309Z"},"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-02-24T21:48:48.479541Z","iopub.execute_input":"2024-02-24T21:48:48.480235Z","iopub.status.idle":"2024-02-24T21:48:48.609981Z","shell.execute_reply.started":"2024-02-24T21:48:48.480199Z","shell.execute_reply":"2024-02-24T21:48:48.608982Z"},"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-02-24T21:48:48.611117Z","iopub.execute_input":"2024-02-24T21:48:48.611391Z","iopub.status.idle":"2024-02-24T21:48:48.655082Z","shell.execute_reply.started":"2024-02-24T21:48:48.611367Z","shell.execute_reply":"2024-02-24T21:48:48.654224Z"},"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-02-24T21:48:48.655999Z","iopub.execute_input":"2024-02-24T21:48:48.656254Z","iopub.status.idle":"2024-02-24T21:49:04.854306Z","shell.execute_reply.started":"2024-02-24T21:48:48.656231Z","shell.execute_reply":"2024-02-24T21:49:04.853410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\n# params = {\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# }\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"num_leaves\": 64,  \n    \"min_data_in_leaf\": 20, \n    \"learning_rate\": 0.05,  \n    \"feature_fraction\": 0.8,  \n    \"bagging_fraction\": 0.8,  \n    \"bagging_freq\": 5,\n    \"n_estimators\": 1000,  \n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"n_jobs\": -1\n}\n\nfitted_models = []\n\nfor 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\nmodel = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-02-24T21:49:04.855480Z","iopub.execute_input":"2024-02-24T21:49:04.855860Z","iopub.status.idle":"2024-02-24T22:25:06.063870Z","shell.execute_reply.started":"2024-02-24T21:49:04.855819Z","shell.execute_reply":"2024-02-24T22:25:06.063067Z"},"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-02-24T22:25:06.065662Z","iopub.execute_input":"2024-02-24T22:25:06.066033Z","iopub.status.idle":"2024-02-24T22:25:06.277138Z","shell.execute_reply.started":"2024-02-24T22:25:06.065999Z","shell.execute_reply":"2024-02-24T22:25:06.276314Z"},"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-02-24T22:25:06.278275Z","iopub.execute_input":"2024-02-24T22:25:06.278635Z","iopub.status.idle":"2024-02-24T22:25:06.296182Z","shell.execute_reply.started":"2024-02-24T22:25:06.278608Z","shell.execute_reply":"2024-02-24T22:25:06.295444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Check null: \", df_subm[\"score\"].isnull().any())\n\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-02-25T06:06:04.134367Z","iopub.execute_input":"2024-02-25T06:06:04.134691Z","iopub.status.idle":"2024-02-25T06:06:04.466600Z","shell.execute_reply.started":"2024-02-25T06:06:04.134663Z","shell.execute_reply":"2024-02-25T06:06:04.465400Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-02-24T22:25:06.311650Z","iopub.execute_input":"2024-02-24T22:25:06.311994Z","iopub.status.idle":"2024-02-24T22:25:06.318364Z","shell.execute_reply.started":"2024-02-24T22:25:06.311964Z","shell.execute_reply":"2024-02-24T22:25:06.317568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}