{"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":7602123,"sourceType":"competition"}],"dockerImageVersionId":30648,"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 StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\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-21T15:04:31.645606Z","iopub.execute_input":"2024-02-21T15:04:31.646417Z","iopub.status.idle":"2024-02-21T15:04:36.588263Z","shell.execute_reply.started":"2024-02-21T15:04:31.646371Z","shell.execute_reply":"2024-02-21T15:04:36.587285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\n    \"\"\"Voting ensemble model.\"\"\"\n    def __init__(self, estimators):\n        \"\"\"Initialize the VotingModel with a list of base estimators.\"\"\"\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        \"\"\"Fit the base estimators.\"\"\"\n        return self\n    \n    def predict(self, X):\n        \"\"\"Make predictions using the base estimators and return the average.\"\"\"\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        \"\"\"Make probability predictions using the base estimators and return the average.\"\"\"\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-21T15:05:19.893203Z","iopub.execute_input":"2024-02-21T15:05:19.893628Z","iopub.status.idle":"2024-02-21T15:05:19.901400Z","shell.execute_reply.started":"2024-02-21T15:05:19.893597Z","shell.execute_reply":"2024-02-21T15:05:19.900332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Pipeline:\n    \"\"\"Data preprocessing pipeline.\"\"\"\n    @staticmethod\n    def set_table_dtypes(df):\n        \"\"\"Set data types for columns.\"\"\"\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        \"\"\"Handle date columns.\"\"\"\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        \"\"\"Filter columns based on missing values and other criteria.\"\"\"\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-21T15:05:21.521197Z","iopub.execute_input":"2024-02-21T15:05:21.522056Z","iopub.status.idle":"2024-02-21T15:05:21.535422Z","shell.execute_reply.started":"2024-02-21T15:05:21.522022Z","shell.execute_reply":"2024-02-21T15:05:21.534283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Aggregator:\n    \"\"\"Feature aggregation functions.\"\"\"\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-21T15:05:23.262517Z","iopub.execute_input":"2024-02-21T15:05:23.263167Z","iopub.status.idle":"2024-02-21T15:05:23.273727Z","shell.execute_reply.started":"2024-02-21T15:05:23.263138Z","shell.execute_reply":"2024-02-21T15:05:23.272702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_file(path, depth=None):\n    \"\"\"Read a single parquet file.\"\"\"\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    \"\"\"Read multiple parquet files.\"\"\"\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-21T15:05:24.576101Z","iopub.execute_input":"2024-02-21T15:05:24.576916Z","iopub.status.idle":"2024-02-21T15:05:24.583721Z","shell.execute_reply.started":"2024-02-21T15:05:24.576880Z","shell.execute_reply":"2024-02-21T15:05:24.582744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    \"\"\"Feature engineering pipeline.\"\"\"\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-21T15:05:25.905263Z","iopub.execute_input":"2024-02-21T15:05:25.905625Z","iopub.status.idle":"2024-02-21T15:05:25.911738Z","shell.execute_reply.started":"2024-02-21T15:05:25.905597Z","shell.execute_reply":"2024-02-21T15:05:25.910879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_pandas(df_data, cat_cols=None):\n    \"\"\"Convert Polars DataFrame to Pandas DataFrame.\"\"\"\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-21T15:05:27.061130Z","iopub.execute_input":"2024-02-21T15:05:27.061505Z","iopub.status.idle":"2024-02-21T15:05:27.067139Z","shell.execute_reply.started":"2024-02-21T15:05:27.061476Z","shell.execute_reply":"2024-02-21T15:05:27.066131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train_models(X_train, y_train, weeks, cv):\n    \"\"\"Train LightGBM models with cross-validation.\"\"\"\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    }\n\n    fitted_models = []\n\n    for idx_train, idx_valid in cv.split(X_train, y_train, groups=weeks):\n        X_train_fold, y_train_fold = X_train.iloc[idx_train], y_train.iloc[idx_train]\n        X_valid_fold, y_valid_fold = X_train.iloc[idx_valid], y_train.iloc[idx_valid]\n\n        model = lgb.LGBMClassifier(**params)\n        model.fit(\n            X_train_fold, y_train_fold,\n            eval_set=[(X_valid_fold, y_valid_fold)],\n            callbacks=[lgb.log_evaluation(100), lgb.early_stopping(100)]\n        )\n\n        fitted_models.append(model)\n\n    return fitted_models","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:05:28.636347Z","iopub.execute_input":"2024-02-21T15:05:28.637330Z","iopub.status.idle":"2024-02-21T15:05:28.645780Z","shell.execute_reply.started":"2024-02-21T15:05:28.637278Z","shell.execute_reply":"2024-02-21T15:05:28.644656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def evaluate_models(models, X_test, y_test):\n    \"\"\"Evaluate models on test data and return evaluation metrics.\"\"\"\n    y_preds = np.mean([model.predict_proba(X_test)[:, 1] for model in models], axis=0)\n    auc = roc_auc_score(y_test, y_preds)\n    return auc\n\ndef save_model(model, filepath):\n    \"\"\"Save the trained model to a file.\"\"\"\n    joblib.dump(model, filepath)","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:05:30.514964Z","iopub.execute_input":"2024-02-21T15:05:30.515356Z","iopub.status.idle":"2024-02-21T15:05:30.521465Z","shell.execute_reply.started":"2024-02-21T15:05:30.515325Z","shell.execute_reply":"2024-02-21T15:05:30.520393Z"},"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-21T15:05:32.229918Z","iopub.execute_input":"2024-02-21T15:05:32.230573Z","iopub.status.idle":"2024-02-21T15:05:32.235080Z","shell.execute_reply.started":"2024-02-21T15:05:32.230540Z","shell.execute_reply":"2024-02-21T15:05:32.234042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data loading and preprocessing\n# Implement data loading, preprocessing, and feature engineering steps\n\ndata_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}\ndf_train = feature_eng(**data_store)","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:05:33.663691Z","iopub.execute_input":"2024-02-21T15:05:33.664059Z","iopub.status.idle":"2024-02-21T15:06:10.077882Z","shell.execute_reply.started":"2024-02-21T15:05:33.664029Z","shell.execute_reply":"2024-02-21T15:06:10.076796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-02-21T13:33:02.154958Z","iopub.execute_input":"2024-02-21T13:33:02.155708Z","iopub.status.idle":"2024-02-21T13:33:02.165347Z","shell.execute_reply.started":"2024-02-21T13:33:02.155649Z","shell.execute_reply":"2024-02-21T13:33:02.164022Z"},"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_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}\n\ndf_test = feature_eng(**data_store)","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:06:37.912267Z","iopub.execute_input":"2024-02-21T15:06:37.913105Z","iopub.status.idle":"2024-02-21T15:06:38.378640Z","shell.execute_reply.started":"2024-02-21T15:06:37.913070Z","shell.execute_reply":"2024-02-21T15:06:38.377770Z"},"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\ndf_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\n\ndel data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:06:40.269058Z","iopub.execute_input":"2024-02-21T15:06:40.269858Z","iopub.status.idle":"2024-02-21T15:06:56.158957Z","shell.execute_reply.started":"2024-02-21T15:06:40.269826Z","shell.execute_reply":"2024-02-21T15:06:56.158092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Model training and evaluation\n# Implement model training, evaluation, and selection logic\n\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)\n\nfitted_models = train_models(X, y, weeks, cv)\nauc = evaluate_models(fitted_models, X, y)\nprint(\"Mean AUC on training data:\", auc)","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:07:01.188185Z","iopub.execute_input":"2024-02-21T15:07:01.189390Z","iopub.status.idle":"2024-02-21T15:28:21.536825Z","shell.execute_reply.started":"2024-02-21T15:07:01.189350Z","shell.execute_reply":"2024-02-21T15:28:21.535900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Final model selection and saving\n# Select the best model based on evaluation metrics and save it for future use\n\nbest_model = fitted_models[3]  # For demonstration, select the first model as the best model\nsave_model(best_model, \"best_model.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:32:51.182610Z","iopub.execute_input":"2024-02-21T15:32:51.183034Z","iopub.status.idle":"2024-02-21T15:32:51.298495Z","shell.execute_reply.started":"2024-02-21T15:32:51.183000Z","shell.execute_reply":"2024-02-21T15:32:51.297554Z"},"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(best_model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:34:13.547462Z","iopub.execute_input":"2024-02-21T15:34:13.547805Z","iopub.status.idle":"2024-02-21T15:34:13.602090Z","shell.execute_reply.started":"2024-02-21T15:34:13.547773Z","shell.execute_reply":"2024-02-21T15:34:13.601288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\n    \"case_id\": df_test[\"case_id\"].to_numpy(),\n    \"score\": y_pred\n}).set_index('case_id')\nsubmission.to_csv(\"./submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:47:20.158924Z","iopub.execute_input":"2024-02-21T15:47:20.159307Z","iopub.status.idle":"2024-02-21T15:47:20.167043Z","shell.execute_reply.started":"2024-02-21T15:47:20.159277Z","shell.execute_reply":"2024-02-21T15:47:20.166006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-21T15:47:33.188905Z","iopub.execute_input":"2024-02-21T15:47:33.189293Z","iopub.status.idle":"2024-02-21T15:47:33.199293Z","shell.execute_reply.started":"2024-02-21T15:47:33.189258Z","shell.execute_reply":"2024-02-21T15:47:33.198046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}