{"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":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# https://blog.csdn.net/s09094031/article/details/92428209?app_version=6.3.1&csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%2292428209%22%2C%22source%22%3A%22unlogin%22%7D&utm_source=app","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-06T05:38:43.191576Z","iopub.execute_input":"2024-04-06T05:38:43.191933Z","iopub.status.idle":"2024-04-06T05:38:45.758360Z","shell.execute_reply.started":"2024-04-06T05:38:43.191904Z","shell.execute_reply":"2024-04-06T05:38:45.757251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from 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-04-06T05:38:45.760253Z","iopub.execute_input":"2024-04-06T05:38:45.760700Z","iopub.status.idle":"2024-04-06T05:38:49.978111Z","shell.execute_reply.started":"2024-04-06T05:38:45.760669Z","shell.execute_reply":"2024-04-06T05:38:49.977170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Pipeline:\n\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    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()) # t - t-1\n        df = df.drop(\"date_decision\", \"MONTH\")\n        return df\n\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                if isnull > 0.5:\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                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n        \n        return df","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:38:49.984299Z","iopub.execute_input":"2024-04-06T05:38:49.984586Z","iopub.status.idle":"2024-04-06T05:38:49.996602Z","shell.execute_reply.started":"2024-04-06T05:38:49.984561Z","shell.execute_reply":"2024-04-06T05:38:49.995668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Aggregator:\n    \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    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    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    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    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]  # max & replace col name\n        return expr_max\n    \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-04-06T05:38:49.998532Z","iopub.execute_input":"2024-04-06T05:38:49.998837Z","iopub.status.idle":"2024-04-06T05:38:50.013595Z","shell.execute_reply.started":"2024-04-06T05:38:49.998812Z","shell.execute_reply":"2024-04-06T05:38:50.012769Z"},"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    \n    for path in glob(str(regex_path)):\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        chunks.append(df)\n    \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:38:50.014812Z","iopub.execute_input":"2024-04-06T05:38:50.015152Z","iopub.status.idle":"2024-04-06T05:38:50.026857Z","shell.execute_reply.started":"2024-04-06T05:38:50.015128Z","shell.execute_reply":"2024-04-06T05:38:50.026040Z"},"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-04-06T05:38:50.028060Z","iopub.execute_input":"2024-04-06T05:38:50.028370Z","iopub.status.idle":"2024-04-06T05:38:50.037341Z","shell.execute_reply.started":"2024-04-06T05:38:50.028340Z","shell.execute_reply":"2024-04-06T05:38:50.036287Z"},"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":{"execution":{"iopub.status.busy":"2024-04-06T05:38:50.038543Z","iopub.execute_input":"2024-04-06T05:38:50.038847Z","iopub.status.idle":"2024-04-06T05:38:50.048847Z","shell.execute_reply.started":"2024-04-06T05:38:50.038812Z","shell.execute_reply":"2024-04-06T05:38:50.047903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:38:50.050329Z","iopub.execute_input":"2024-04-06T05:38:50.050637Z","iopub.status.idle":"2024-04-06T05:38:50.057558Z","shell.execute_reply.started":"2024-04-06T05:38:50.050605Z","shell.execute_reply":"2024-04-06T05:38:50.056541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store_train = {\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        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:38:50.061357Z","iopub.execute_input":"2024-04-06T05:38:50.061676Z","iopub.status.idle":"2024-04-06T05:40:58.447425Z","shell.execute_reply.started":"2024-04-06T05:38:50.061653Z","shell.execute_reply":"2024-04-06T05:40:58.446372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store_test = {\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_files(TEST_DIR / \"test_credit_bureau_a_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        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:40:58.449117Z","iopub.execute_input":"2024-04-06T05:40:58.449468Z","iopub.status.idle":"2024-04-06T05:40:58.711301Z","shell.execute_reply.started":"2024-04-06T05:40:58.449435Z","shell.execute_reply":"2024-04-06T05:40:58.710350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#########################################################################################################################","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:40:58.712565Z","iopub.execute_input":"2024-04-06T05:40:58.713200Z","iopub.status.idle":"2024-04-06T05:40:58.717412Z","shell.execute_reply.started":"2024-04-06T05:40:58.713167Z","shell.execute_reply":"2024-04-06T05:40:58.716496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def filter_cols(df, isnull_per = 0.7, freq_num = 200):\n    for col in df.columns:\n        if col not in [\"target\", \"case_id\", \"WEEK_NUM\"]:\n            isnull = df[col].is_null().mean()\n            if isnull > isnull_per:\n                df = df.drop(col)\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            if (freq == 1) | (freq > 200):\n                df = df.drop(col)\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:40:58.718648Z","iopub.execute_input":"2024-04-06T05:40:58.718923Z","iopub.status.idle":"2024-04-06T05:40:58.728501Z","shell.execute_reply.started":"2024-04-06T05:40:58.718901Z","shell.execute_reply":"2024-04-06T05:40:58.727640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store_train)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:40:58.729567Z","iopub.execute_input":"2024-04-06T05:40:58.729840Z","iopub.status.idle":"2024-04-06T05:41:08.697092Z","shell.execute_reply.started":"2024-04-06T05:40:58.729818Z","shell.execute_reply":"2024-04-06T05:41:08.696049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store_test)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:41:08.698379Z","iopub.execute_input":"2024-04-06T05:41:08.698674Z","iopub.status.idle":"2024-04-06T05:41:08.740559Z","shell.execute_reply.started":"2024-04-06T05:41:08.698649Z","shell.execute_reply":"2024-04-06T05:41:08.739668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Selection","metadata":{}},{"cell_type":"code","source":"# Drop the insignificant features\ndf_train = filter_cols(df_train, 0.7, 200)\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-04-06T05:41:08.741795Z","iopub.execute_input":"2024-04-06T05:41:08.742520Z","iopub.status.idle":"2024-04-06T05:41:11.837761Z","shell.execute_reply.started":"2024-04-06T05:41:08.742488Z","shell.execute_reply":"2024-04-06T05:41:11.836837Z"},"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-04-06T05:41:11.839204Z","iopub.execute_input":"2024-04-06T05:41:11.839487Z","iopub.status.idle":"2024-04-06T05:41:33.104560Z","shell.execute_reply.started":"2024-04-06T05:41:11.839464Z","shell.execute_reply":"2024-04-06T05:41:33.103501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store_train\ngc.collect()\ndel data_store_test\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:41:33.105870Z","iopub.execute_input":"2024-04-06T05:41:33.106178Z","iopub.status.idle":"2024-04-06T05:41:33.700628Z","shell.execute_reply.started":"2024-04-06T05:41:33.106152Z","shell.execute_reply":"2024-04-06T05:41:33.699639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 12,  \n    \"learning_rate\": 0.05,\n    \"n_estimators\": 2000,  \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    \"verbose\": -1,\n}\n\nfitted_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    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set = [(X_valid, y_valid)],\n        callbacks = [lgb.log_evaluation(200), lgb.early_stopping(60)] )\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\ncv_scores = np.array(cv_scores)\nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-04-06T05:41:33.701734Z","iopub.execute_input":"2024-04-06T05:41:33.702039Z","iopub.status.idle":"2024-04-06T06:07:34.490826Z","shell.execute_reply.started":"2024-04-06T05:41:33.702008Z","shell.execute_reply":"2024-04-06T06:07:34.489859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predict\ndef predict(models, X_test, models_weight):\n    y_preds = pd.DataFrame(index=X_test.index,columns = ['pred_'+str(i) for i in range(0,len(models))])\n    for i in range(0,len(models)):\n        y_preds.loc[:, 'pred_'+str(i)] = np.array(models[i].predict_proba(X_test)[:,1]) * models_weight[i]\n    return y_preds.sum(1)","metadata":{"execution":{"iopub.status.busy":"2024-04-06T06:16:56.374720Z","iopub.execute_input":"2024-04-06T06:16:56.375123Z","iopub.status.idle":"2024-04-06T06:16:56.381574Z","shell.execute_reply.started":"2024-04-06T06:16:56.375094Z","shell.execute_reply":"2024-04-06T06:16:56.380526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submission","metadata":{}},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\nmodels_weight = cv_scores / cv_scores.sum()\n\nlgb_pred = pd.Series(predict(fitted_models, X_test, models_weight), index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-04-06T06:16:56.792029Z","iopub.execute_input":"2024-04-06T06:16:56.792396Z","iopub.status.idle":"2024-04-06T06:16:57.075247Z","shell.execute_reply.started":"2024-04-06T06:16:56.792368Z","shell.execute_reply":"2024-04-06T06:16:57.074203Z"},"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-04-06T06:17:02.566016Z","iopub.execute_input":"2024-04-06T06:17:02.566762Z","iopub.status.idle":"2024-04-06T06:17:02.578859Z","shell.execute_reply.started":"2024-04-06T06:17:02.566731Z","shell.execute_reply":"2024-04-06T06:17:02.578044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-26T13:57:31.193109Z","iopub.execute_input":"2024-03-26T13:57:31.193821Z","iopub.status.idle":"2024-03-26T13:57:31.203538Z","shell.execute_reply.started":"2024-03-26T13:57:31.19379Z","shell.execute_reply":"2024-03-26T13:57:31.202386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-19T21:33:29.240571Z","iopub.execute_input":"2024-03-19T21:33:29.241019Z","iopub.status.idle":"2024-03-19T21:33:29.24967Z","shell.execute_reply.started":"2024-03-19T21:33:29.240982Z","shell.execute_reply":"2024-03-19T21:33:29.248856Z"},"trusted":true},"execution_count":null,"outputs":[]}]}