{"metadata":{"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"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.10.13"},"papermill":{"default_parameters":{},"duration":9468.936222,"end_time":"2024-02-18T04:41:03.134316","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-02-18T02:03:14.198094","version":"2.5.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Home Credit - Credit Risk Model Stability\n\nref：https://www.kaggle.com/code/finlay/home-credit-02-lightgbm","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:37.247434Z","iopub.execute_input":"2024-05-07T15:38:37.247795Z","iopub.status.idle":"2024-05-07T15:38:37.253724Z","shell.execute_reply.started":"2024-05-07T15:38:37.247769Z","shell.execute_reply":"2024-05-07T15:38:37.252476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import library","metadata":{}},{"cell_type":"code","source":"import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport os\nimport gc\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nprint(pl.__version__)\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nimport lightgbm as lgb","metadata":{"execution":{"iopub.status.busy":"2024-05-07T16:00:40.809879Z","iopub.execute_input":"2024-05-07T16:00:40.810253Z","iopub.status.idle":"2024-05-07T16:00:40.816961Z","shell.execute_reply.started":"2024-05-07T16:00:40.810204Z","shell.execute_reply":"2024-05-07T16:00:40.815942Z"},"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        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.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-05-07T16:01:26.300886Z","iopub.execute_input":"2024-05-07T16:01:26.301297Z","iopub.status.idle":"2024-05-07T16:01:26.315108Z","shell.execute_reply.started":"2024-05-07T16:01:26.301264Z","shell.execute_reply":"2024-05-07T16:01:26.314052Z"},"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        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-05-07T16:01:36.820153Z","iopub.execute_input":"2024-05-07T16:01:36.820967Z","iopub.status.idle":"2024-05-07T16:01:36.832961Z","shell.execute_reply.started":"2024-05-07T16:01:36.820938Z","shell.execute_reply":"2024-05-07T16:01:36.831962Z"},"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    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\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    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    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-07T16:01:51.964928Z","iopub.execute_input":"2024-05-07T16:01:51.96533Z","iopub.status.idle":"2024-05-07T16:01:51.972458Z","shell.execute_reply.started":"2024-05-07T16:01:51.9653Z","shell.execute_reply":"2024-05-07T16:01:51.971605Z"},"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    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    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base","metadata":{"execution":{"iopub.status.busy":"2024-05-07T16:02:01.249415Z","iopub.execute_input":"2024-05-07T16:02:01.250033Z","iopub.status.idle":"2024-05-07T16:02:01.256152Z","shell.execute_reply.started":"2024-05-07T16:02:01.250002Z","shell.execute_reply":"2024-05-07T16:02:01.2551Z"},"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    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    return df_data, cat_cols","metadata":{"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-05-07T16:03:33.20399Z","iopub.execute_input":"2024-05-07T16:03:33.204857Z","iopub.status.idle":"2024-05-07T16:03:33.209176Z","shell.execute_reply.started":"2024-05-07T16:03:33.204824Z","shell.execute_reply":"2024-05-07T16:03:33.208198Z"},"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_file(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_file(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-05-07T16:12:22.618474Z","iopub.execute_input":"2024-05-07T16:12:22.619119Z","iopub.status.idle":"2024-05-07T16:12:51.555746Z","shell.execute_reply.started":"2024-05-07T16:12:22.619089Z","shell.execute_reply":"2024-05-07T16:12:51.554964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-07T16:05:01.879648Z","iopub.execute_input":"2024-05-07T16:05:01.879991Z","iopub.status.idle":"2024-05-07T16:05:07.129987Z","shell.execute_reply.started":"2024-05-07T16:05:01.879964Z","shell.execute_reply":"2024-05-07T16:05:07.129045Z"},"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_file(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-05-08T14:02:36.20037Z","iopub.execute_input":"2024-05-08T14:02:36.201347Z","iopub.status.idle":"2024-05-08T14:02:36.244708Z","shell.execute_reply.started":"2024-05-08T14:02:36.201306Z","shell.execute_reply":"2024-05-08T14:02:36.243289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-07T16:05:32.464241Z","iopub.execute_input":"2024-05-07T16:05:32.464672Z","iopub.status.idle":"2024-05-07T16:05:32.717424Z","shell.execute_reply.started":"2024-05-07T16:05:32.464633Z","shell.execute_reply":"2024-05-07T16:05:32.716488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_test = feature_eng(**data_store)\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:00:23.716951Z","iopub.execute_input":"2024-05-08T14:00:23.7179Z","iopub.status.idle":"2024-05-08T14:00:23.74597Z","shell.execute_reply.started":"2024-05-08T14:00:23.717864Z","shell.execute_reply":"2024-05-08T14:00:23.744796Z"},"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-05-07T16:05:48.22373Z","iopub.execute_input":"2024-05-07T16:05:48.224076Z","iopub.status.idle":"2024-05-07T16:05:48.275445Z","shell.execute_reply.started":"2024-05-07T16:05:48.224049Z","shell.execute_reply":"2024-05-07T16:05:48.274259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-07T16:07:05.129365Z","iopub.execute_input":"2024-05-07T16:07:05.129723Z","iopub.status.idle":"2024-05-07T16:07:05.768546Z","shell.execute_reply.started":"2024-05-07T16:07:05.129697Z","shell.execute_reply":"2024-05-07T16:07:05.767594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-05-07T16:07:11.864222Z","iopub.execute_input":"2024-05-07T16:07:11.865028Z","iopub.status.idle":"2024-05-07T16:07:11.872805Z","shell.execute_reply.started":"2024-05-07T16:07:11.86499Z","shell.execute_reply":"2024-05-07T16:07:11.871753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nX = 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)","metadata":{"execution":{"iopub.status.busy":"2024-05-08T14:02:21.389875Z","iopub.execute_input":"2024-05-08T14:02:21.390539Z","iopub.status.idle":"2024-05-08T14:02:21.416653Z","shell.execute_reply.started":"2024-05-08T14:02:21.390509Z","shell.execute_reply":"2024-05-08T14:02:21.415585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,\n    \"learning_rate\": 0.05,\n    \"max_bin\": 255,\n    \"n_estimators\": 1200,\n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    'num_leaves':64,\n    \"device\": \"gpu\",\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:41.127883Z","iopub.status.idle":"2024-05-07T15:38:41.128246Z","shell.execute_reply.started":"2024-05-07T15:38:41.128061Z","shell.execute_reply":"2024-05-07T15:38:41.128076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fitted_models = []\ncv_scores = []\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    print(\"Valid week range: \", (weeks.iloc[idx_valid].min(), weeks.iloc[idx_valid].max()))\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(50), lgb.early_stopping(50)]\n    )\n\n    fitted_models.append(model)\n\n    y_pred_valid = model.predict_proba(X_valid)[:, 1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n\nmodel = VotingModel(fitted_models)\nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Average CV AUC score: \", sum(cv_scores) / len(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:41.129576Z","iopub.status.idle":"2024-05-07T15:38:41.129934Z","shell.execute_reply.started":"2024-05-07T15:38:41.129766Z","shell.execute_reply":"2024-05-07T15:38:41.129781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\n\nlgb_pred = pd.Series(model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:41.130813Z","iopub.status.idle":"2024-05-07T15:38:41.131146Z","shell.execute_reply.started":"2024-05-07T15:38:41.130974Z","shell.execute_reply":"2024-05-07T15:38:41.130989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\"] = lgb_pred","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:41.132717Z","iopub.status.idle":"2024-05-07T15:38:41.133084Z","shell.execute_reply.started":"2024-05-07T15:38:41.132885Z","shell.execute_reply":"2024-05-07T15:38:41.132899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Check null: \", df_subm[\"score\"].isnull().any())","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:41.134423Z","iopub.status.idle":"2024-05-07T15:38:41.134738Z","shell.execute_reply.started":"2024-05-07T15:38:41.134581Z","shell.execute_reply":"2024-05-07T15:38:41.134594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.head()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:41.135662Z","iopub.status.idle":"2024-05-07T15:38:41.136037Z","shell.execute_reply.started":"2024-05-07T15:38:41.135859Z","shell.execute_reply":"2024-05-07T15:38:41.135879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-05-07T15:38:41.136987Z","iopub.status.idle":"2024-05-07T15:38:41.13733Z","shell.execute_reply.started":"2024-05-07T15:38:41.137145Z","shell.execute_reply":"2024-05-07T15:38:41.137158Z"},"trusted":true},"execution_count":null,"outputs":[]}]}