{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"},{"sourceId":8664150,"sourceType":"datasetVersion","datasetId":5189538},{"sourceId":8662844,"sourceType":"datasetVersion","datasetId":5190549},{"sourceId":182697378,"sourceType":"kernelVersion"}],"dockerImageVersionId":30648,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Note: I'm looking for a job in Europe, if you like my work don't hesitate to reach =)\n\nimport 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\nimport joblib  # Save and load Python objects\n\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom sklearn.metrics import roc_auc_score, accuracy_score  # ROC AUC score\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-06-11T05:08:32.952900Z","iopub.execute_input":"2024-06-11T05:08:32.953766Z","iopub.status.idle":"2024-06-11T05:08:35.029244Z","shell.execute_reply.started":"2024-06-11T05:08:32.953726Z","shell.execute_reply":"2024-06-11T05:08:35.027997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pre-Fitted Voting Model","metadata":{}},{"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,predictor=\"gpu_predictor\") 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,predictor=\"gpu_predictor\") for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T01:18:12.543644Z","iopub.execute_input":"2024-06-11T01:18:12.544099Z","iopub.status.idle":"2024-06-11T01:18:12.552760Z","shell.execute_reply.started":"2024-06-11T01:18:12.544066Z","shell.execute_reply":"2024-06-11T01:18:12.551274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pipeline","metadata":{}},{"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","metadata":{"execution":{"iopub.status.busy":"2024-06-10T10:16:33.05012Z","iopub.execute_input":"2024-06-10T10:16:33.050521Z","iopub.status.idle":"2024-06-10T10:16:33.070192Z","shell.execute_reply.started":"2024-06-10T10:16:33.050485Z","shell.execute_reply":"2024-06-10T10:16:33.068942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Automatic Aggregation","metadata":{}},{"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        expr_1 = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        expr_2 = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        cols2 = [col for col in df.columns if col[-1] in (\"A\")]\n        expr_3 = [pl.mean(col).alias(f\"mean_{col}\") for col in cols2] + [pl.std(col).alias(f\"std_{col}\") for col in cols2] + \\\n            [pl.sum(col).alias(f\"sum_{col}\") for col in cols2]\n        return expr_1 + expr_2 + expr_3\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        expr_min = [\n            pl.min(col).alias(f\"min_{col}\") for col in cols\n            if col not in [\n                'empl_employedfrom_271D',\n                'recorddate_4527225D',\n            ]\n        ]\n        return expr_max + expr_min\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        expr_mode = []\n        for col in cols:\n            if df[col].dtype == pl.String:\n                mode1 = pl.col(col).drop_nulls().mode().max()\n                # mode2 = pl.col(col).filter(pl.col(col) != mode1).mode().first()\n                expr_mode.append(mode1.alias(f\"mode1_{col}\"))\n        \n        return expr_max + expr_mode\n\n    @staticmethod\n    def other_expr(df):\n        redundant_cols = [\n            'pmts_month_158T',\n            'pmts_year_1139T',\n            'pmts_month_706T',\n            'dpdmaxdateyear_596T',\n            'overdueamountmaxdatemonth_284T',\n            'overdueamountmaxdatemonth_365T',\n            'dpdmaxdatemonth_89T',\n            'dpdmaxdatemonth_442T',\n\n            'contractssum_5085716L',\n            'applicationscnt_629L',\n            'clientscnt_1130L',\n            'clientscnt_360L',\n            'clientscnt_533L',\n            'clientscnt_887L',\n            'clientscnt_946L',\n            'numinstpaidlastcontr_4325080L',\n            'numnotactivated_1143L',\n            'contaddr_smempladdr_334L',\n            'type_25L',\n\n            # only 1 unique value\n            'personindex_1023L',\n            'persontype_1072L',\n            'persontype_792L',\n\n            # only 2 unique values\n            'contaddr_matchlist_1032L',  # [null, false]\n            'remitter_829L',             # [ 0. null]\n\n            # duplicates\n            'tenor_203L',  # ~ pmtnum_8L\n            \n            # score decrease\n            'periodicityofpmts_837L',\n            'overdueamountmaxdateyear_2T',\n            'numberofoutstandinstls_59L',\n            'annualeffectiverate_63L',\n            'pmtnum_8L',\n            'status_219L',\n        ]\n\n        cols = [\n            col for col in df.columns\n            if (col[-1] in (\"T\",\"L\")) and (col not in redundant_cols)\n        ]\n        \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        return expr_max + expr_last\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        if \"num_group2\" not in df.columns:\n            expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n            return expr_max + expr_last\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-06-10T10:16:33.071997Z","iopub.execute_input":"2024-06-10T10:16:33.07264Z","iopub.status.idle":"2024-06-10T10:16:33.085607Z","shell.execute_reply.started":"2024-06-10T10:16:33.072605Z","shell.execute_reply":"2024-06-10T10:16:33.084545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### File I/O","metadata":{}},{"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-06-10T10:16:33.088918Z","iopub.execute_input":"2024-06-10T10:16:33.089363Z","iopub.status.idle":"2024-06-10T10:16:33.099148Z","shell.execute_reply.started":"2024-06-10T10:16:33.089327Z","shell.execute_reply":"2024-06-10T10:16:33.098139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Engineering","metadata":{}},{"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-06-10T10:16:33.10034Z","iopub.execute_input":"2024-06-10T10:16:33.100741Z","iopub.status.idle":"2024-06-10T10:16:33.110311Z","shell.execute_reply.started":"2024-06-10T10:16:33.100704Z","shell.execute_reply":"2024-06-10T10:16:33.109199Z"},"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-06-10T10:16:33.11169Z","iopub.execute_input":"2024-06-10T10:16:33.112485Z","iopub.status.idle":"2024-06-10T10:16:33.123957Z","shell.execute_reply.started":"2024-06-10T10:16:33.112448Z","shell.execute_reply":"2024-06-10T10:16:33.122916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"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    \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    return df","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Configuration","metadata":{}},{"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-06-10T10:16:33.125399Z","iopub.execute_input":"2024-06-10T10:16:33.126006Z","iopub.status.idle":"2024-06-10T10:16:33.133382Z","shell.execute_reply.started":"2024-06-10T10:16:33.125968Z","shell.execute_reply":"2024-06-10T10:16:33.132398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train Files Read & Feature Engineering","metadata":{}},{"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-06-10T10:34:02.589304Z","iopub.execute_input":"2024-06-10T10:34:02.591926Z","iopub.status.idle":"2024-06-10T10:36:21.166995Z","shell.execute_reply.started":"2024-06-10T10:34:02.59186Z","shell.execute_reply":"2024-06-10T10:36:21.165192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\n\ndel data_store\ngc.collect()\n\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_train, cat_cols = to_pandas(df_train)\n\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T10:18:42.310063Z","iopub.execute_input":"2024-06-10T10:18:42.310423Z","iopub.status.idle":"2024-06-10T10:18:57.390888Z","shell.execute_reply.started":"2024-06-10T10:18:42.310395Z","shell.execute_reply":"2024-06-10T10:18:57.389799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nums=df_train.select_dtypes(exclude='category').columns\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        use.append(vx)\n    return use\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    correlation_matrix = matrix.corr()\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            grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use=reduce_group(grps)\n            uses=uses+use\n    else:\n        uses=uses+v\n\n# Subset the DataFrame to keep only the selected columns\ndf_train = df_train[uses + cat_cols]  \n\nprint(\"train data shape after correlation-based reduction :\\t\", df_train.shape)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train=reduce_mem_usage(df_train)\nprint(\"memery usage after reduction:\",df_train.memory_usage().sum() / 1024**2)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Test Files Read & Feature Engineering","metadata":{}},{"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-06-10T10:18:57.392438Z","iopub.execute_input":"2024-06-10T10:18:57.392774Z","iopub.status.idle":"2024-06-10T10:18:58.066839Z","shell.execute_reply.started":"2024-06-10T10:18:57.392746Z","shell.execute_reply":"2024-06-10T10:18:58.065828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\n\ndel data_store\ngc.collect()\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T01:18:01.664066Z","iopub.execute_input":"2024-06-11T01:18:01.665233Z","iopub.status.idle":"2024-06-11T01:18:02.062490Z","shell.execute_reply.started":"2024-06-11T01:18:01.665195Z","shell.execute_reply":"2024-06-11T01:18:02.060793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Elimination","metadata":{}},{"cell_type":"code","source":"df_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T10:18:58.115326Z","iopub.execute_input":"2024-06-10T10:18:58.115724Z","iopub.status.idle":"2024-06-10T10:19:01.319923Z","shell.execute_reply.started":"2024-06-10T10:18:58.115678Z","shell.execute_reply":"2024-06-10T10:19:01.318811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pandas Conversion","metadata":{}},{"cell_type":"code","source":"df_test, cat_cols = to_pandas(df_test, cat_cols)\n\ngc.collect()\n\ndf_test=reduce_mem_usage(df_test)\nprint(\"test set memery usage after reduction:\",df_test.memory_usage().sum() / 1024**2)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T10:19:01.323396Z","iopub.execute_input":"2024-06-10T10:19:01.323745Z","iopub.status.idle":"2024-06-10T10:19:15.837592Z","shell.execute_reply.started":"2024-06-10T10:19:01.323718Z","shell.execute_reply":"2024-06-10T10:19:15.836663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# process inconsistences between df_train, df_val, and df_test\ndef convert_cols_cat_add_Unknown(*dfs):\n    # List of columns of the tuple of dataframes that are of type \"object\" in at least\n    # one of the dataframes\n    cat_cols = dfs[0].select_dtypes(include=['category']).columns\n    # For each column of dtype \"object\"\n    for col in cat_cols:\n        # For each dataframe of the tuple\n        for df in dfs:\n            # Convert current column to dtype \"category\"\n            # New categorical dtype whose categories correspond to the ones of the\n            # current column and the category \"Unknown\", being ordered\n            new_dtype = pd.CategoricalDtype(categories=list(set(df[col].cat.categories.to_list() +\n                                            [\"Unknown\"])),\n                                            ordered=True)\n            # Assign new dtype to current column\n            df[col] = df[col].astype(new_dtype)\n            df[col].fillna('Unknown', inplace=True)\n    return dfs\n\ndef make_cat_excl_unknown(df, df_ref):\n    # For each categorical column of the reference pandas dataframe\n    for col in df_ref.select_dtypes(include=[\"category\"]).columns:\n        # List of categories in the reference pandas dataframe\n        cat_ref = df_ref[col].cat.categories.to_list()\n        # List of categories in the pandas dataframe of interest\n        cat = df[col].cat.categories.to_list()\n        \n        # List of exclusive categories\n        cat_exc = list(set(cat).difference(cat_ref))\n        # New categorical dtype whose categories correspond to the ref ones\n        new_dtype = pd.CategoricalDtype(categories=cat_ref,\n                                        ordered=True)\n        # Replace current column's entries associated with exclusive categories as\n        # \"Unknown\"\n        df[col] = df[col].replace(to_replace=cat_exc, value=\"Unknown\")\n        # Assign the new dtype to the current column\n        df[col] = df[col].astype(new_dtype)\n    return df","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, df_test = convert_cols_cat_add_Unknown(df_train, df_test)\n\ndf_test = make_cat_excl_unknown(df= df_test, df_ref= df_train)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Load models","metadata":{}},{"cell_type":"code","source":"! ls /kaggle/input/","metadata":{"execution":{"iopub.status.busy":"2024-06-11T01:18:45.065041Z","iopub.execute_input":"2024-06-11T01:18:45.065445Z","iopub.status.idle":"2024-06-11T01:18:46.104485Z","shell.execute_reply.started":"2024-06-11T01:18:45.065418Z","shell.execute_reply":"2024-06-11T01:18:46.102968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = Path(\"/kaggle/input/lgb-gbdt5-goss5\")/ \"model_lgb_gbdt.pkl\"\nmodel_lgb_gbdt = joblib.load(model_path)\nmodel_path = Path(\"/kaggle/input/lgb-gbdt5-goss5\")/ \"model_lgb_goss.pkl\"\nmodel_lgb_goss = joblib.load(model_path)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T01:19:05.536062Z","iopub.execute_input":"2024-06-11T01:19:05.536635Z","iopub.status.idle":"2024-06-11T01:19:05.771385Z","shell.execute_reply.started":"2024-06-11T01:19:05.536596Z","shell.execute_reply":"2024-06-11T01:19:05.770110Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# catboost\nfrom catboost import CatBoostClassifier, Pool\n\nclass VotingModel_cat(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-06-11T05:08:53.225972Z","iopub.execute_input":"2024-06-11T05:08:53.226420Z","iopub.status.idle":"2024-06-11T05:08:53.236430Z","shell.execute_reply.started":"2024-06-11T05:08:53.226383Z","shell.execute_reply":"2024-06-11T05:08:53.234919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = Path(\"/kaggle/input/my-cat\")/ \"model_cat_1.pkl\"\ncat_model= joblib.load(model_path)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T05:09:33.820821Z","iopub.execute_input":"2024-06-11T05:09:33.821235Z","iopub.status.idle":"2024-06-11T05:09:37.025753Z","shell.execute_reply.started":"2024-06-11T05:09:33.821200Z","shell.execute_reply":"2024-06-11T05:09:37.024635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction","metadata":{}},{"cell_type":"code","source":"# df_test.drop(columns=[\"case_id\"]).to_csv('test_data.csv', index=False)\n# del df_test\n# gc.collect()\n# def set_categoricals(df_data, cat_cols):\n#     df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n#     return df_data","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict_proba(X_test):\n    weight = [0.3,0.4,0.3]\n    y=0\n    for i, submodel in enumerate([cat_model, model_lgb_goss, model_lgb_gbdt]):\n        y = y+ weight[i]*submodel.predict_proba(X_test)\n    return y\n    ","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\ny_pred = pd.Series(predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T05:10:00.551175Z","iopub.execute_input":"2024-06-11T05:10:00.551614Z","iopub.status.idle":"2024-06-11T05:10:00.655181Z","shell.execute_reply.started":"2024-06-11T05:10:00.551578Z","shell.execute_reply":"2024-06-11T05:10:00.653676Z"},"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\"] = y_pred","metadata":{"execution":{"iopub.status.busy":"2024-06-10T10:20:05.646759Z","iopub.status.idle":"2024-06-10T10:20:05.647099Z","shell.execute_reply.started":"2024-06-10T10:20:05.646936Z","shell.execute_reply":"2024-06-10T10:20:05.64695Z"},"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-06-10T10:20:05.648163Z","iopub.status.idle":"2024-06-10T10:20:05.648546Z","shell.execute_reply.started":"2024-06-10T10:20:05.64836Z","shell.execute_reply":"2024-06-10T10:20:05.648375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-06-10T10:20:05.649729Z","iopub.status.idle":"2024-06-10T10:20:05.650058Z","shell.execute_reply.started":"2024-06-10T10:20:05.649897Z","shell.execute_reply":"2024-06-10T10:20:05.649911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}