{"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":30698,"isInternetEnabled":false,"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 StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\nimport lightgbm as lgb\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:39:19.518754Z","iopub.execute_input":"2024-05-20T04:39:19.519142Z","iopub.status.idle":"2024-05-20T04:39:24.728186Z","shell.execute_reply.started":"2024-05-20T04:39:19.519113Z","shell.execute_reply":"2024-05-20T04:39:24.726836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, ClassifierMixin):\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-20T04:39:26.794363Z","iopub.execute_input":"2024-05-20T04:39:26.795440Z","iopub.status.idle":"2024-05-20T04:39:26.804312Z","shell.execute_reply.started":"2024-05-20T04:39:26.795397Z","shell.execute_reply":"2024-05-20T04:39:26.802970Z"},"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.Int32))\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                df = df.with_columns(pl.col(col).cast(pl.Float32))\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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:39:28.384976Z","iopub.execute_input":"2024-05-20T04:39:28.385424Z","iopub.status.idle":"2024-05-20T04:39:28.401053Z","shell.execute_reply.started":"2024-05-20T04:39:28.385391Z","shell.execute_reply":"2024-05-20T04:39:28.399927Z"},"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-05-20T04:39:29.279039Z","iopub.execute_input":"2024-05-20T04:39:29.279450Z","iopub.status.idle":"2024-05-20T04:39:29.293823Z","shell.execute_reply.started":"2024-05-20T04:39:29.279420Z","shell.execute_reply":"2024-05-20T04:39:29.292422Z"},"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        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        chunks.append(df)\n        \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:39:30.800420Z","iopub.execute_input":"2024-05-20T04:39:30.800826Z","iopub.status.idle":"2024-05-20T04:39:30.810356Z","shell.execute_reply.started":"2024-05-20T04:39:30.800798Z","shell.execute_reply":"2024-05-20T04:39:30.809087Z"},"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-05-20T04:39:32.261582Z","iopub.execute_input":"2024-05-20T04:39:32.262259Z","iopub.status.idle":"2024-05-20T04:39:32.268815Z","shell.execute_reply.started":"2024-05-20T04:39:32.262223Z","shell.execute_reply":"2024-05-20T04:39:32.267707Z"},"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-05-20T04:39:33.996231Z","iopub.execute_input":"2024-05-20T04:39:33.996668Z","iopub.status.idle":"2024-05-20T04:39:34.004432Z","shell.execute_reply.started":"2024-05-20T04:39:33.996634Z","shell.execute_reply":"2024-05-20T04:39:34.002266Z"},"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-20T04:39:35.406362Z","iopub.execute_input":"2024-05-20T04:39:35.406753Z","iopub.status.idle":"2024-05-20T04:39:35.412997Z","shell.execute_reply.started":"2024-05-20T04:39:35.406725Z","shell.execute_reply":"2024-05-20T04:39:35.411521Z"},"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_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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:39:36.935377Z","iopub.execute_input":"2024-05-20T04:39:36.935806Z","iopub.status.idle":"2024-05-20T04:42:08.591594Z","shell.execute_reply.started":"2024-05-20T04:39:36.935772Z","shell.execute_reply":"2024-05-20T04:42:08.590394Z"},"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-05-20T04:42:12.912759Z","iopub.execute_input":"2024-05-20T04:42:12.913227Z","iopub.status.idle":"2024-05-20T04:42:25.015473Z","shell.execute_reply.started":"2024-05-20T04:42:12.913194Z","shell.execute_reply":"2024-05-20T04:42:25.014551Z"},"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_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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:42:41.949690Z","iopub.execute_input":"2024-05-20T04:42:41.950100Z","iopub.status.idle":"2024-05-20T04:42:42.622299Z","shell.execute_reply.started":"2024-05-20T04:42:41.950069Z","shell.execute_reply":"2024-05-20T04:42:42.621372Z"},"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-05-20T04:42:45.453420Z","iopub.execute_input":"2024-05-20T04:42:45.454030Z","iopub.status.idle":"2024-05-20T04:42:45.512872Z","shell.execute_reply.started":"2024-05-20T04:42:45.453997Z","shell.execute_reply":"2024-05-20T04:42:45.511676Z"},"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-05-20T04:42:47.270267Z","iopub.execute_input":"2024-05-20T04:42:47.270727Z","iopub.status.idle":"2024-05-20T04:42:50.293835Z","shell.execute_reply.started":"2024-05-20T04:42:47.270694Z","shell.execute_reply":"2024-05-20T04:42:50.292568Z"},"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-20T04:42:51.804659Z","iopub.execute_input":"2024-05-20T04:42:51.805158Z","iopub.status.idle":"2024-05-20T04:43:16.115097Z","shell.execute_reply.started":"2024-05-20T04:42:51.805119Z","shell.execute_reply":"2024-05-20T04:43:16.113652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:43:18.212308Z","iopub.execute_input":"2024-05-20T04:43:18.212722Z","iopub.status.idle":"2024-05-20T04:43:18.333782Z","shell.execute_reply.started":"2024-05-20T04:43:18.212690Z","shell.execute_reply":"2024-05-20T04:43:18.332278Z"},"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()))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:43:19.800363Z","iopub.execute_input":"2024-05-20T04:43:19.800770Z","iopub.status.idle":"2024-05-20T04:43:19.835342Z","shell.execute_reply.started":"2024-05-20T04:43:19.800743Z","shell.execute_reply":"2024-05-20T04:43:19.834060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# print(df_train['target'].value_counts())\n# from imblearn.under_sampling import RandomUnderSampler\n# from imblearn.over_sampling import SMOTE\n# x = df_train.drop('target', axis=1)\n# y = df_train['target']\n\n# x_encoded = pd.get_dummies(x)\n# oversample = SMOTE(random_state=42)\n# #undersample = RandomUnderSampler()\n# X, Y = oversample.fit_resample(x, y)\n# df_train = pd.concat([pd.DataFrame(X, columns=x_encoded.columns), pd.Series(Y, name='target')], axis=1)\n# print(\"after--------------\", df_train['target'].value_counts())\n\n# print(df_train.isnull().sum())","metadata":{"execution":{"iopub.status.busy":"2024-05-20T05:12:20.901844Z","iopub.execute_input":"2024-05-20T05:12:20.902450Z","iopub.status.idle":"2024-05-20T05:12:22.076289Z","shell.execute_reply.started":"2024-05-20T05:12:20.902414Z","shell.execute_reply":"2024-05-20T05:12:22.074596Z"},"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\": 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}\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(10), lgb.early_stopping(10)]\n    )\n\n    fitted_models.append(model)\n\nmodel = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T04:59:46.547138Z","iopub.execute_input":"2024-05-20T04:59:46.548144Z","iopub.status.idle":"2024-05-20T05:07:06.768992Z","shell.execute_reply.started":"2024-05-20T04:59:46.548091Z","shell.execute_reply":"2024-05-20T05:07:06.767432Z"},"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\ny_pred = pd.Series(model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T05:07:27.815251Z","iopub.execute_input":"2024-05-20T05:07:27.815919Z","iopub.status.idle":"2024-05-20T05:07:28.198054Z","shell.execute_reply.started":"2024-05-20T05:07:27.815874Z","shell.execute_reply":"2024-05-20T05:07:28.196322Z"},"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\"] = y_pred","metadata":{"execution":{"iopub.status.busy":"2024-05-20T05:07:31.306036Z","iopub.execute_input":"2024-05-20T05:07:31.306520Z","iopub.status.idle":"2024-05-20T05:07:31.324784Z","shell.execute_reply.started":"2024-05-20T05:07:31.306484Z","shell.execute_reply":"2024-05-20T05:07:31.323680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Check null: \", df_subm[\"score\"].isnull().any())\n\ndf_subm.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T05:07:35.535592Z","iopub.execute_input":"2024-05-20T05:07:35.536499Z","iopub.status.idle":"2024-05-20T05:07:35.555569Z","shell.execute_reply.started":"2024-05-20T05:07:35.536449Z","shell.execute_reply":"2024-05-20T05:07:35.553538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-05-20T05:07:45.853659Z","iopub.execute_input":"2024-05-20T05:07:45.854196Z","iopub.status.idle":"2024-05-20T05:07:45.872387Z","shell.execute_reply.started":"2024-05-20T05:07:45.854156Z","shell.execute_reply":"2024-05-20T05:07:45.870349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}