{"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":"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'\n\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\n\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import KNNImputer","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-19T12:46:08.447792Z","iopub.execute_input":"2024-05-19T12:46:08.448849Z","iopub.status.idle":"2024-05-19T12:46:08.455880Z","shell.execute_reply.started":"2024-05-19T12:46:08.448819Z","shell.execute_reply":"2024-05-19T12:46:08.454825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# class Aggregator:\n#     #Please add or subtract features yourself, be aware that too many features will take up too much space.\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        \n#         expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n#         #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n#         expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n#         return expr_max +expr_last+expr_mean\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#         #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n#         expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n#         #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n#         expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n#         return  expr_max +expr_last+expr_mean\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#         #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n#         expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n#         #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n#         #expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n#         return  expr_max +expr_last#+expr_count\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#         #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n#         expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n#         #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n#         return  expr_max +expr_last\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] \n#         #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n#         expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n#         #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n#         return  expr_max +expr_last\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-05-19T12:46:08.463068Z","iopub.execute_input":"2024-05-19T12:46:08.463371Z","iopub.status.idle":"2024-05-19T12:46:08.478319Z","shell.execute_reply.started":"2024-05-19T12:46:08.463349Z","shell.execute_reply":"2024-05-19T12:46:08.477494Z"},"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.7:\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\n\n\n# class Aggregator:\n#     @staticmethod\n#     def generate_expr(df, suffixes):\n#         exprs = []\n#         for col_suffix in suffixes:\n#             cols = [col for col in df.columns if col.endswith(col_suffix)]\n#             if not cols:\n#                 continue  # Skip if no columns with this suffix\n#             expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n#             expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n#             expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n#             exprs.extend(expr_max + expr_last + expr_mean)\n#         return exprs\n    \n#     @staticmethod\n#     def get_exprs(df):\n#         num_suffixes = (\"P\", \"A\")\n#         date_suffixes = (\"D\",)\n#         str_suffixes = (\"M\",)\n#         other_suffixes = (\"T\", \"L\")\n#         count_suffixes = (\"num_group\",)\n        \n#         exprs = Aggregator.generate_expr(df, num_suffixes)\n#         exprs += Aggregator.generate_expr(df, date_suffixes)\n#         exprs += Aggregator.generate_expr(df, str_suffixes)\n#         exprs += Aggregator.generate_expr(df, other_suffixes)\n#         exprs += Aggregator.generate_expr(df, count_suffixes)\n        \n#         return exprs\n\n\n# 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\n# def 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\n\n# 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\n\n# 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\n\n# def reduce_mem_usage(df):\n#     \"\"\" iterate through all the columns of a dataframe and modify the data type\n#         to reduce memory usage.        \n#     \"\"\"\n#     start_mem = df.memory_usage().sum() / 1024**2\n#     print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n#     for col in df.columns:\n#         col_type = df[col].dtype\n#         if str(col_type)==\"category\":\n#             continue\n        \n#         if col_type != object:\n#             c_min = df[col].min()\n#             c_max = df[col].max()\n#             if str(col_type)[:3] == 'int':\n#                 if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n#                     df[col] = df[col].astype(np.int8)\n#                 elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n#                     df[col] = df[col].astype(np.int16)\n#                 elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n#                     df[col] = df[col].astype(np.int32)\n#                 elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n#                     df[col] = df[col].astype(np.int64)  \n#             else:\n#                 if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n#                     df[col] = df[col].astype(np.float16)\n#                 elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n#                     df[col] = df[col].astype(np.float32)\n#                 else:\n#                     df[col] = df[col].astype(np.float64)\n#         else:\n#             continue\n#     end_mem = df.memory_usage().sum() / 1024**2\n#     print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n#     print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n#     return df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:46:08.479925Z","iopub.execute_input":"2024-05-19T12:46:08.480185Z","iopub.status.idle":"2024-05-19T12:46:08.494178Z","shell.execute_reply.started":"2024-05-19T12:46:08.480163Z","shell.execute_reply":"2024-05-19T12:46:08.493339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### generate_expr Functionality:\n   - Initialize an empty list exprs to hold the expressions.\n   - Iterate over each suffix in the suffixes list.\n   - For each suffix, it collects all columns from the DataFrame whose names end with that suffix.\n   - If no columns are found for a particular suffix,skip to the next suffix.\n   - For the columns with the given suffix,create three types of aggregation expressions:\n       - Maximum value (pl.max)\n       - Last value (pl.last)\n       - Mean value (pl.mean)\n- These expressions are aliased with a prefix (max_, last_, mean_) followed by the original column name.\n- All expressions are added to the exprs list.\n- Return list of expressions.\n\n### generate_expr Functionality:\n - Define several sets of suffixes to be used for different types of columns:\n   - num_suffixes: Suffixes for numerical columns, (\"P\", \"A\").\n   - date_suffixes: Suffixes for date columns, (\"D\",).\n   - str_suffixes: Suffixes for string columns, (\"M\",).\n   - other_suffixes: Suffixes for other types of columns, (\"T\", \"L\").\n   - count_suffixes: Suffixes for columns that represent counts, (\"num_group\",).\n - Call generate_expr for each set of suffixes and concatenate all the resulting expressions into a single list exprs.\n - Return combined list of expressions.\n \n \n\n### feature_eng Functionality\n - with_columns to add two new columns to df_base:\n      - month_decision: Extracts the month from the date_decision column.\n      - weekday_decision: Extracts the weekday from the date_decision column.\n      \n - pl.col(\"date_decision\").dt.month() and pl.col(\"date_decision\").dt.weekday() use Polars' datetime functionality to extract the month and weekday, respectively.\n - Joining Additional DataFrames:\n - iterate over the combined list of DataFrames from depth_0, depth_1, and depth_2.\n - enumerate provides an index i and the DataFrame df for each iteration.\n - Each DataFrame df is joined to df_base using a left join on the case_id column.\n - The suffix parameter adds a suffix _i to the column names of the joined DataFrame to avoid name clashes.","metadata":{}},{"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 in [\"MONTH\"]:\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.7:\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\n\n\nclass Aggregator:\n    @staticmethod\n    def generate_expr(df, suffixes):\n        exprs = []\n        for col_suffix in suffixes:\n            cols = [col for col in df.columns if col.endswith(col_suffix)]\n            if not cols:\n                continue  # Skip if no columns with this suffix\n            expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n            expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n            expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n            exprs.extend(expr_max + expr_last + expr_mean)\n        return exprs\n    \n    @staticmethod\n    def get_exprs(df):\n        num_suffixes = (\"P\", \"A\")\n        date_suffixes = (\"D\",)\n        str_suffixes = (\"M\",)\n        other_suffixes = (\"T\", \"L\")\n        count_suffixes = (\"num_group\",)\n        \n        exprs = Aggregator.generate_expr(df, num_suffixes)\n        exprs += Aggregator.generate_expr(df, date_suffixes)\n        exprs += Aggregator.generate_expr(df, str_suffixes)\n        exprs += Aggregator.generate_expr(df, other_suffixes)\n        exprs += Aggregator.generate_expr(df, count_suffixes)\n        \n        return exprs\n\n\ndef 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\n\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\n\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\n\ndef reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        if str(col_type)==\"category\":\n            continue\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            continue\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:46:08.582240Z","iopub.execute_input":"2024-05-19T12:46:08.582498Z","iopub.status.idle":"2024-05-19T12:46:08.616378Z","shell.execute_reply.started":"2024-05-19T12:46:08.582476Z","shell.execute_reply":"2024-05-19T12:46:08.615549Z"},"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-05-19T12:46:08.618015Z","iopub.execute_input":"2024-05-19T12:46:08.618284Z","iopub.status.idle":"2024-05-19T12:46:08.630286Z","shell.execute_reply.started":"2024-05-19T12:46:08.618262Z","shell.execute_reply":"2024-05-19T12:46:08.629350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\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_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-05-19T12:46:08.631350Z","iopub.execute_input":"2024-05-19T12:46:08.631629Z","iopub.status.idle":"2024-05-19T12:48:27.261154Z","shell.execute_reply.started":"2024-05-19T12:46:08.631607Z","shell.execute_reply":"2024-05-19T12:48:27.260221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### reduce_group(grps):\n    - reduce a group of correlated columns to the single column that has the maximum number of unique values.\n    -  grps -  list of groups, where each group is a list of column names that are highly correlated.\n - Initialize an empty list use to store the selected columns.\n - For each group g in grps, find the column with the maximum number of unique values.\n - Iterate through each column in the group, calculate the number of unique values (nunique) for that column, and keep track of the column with the highest count.\n - The column with the highest count of unique values is appended to the use list.\n \n \n### group_columns_by_correlation(matrix, threshold=0.8):\n   - To group columns of a DataFrame based on their pairwise correlation.\n   - matrix - the DataFrame whose columns are to be grouped.\n   - threshold - the correlation threshold above which columns are considered correlated (default is 0.8).\n\n   - Calculate the correlation matrix of the DataFrame.\n   - initialize an empty list groups to store the groups of correlated columns and a list remaining_cols containing all column names.\n   - iteratively pop a column from remaining_cols, forms a group with columns that are correlated with the popped column above the threshold, and removes these correlated columns from remaining_cols.\n   - formed group is appended to groups.\n\n\n### for k,v in nans_groups.items():\n\n- Perform correlation-based feature reduction on the columns of df_train that are grouped by the number of missing values (NaNs).\n - Initialize an empty list uses to store the final selected columns.\n - Iterate through each item in nans_groups, where k is the number of NaNs and v is the list of columns with k NaNs.\n - If a group v contains more than one column, group the columns by correlation using group_columns_by_correlation and reduces each group to one column using reduce_group.\n - If a group v contains only one column, directly append the column to uses.\n - append categorical columns from df_train to uses.\n - Filter df_train to only include the selected columns in uses.","metadata":{}},{"cell_type":"code","source":"%%time\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ngc.collect()\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\nnums=df_train.select_dtypes(exclude='category').columns\nfrom itertools import combinations, permutations\n#df_train=df_train[nums]\nnans_df = df_train[nums].isna()\nnans_groups={}\nfor col in nums:\n    cur_group = nans_df[col].sum()\n    try:\n        nans_groups[cur_group].append(col)\n    except:\n        nans_groups[cur_group]=[col]\ndel nans_df; x=gc.collect()\n\ndef reduce_group(grps):\n    use = []\n    for g in grps:\n        mx = 0; vx = g[0]\n        for gg in g:\n            n = df_train[gg].nunique()\n            if n>mx:\n                mx = n\n                vx = gg\n            #print(str(gg)+'-'+str(n),', ',end='')\n        use.append(vx)\n        #print()\n    print('Use these',use)\n    return use\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    # 计算列之间的相关性\n    correlation_matrix = matrix.corr()\n\n    # 分组列\n    groups = []\n    remaining_cols = list(matrix.columns)\n    while remaining_cols:\n        col = remaining_cols.pop(0)\n        group = [col]\n        correlated_cols = [col]\n        for c in remaining_cols:\n            if correlation_matrix.loc[col, c] >= threshold:\n                group.append(c)\n                correlated_cols.append(c)\n        groups.append(group)\n        remaining_cols = [c for c in remaining_cols if c not in correlated_cols]\n    \n    return groups\n\nuses=[]\nfor k,v in nans_groups.items():\n    if len(v)>1:\n            Vs = nans_groups[k]\n            #cross_features=list(combinations(Vs, 2))\n            #make_corr(Vs)\n            grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use=reduce_group(grps)\n            uses=uses+use\n            #make_corr(use)\n    else:\n        uses=uses+v\n    print('####### NAN count =',k)\nprint(uses)\nprint(len(uses))\nuses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train=df_train[uses]","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:48:27.262542Z","iopub.execute_input":"2024-05-19T12:48:27.262842Z","iopub.status.idle":"2024-05-19T12:50:11.925093Z","shell.execute_reply.started":"2024-05-19T12:48:27.262816Z","shell.execute_reply":"2024-05-19T12:50:11.924091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv(\"/kaggle/input/home-credit-credit-risk-model-stability/sample_submission.csv\")\ndevice='gpu'\n#n_samples=200000\nn_est=6000\nDRY_RUN = True if sample.shape[0] == 10 else False   \nif DRY_RUN:\n    device='cpu'\n    df_train = df_train.iloc[:50000]\n    #n_samples=10000\n    n_est=600\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:50:11.927431Z","iopub.execute_input":"2024-05-19T12:50:11.927738Z","iopub.status.idle":"2024-05-19T12:50:11.942568Z","shell.execute_reply.started":"2024-05-19T12:50:11.927713Z","shell.execute_reply":"2024-05-19T12:50:11.941616Z"},"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        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-05-19T12:50:11.943800Z","iopub.execute_input":"2024-05-19T12:50:11.944075Z","iopub.status.idle":"2024-05-19T12:50:12.266424Z","shell.execute_reply.started":"2024-05-19T12:50:11.944053Z","shell.execute_reply":"2024-05-19T12:50:12.265415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()\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)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\nweek_num = list(df_test[\"WEEK_NUM\"])\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:50:12.267705Z","iopub.execute_input":"2024-05-19T12:50:12.268000Z","iopub.status.idle":"2024-05-19T12:50:12.776589Z","shell.execute_reply.started":"2024-05-19T12:50:12.267975Z","shell.execute_reply":"2024-05-19T12:50:12.775711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Selection","metadata":{}},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:50:12.777598Z","iopub.execute_input":"2024-05-19T12:50:12.777864Z","iopub.status.idle":"2024-05-19T12:50:12.903738Z","shell.execute_reply.started":"2024-05-19T12:50:12.777841Z","shell.execute_reply":"2024-05-19T12:50:12.902909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)\ndf_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:50:12.904991Z","iopub.execute_input":"2024-05-19T12:50:12.905425Z","iopub.status.idle":"2024-05-19T12:50:13.199804Z","shell.execute_reply.started":"2024-05-19T12:50:12.905394Z","shell.execute_reply":"2024-05-19T12:50:13.198817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,  \n    \"learning_rate\": 0.08,\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\": device, \n    \"verbose\": -1,\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-19T12:50:13.201133Z","iopub.execute_input":"2024-05-19T12:50:13.201465Z","iopub.status.idle":"2024-05-19T12:50:13.206986Z","shell.execute_reply.started":"2024-05-19T12:50:13.201436Z","shell.execute_reply":"2024-05-19T12:50:13.206122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom catboost import CatBoostClassifier, Pool\n\nfitted_models_cat = []\nfitted_models_lgb = []\n\ncv_scores_cat = []\ncv_scores_lgb = []\n\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# \n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n    train_pool = Pool(X_train, y_train,cat_features=cat_cols)\n    val_pool = Pool(X_valid, y_valid,cat_features=cat_cols)\n    clf = CatBoostClassifier(\n    eval_metric='AUC',\n    task_type='GPU',\n    learning_rate=0.03,\n    iterations=n_est)\n    random_seed=3107\n    clf.fit(train_pool, eval_set=val_pool,verbose=300)\n    fitted_models_cat.append(clf)\n    y_pred_valid = clf.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_cat.append(auc_score)\n    \n    \n    X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n    X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\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(100)] )\n    \n    fitted_models_lgb.append(model)\n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_lgb.append(auc_score)\n    \n    \nprint(\"CV AUC scores: \", cv_scores_cat)\nprint(\"Maximum CV AUC score: \", max(cv_scores_cat))\n\n\nprint(\"CV AUC scores: \", cv_scores_lgb)\nprint(\"Maximum CV AUC score: \", max(cv_scores_lgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-19T13:34:27.623368Z","iopub.execute_input":"2024-05-19T13:34:27.624290Z","iopub.status.idle":"2024-05-19T13:34:27.629931Z","shell.execute_reply.started":"2024-05-19T13:34:27.624259Z","shell.execute_reply":"2024-05-19T13:34:27.628852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import gc\n# import lightgbm as lgb\n# from catboost import CatBoostClassifier, Pool\n# from sklearn.metrics import roc_auc_score\n# from sklearn.model_selection import GroupKFold\n\n# def train_models(df_train, y, cat_cols, params, n_est, cv, weeks, random_seed=3107):\n#     # Initialize storage for fitted models and scores\n#     fitted_models_cat = []\n#     fitted_models_lgb = []\n#     cv_scores_cat = []\n#     cv_scores_lgb = []\n    \n#     # Cross-validation\n#     for idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n#         X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]\n#         X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n\n#         # CatBoost training\n#         train_pool = Pool(X_train, y_train, cat_features=cat_cols)\n#         val_pool = Pool(X_valid, y_valid, cat_features=cat_cols)\n#         clf = CatBoostClassifier(\n#             eval_metric='AUC',\n#             task_type='GPU',\n#             learning_rate=0.03,\n#             iterations=n_est,\n#             random_seed=random_seed\n#         )\n#         clf.fit(train_pool, eval_set=val_pool, verbose=300)\n#         fitted_models_cat.append(clf)\n#         y_pred_valid = clf.predict_proba(X_valid)[:, 1]\n#         auc_score = roc_auc_score(y_valid, y_pred_valid)\n#         cv_scores_cat.append(auc_score)\n\n#         # LightGBM training\n#         X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n#         X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\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(100)]\n#         )\n#         fitted_models_lgb.append(model)\n#         y_pred_valid = model.predict_proba(X_valid)[:, 1]\n#         auc_score = roc_auc_score(y_valid, y_pred_valid)\n#         cv_scores_lgb.append(auc_score)\n\n#         # Cleanup\n#         gc.collect()\n\n#     # Output results\n#     print(\"CatBoost CV AUC scores: \", cv_scores_cat)\n#     print(\"Maximum CatBoost CV AUC score: \", max(cv_scores_cat))\n#     print(\"LightGBM CV AUC scores: \", cv_scores_lgb)\n#     print(\"Maximum LightGBM CV AUC score: \", max(cv_scores_lgb))\n\n#     return fitted_models_cat, cv_scores_cat, fitted_models_lgb, cv_scores_lgb\n\n# # Usage\n# cv = GroupKFold(n_splits=5)\n# fitted_models_cat, cv_scores_cat, fitted_models_lgb, cv_scores_lgb = train_models(\n#     df_train, y, cat_cols, params, n_est, cv, weeks\n# )\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T13:36:41.474346Z","iopub.execute_input":"2024-05-19T13:36:41.475074Z","iopub.status.idle":"2024-05-19T13:36:41.487715Z","shell.execute_reply.started":"2024-05-19T13:36:41.475045Z","shell.execute_reply":"2024-05-19T13:36:41.486514Z"},"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        \n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]\n        \n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        y_preds += [estimator.predict_proba(X) for estimator in self.estimators[5:]]\n        \n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models_cat+fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T13:36:11.497955Z","iopub.execute_input":"2024-05-19T13:36:11.498857Z","iopub.status.idle":"2024-05-19T13:36:11.506591Z","shell.execute_reply.started":"2024-05-19T13:36:11.498826Z","shell.execute_reply":"2024-05-19T13:36:11.505558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submision","metadata":{}},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")\n\n\ny_pred = pd.Series(model.predict_proba(df_test)[:, 1], index=df_test.index)\nsubm_df = pd.read_csv(ROOT / \"sample_submission.csv\")\nsubm_df = subm_df.set_index(\"case_id\")\nsubm_df[\"score\"] = y_pred\nsubm_df[\"WEEK_NUM\"] = week_num\ndisplay(subm_df.head())\nprint(\"Check null: \", subm_df[\"score\"].isnull().any())\ncondition = subm_df[\"WEEK_NUM\"] < (subm_df[\"WEEK_NUM\"].max() - subm_df[\"WEEK_NUM\"].min())/2 + subm_df[\"WEEK_NUM\"].min() \nsubm_df.loc[condition, 'score'] = (subm_df.loc[condition, 'score'] - 0.02).clip(0) \nsubm_df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T13:36:13.188079Z","iopub.execute_input":"2024-05-19T13:36:13.188926Z","iopub.status.idle":"2024-05-19T13:36:13.284749Z","shell.execute_reply.started":"2024-05-19T13:36:13.188895Z","shell.execute_reply":"2024-05-19T13:36:13.283450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del subm_df[\"WEEK_NUM\"]\nsubm_df.to_csv(\"submission.csv\")\nsubm_df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:00:39.613516Z","iopub.execute_input":"2024-05-19T15:00:39.613857Z","iopub.status.idle":"2024-05-19T15:00:39.943959Z","shell.execute_reply.started":"2024-05-19T15:00:39.613828Z","shell.execute_reply":"2024-05-19T15:00:39.942802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}