{"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":30698,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Import library","metadata":{}},{"cell_type":"code","source":"# Ignore future warnings\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n# Import the operating system interface\nimport os\n# Import the garbage collection module\nimport gc\n\n# Import the NumPy library and rename it np\nimport numpy as np\n# import pandas as pd\nimport pandas as pd\n\n# Import the Polars library and print the version number\nimport polars as pl\nprint(pl.__version__)\n\n# Import glob function from glob module for file path pattern matching\nfrom glob import glob\n# Import the Path class from the pathlib module for working with file paths\nfrom pathlib import Path\n# Import the datetime class from the datetime module for working with dates and times\nfrom datetime import datetime\n\n# Import the plotting module of matplotlib and rename it plt\nimport matplotlib.pyplot as plt\n# import seaborn as sns\nimport seaborn as sns\n\n# Import time series segmentation classes from sklearn.model_selection\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\n# Import base class Estimator and regressor mixins from sklearn.base\nfrom sklearn.base import BaseEstimator, RegressorMixin\n# ROC-AUC calculation methodology\nfrom sklearn.metrics import roc_auc_score\n# Import the LightGBM library and rename it lgb\nimport lightgbm as lgb","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:22:36.702349Z","iopub.execute_input":"2024-05-11T05:22:36.703084Z","iopub.status.idle":"2024-05-11T05:22:41.857361Z","shell.execute_reply.started":"2024-05-11T05:22:36.703054Z","shell.execute_reply":"2024-05-11T05:22:41.856310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Table Description","metadata":{}},{"cell_type":"code","source":"class Pipeline:\n    #Set table data type\n    # https://www.kaggle.com/competitions/home-credit-credit-risk-model-stability/data\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    # Processing date\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    # Filter columns\n    # If the column name is not in the reserved list and the column's null ratio is greater than 0.95, remove the column\n    # Remove the column if the column name is not in the reserved list and the column's data type is String and the number of unique values is 1 or greater than 200\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-11T05:22:53.850267Z","iopub.execute_input":"2024-05-11T05:22:53.850615Z","iopub.status.idle":"2024-05-11T05:22:53.863864Z","shell.execute_reply.started":"2024-05-11T05:22:53.850590Z","shell.execute_reply":"2024-05-11T05:22:53.862735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Defines a class called Aggregator that contains several static methods for generating aggregated expressions","metadata":{}},{"cell_type":"code","source":"# defines a class called Aggregator that contains several static methods that generate aggregate expressions\nclass Aggregator:\n    # Generate maximum value aggregation expression for numeric columns\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    # Generate maximum value aggregation expression for date type column\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    # Generate maximum value aggregation expression for column of type string\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    # Generate maximum value aggregation expression for other types of columns\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    # Generate a maximum value aggregation expression for a specific column that contains \"num_group\".\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    # Get all types of aggregate expressions\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-11T05:22:57.420833Z","iopub.execute_input":"2024-05-11T05:22:57.421646Z","iopub.status.idle":"2024-05-11T05:22:57.432328Z","shell.execute_reply.started":"2024-05-11T05:22:57.421617Z","shell.execute_reply":"2024-05-11T05:22:57.431235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read a single file and preprocess it\ndef read_file(path, depth=None):\n    # Use the Polars library to read Parquet files\n    df = pl.read_parquet(path)\n    # Call the set_table_dtypes method of the Pipeline class to set the data type\n    df = df.pipe(Pipeline.set_table_dtypes)\n    # If the depth parameter is 1 or 2, the data is aggregated by case_id\n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    return df\n\n# Read multiple files and preprocess\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-11T05:22:58.298534Z","iopub.execute_input":"2024-05-11T05:22:58.299351Z","iopub.status.idle":"2024-05-11T05:22:58.306135Z","shell.execute_reply.started":"2024-05-11T05:22:58.299318Z","shell.execute_reply":"2024-05-11T05:22:58.305232Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Feature engineering functions for adding new features and merging data frames","metadata":{}},{"cell_type":"code","source":"# Feature engineering functions for adding new features and merging data frames\ndef 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-11T05:22:59.303267Z","iopub.execute_input":"2024-05-11T05:22:59.303613Z","iopub.status.idle":"2024-05-11T05:22:59.309864Z","shell.execute_reply.started":"2024-05-11T05:22:59.303586Z","shell.execute_reply":"2024-05-11T05:22:59.308853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert the Polars data frame to the Pandas data frame and process the category columns\ndef 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-05-11T05:22:59.922457Z","iopub.execute_input":"2024-05-11T05:22:59.922766Z","iopub.status.idle":"2024-05-11T05:22:59.928104Z","shell.execute_reply.started":"2024-05-11T05:22:59.922741Z","shell.execute_reply":"2024-05-11T05:22:59.927030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n# ROOT            = Path(\"./input\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:23:00.175176Z","iopub.execute_input":"2024-05-11T05:23:00.176018Z","iopub.status.idle":"2024-05-11T05:23:00.180914Z","shell.execute_reply.started":"2024-05-11T05:23:00.175978Z","shell.execute_reply":"2024-05-11T05:23:00.179719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read the file of the training set\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}","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:28:59.578051Z","iopub.execute_input":"2024-05-11T05:28:59.578423Z","iopub.status.idle":"2024-05-11T05:29:31.143690Z","shell.execute_reply.started":"2024-05-11T05:28:59.578388Z","shell.execute_reply":"2024-05-11T05:29:31.142719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Perform feature engineering on the training set\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:30:03.971609Z","iopub.execute_input":"2024-05-11T05:30:03.972344Z","iopub.status.idle":"2024-05-11T05:30:09.212385Z","shell.execute_reply.started":"2024-05-11T05:30:03.972311Z","shell.execute_reply":"2024-05-11T05:30:09.211342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read the test set file\ndata_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-05-11T05:30:12.309988Z","iopub.execute_input":"2024-05-11T05:30:12.310336Z","iopub.status.idle":"2024-05-11T05:30:12.751072Z","shell.execute_reply.started":"2024-05-11T05:30:12.310308Z","shell.execute_reply":"2024-05-11T05:30:12.750249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Feature engineering the test set\ndf_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:30:12.752816Z","iopub.execute_input":"2024-05-11T05:30:12.753513Z","iopub.status.idle":"2024-05-11T05:30:12.784090Z","shell.execute_reply.started":"2024-05-11T05:30:12.753478Z","shell.execute_reply":"2024-05-11T05:30:12.783226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Perform feature filtering\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(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:30:12.785460Z","iopub.execute_input":"2024-05-11T05:30:12.785744Z","iopub.status.idle":"2024-05-11T05:30:14.716482Z","shell.execute_reply.started":"2024-05-11T05:30:12.785720Z","shell.execute_reply":"2024-05-11T05:30:14.715551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert to pandas\ndf_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:30:14.718440Z","iopub.execute_input":"2024-05-11T05:30:14.718914Z","iopub.status.idle":"2024-05-11T05:30:29.939503Z","shell.execute_reply.started":"2024-05-11T05:30:14.718878Z","shell.execute_reply":"2024-05-11T05:30:29.938496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:30:29.940809Z","iopub.execute_input":"2024-05-11T05:30:29.941104Z","iopub.status.idle":"2024-05-11T05:30:30.055575Z","shell.execute_reply.started":"2024-05-11T05:30:29.941081Z","shell.execute_reply":"2024-05-11T05:30:30.054500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training","metadata":{}},{"cell_type":"code","source":"# Custom voting model, API similar to sklearn's\nclass 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-11T05:30:30.057884Z","iopub.execute_input":"2024-05-11T05:30:30.058196Z","iopub.status.idle":"2024-05-11T05:30:30.065791Z","shell.execute_reply.started":"2024-05-11T05:30:30.058172Z","shell.execute_reply":"2024-05-11T05:30:30.064990Z"},"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\n# Define cross-validation\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\n# LGB model parameters\nparams = {\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\",  # Uncomment if you want to use GPU for training\n}\n\nfitted_models = []\ncv_scores = []\n\n# # Cross-validate the trained model\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-11T05:30:30.066996Z","iopub.execute_input":"2024-05-11T05:30:30.067709Z","iopub.status.idle":"2024-05-11T05:50:42.496901Z","shell.execute_reply.started":"2024-05-11T05:30:30.067655Z","shell.execute_reply":"2024-05-11T05:50:42.495712Z"},"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-11T05:50:42.498307Z","iopub.execute_input":"2024-05-11T05:50:42.498614Z","iopub.status.idle":"2024-05-11T05:50:42.717696Z","shell.execute_reply.started":"2024-05-11T05:50:42.498588Z","shell.execute_reply":"2024-05-11T05:50:42.716854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submission","metadata":{}},{"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-11T05:50:42.719142Z","iopub.execute_input":"2024-05-11T05:50:42.719436Z","iopub.status.idle":"2024-05-11T05:50:42.741581Z","shell.execute_reply.started":"2024-05-11T05:50:42.719410Z","shell.execute_reply":"2024-05-11T05:50:42.740790Z"},"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-11T05:50:42.742755Z","iopub.execute_input":"2024-05-11T05:50:42.743014Z","iopub.status.idle":"2024-05-11T05:50:42.748722Z","shell.execute_reply.started":"2024-05-11T05:50:42.742991Z","shell.execute_reply":"2024-05-11T05:50:42.747719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:50:42.749920Z","iopub.execute_input":"2024-05-11T05:50:42.750281Z","iopub.status.idle":"2024-05-11T05:50:42.762510Z","shell.execute_reply.started":"2024-05-11T05:50:42.750258Z","shell.execute_reply":"2024-05-11T05:50:42.761641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-05-11T05:50:42.766766Z","iopub.execute_input":"2024-05-11T05:50:42.767049Z","iopub.status.idle":"2024-05-11T05:50:42.773722Z","shell.execute_reply.started":"2024-05-11T05:50:42.767026Z","shell.execute_reply":"2024-05-11T05:50:42.772729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}