{"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"}],"dockerImageVersionId":30646,"isInternetEnabled":true,"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 train_test_split\nfrom sklearn.base import BaseEstimator, RegressorMixin\n\nimport joblib\n\nimport xgboost as xgb\nimport lightgbm as lgb\nimport shap\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-23T17:17:45.986134Z","iopub.execute_input":"2024-02-23T17:17:45.987083Z","iopub.status.idle":"2024-02-23T17:17:45.995322Z","shell.execute_reply.started":"2024-02-23T17:17:45.987045Z","shell.execute_reply":"2024-02-23T17:17:45.993940Z"},"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-02-23T17:17:45.997146Z","iopub.execute_input":"2024-02-23T17:17:45.997507Z","iopub.status.idle":"2024-02-23T17:17:46.013082Z","shell.execute_reply.started":"2024-02-23T17:17:45.997478Z","shell.execute_reply":"2024-02-23T17:17:46.011892Z"},"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-02-23T17:17:46.015052Z","iopub.execute_input":"2024-02-23T17:17:46.015454Z","iopub.status.idle":"2024-02-23T17:17:46.031787Z","shell.execute_reply.started":"2024-02-23T17:17:46.015412Z","shell.execute_reply":"2024-02-23T17:17:46.030791Z"},"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-02-23T17:17:46.033080Z","iopub.execute_input":"2024-02-23T17:17:46.033516Z","iopub.status.idle":"2024-02-23T17:17:46.048852Z","shell.execute_reply.started":"2024-02-23T17:17:46.033477Z","shell.execute_reply":"2024-02-23T17:17:46.047691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-23T17:17:46.051279Z","iopub.execute_input":"2024-02-23T17:17:46.051680Z","iopub.status.idle":"2024-02-23T17:17:46.059917Z","shell.execute_reply.started":"2024-02-23T17:17:46.051652Z","shell.execute_reply":"2024-02-23T17:17:46.058911Z"},"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-23T17:17:46.061069Z","iopub.execute_input":"2024-02-23T17:17:46.061649Z","iopub.status.idle":"2024-02-23T17:17:46.074995Z","shell.execute_reply.started":"2024-02-23T17:17:46.061620Z","shell.execute_reply":"2024-02-23T17:17:46.073821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-23T17:17:46.076636Z","iopub.execute_input":"2024-02-23T17:17:46.077025Z","iopub.status.idle":"2024-02-23T17:17:46.085310Z","shell.execute_reply.started":"2024-02-23T17:17:46.076995Z","shell.execute_reply":"2024-02-23T17:17:46.084332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_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}\n\ntest_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-23T17:17:46.143211Z","iopub.execute_input":"2024-02-23T17:17:46.143995Z","iopub.status.idle":"2024-02-23T17:18:18.353153Z","shell.execute_reply.started":"2024-02-23T17:17:46.143951Z","shell.execute_reply":"2024-02-23T17:18:18.352071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**train_data_store)\ndf_test = feature_eng(**test_data_store)","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:18:18.355412Z","iopub.execute_input":"2024-02-23T17:18:18.355742Z","iopub.status.idle":"2024-02-23T17:18:26.718427Z","shell.execute_reply.started":"2024-02-23T17:18:18.355715Z","shell.execute_reply":"2024-02-23T17:18:26.717308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(df_train.shape)\nprint(df_test.shape)\n\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n\nprint(df_train.shape)\nprint(df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:18:26.719813Z","iopub.execute_input":"2024-02-23T17:18:26.720142Z","iopub.status.idle":"2024-02-23T17:18:29.164655Z","shell.execute_reply.started":"2024-02-23T17:18:26.720113Z","shell.execute_reply":"2024-02-23T17:18:29.163536Z"},"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-02-23T17:18:29.165958Z","iopub.execute_input":"2024-02-23T17:18:29.166291Z","iopub.status.idle":"2024-02-23T17:18:44.354091Z","shell.execute_reply.started":"2024-02-23T17:18:29.166263Z","shell.execute_reply":"2024-02-23T17:18:44.352930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del train_data_store\ndel test_data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:18:44.357093Z","iopub.execute_input":"2024-02-23T17:18:44.357481Z","iopub.status.idle":"2024-02-23T17:18:44.820052Z","shell.execute_reply.started":"2024-02-23T17:18:44.357449Z","shell.execute_reply":"2024-02-23T17:18:44.818933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.01,\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}","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:18:44.821336Z","iopub.execute_input":"2024-02-23T17:18:44.821704Z","iopub.status.idle":"2024-02-23T17:18:44.831755Z","shell.execute_reply.started":"2024-02-23T17:18:44.821674Z","shell.execute_reply":"2024-02-23T17:18:44.830774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X, y = df_train.iloc[:, 3:], df_train['target']\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n# train_x = xgb.DMatrix(X, label=y, enable_categorical=True)\n\nmodel = lgb.LGBMClassifier(**params)\nmodel.fit(\n        X, y,\n        callbacks=[lgb.log_evaluation(100)]\n    )","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:18:44.833129Z","iopub.execute_input":"2024-02-23T17:18:44.833472Z","iopub.status.idle":"2024-02-23T17:22:34.077344Z","shell.execute_reply.started":"2024-02-23T17:18:44.833443Z","shell.execute_reply":"2024-02-23T17:22:34.076438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del X\ndel y","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:22:34.078717Z","iopub.execute_input":"2024-02-23T17:22:34.079142Z","iopub.status.idle":"2024-02-23T17:22:34.088953Z","shell.execute_reply.started":"2024-02-23T17:22:34.079106Z","shell.execute_reply":"2024-02-23T17:22:34.088115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"explainer = shap.Explainer(model)\nshap_values = explainer(df_test.iloc[:, 2:])","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:22:34.090290Z","iopub.execute_input":"2024-02-23T17:22:34.090584Z","iopub.status.idle":"2024-02-23T17:22:35.911476Z","shell.execute_reply.started":"2024-02-23T17:22:34.090561Z","shell.execute_reply":"2024-02-23T17:22:35.910677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_shap = pd.DataFrame([df_test.iloc[:, 2:].columns.tolist(), np.abs(shap_values.values).mean(axis=0).tolist()]).T\ndf_shap.columns = [\"col_list\", \"Shap_value\"]\ndf_shap = df_shap.sort_values(by=['Shap_value'], ascending=False)","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:22:35.912499Z","iopub.execute_input":"2024-02-23T17:22:35.912766Z","iopub.status.idle":"2024-02-23T17:22:35.935634Z","shell.execute_reply.started":"2024-02-23T17:22:35.912742Z","shell.execute_reply":"2024-02-23T17:22:35.934785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rank_col = list(df_shap['col_list'])","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:22:35.936763Z","iopub.execute_input":"2024-02-23T17:22:35.937435Z","iopub.status.idle":"2024-02-23T17:22:35.941529Z","shell.execute_reply.started":"2024-02-23T17:22:35.937401Z","shell.execute_reply":"2024-02-23T17:22:35.940660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score\n\nfor i in range(20, 221, 50):\n    X, y = df_train.loc[:, rank_col[:i]], df_train['target']\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n            X_train, y_train\n        )\n    \n    pred = model.predict(X_test)\n    accuracy = roc_auc_score(pred, y_test)\n    \n    print(f\"Top {i} Features Accuracy : {accuracy}\")","metadata":{"execution":{"iopub.status.busy":"2024-02-23T17:26:08.268242Z","iopub.execute_input":"2024-02-23T17:26:08.269115Z","iopub.status.idle":"2024-02-23T17:38:07.940489Z","shell.execute_reply.started":"2024-02-23T17:26:08.269082Z","shell.execute_reply":"2024-02-23T17:38:07.939431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}