{"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":8666103,"sourceType":"datasetVersion","datasetId":5192343}],"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-12T12:56:46.891019Z","iopub.execute_input":"2024-06-12T12:56:46.891321Z","iopub.status.idle":"2024-06-12T12:56:53.023392Z","shell.execute_reply.started":"2024-06-12T12:56:46.891294Z","shell.execute_reply":"2024-06-12T12:56:53.022651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pre-Fitted Voting Model","metadata":{}},{"cell_type":"code","source":"!ls /kaggle/input","metadata":{"execution":{"iopub.status.busy":"2024-06-12T12:56:53.024971Z","iopub.execute_input":"2024-06-12T12:56:53.025248Z","iopub.status.idle":"2024-06-12T12:56:53.973652Z","shell.execute_reply.started":"2024-06-12T12:56:53.025224Z","shell.execute_reply":"2024-06-12T12:56:53.972767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, ClassifierMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X,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-12T12:56:53.974975Z","iopub.execute_input":"2024-06-12T12:56:53.975270Z","iopub.status.idle":"2024-06-12T12:56:53.982919Z","shell.execute_reply.started":"2024-06-12T12:56:53.975243Z","shell.execute_reply":"2024-06-12T12:56:53.982113Z"},"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-12T12:56:53.985053Z","iopub.execute_input":"2024-06-12T12:56:53.985358Z","iopub.status.idle":"2024-06-12T12:56:53.999209Z","shell.execute_reply.started":"2024-06-12T12:56:53.985335Z","shell.execute_reply":"2024-06-12T12:56:53.998367Z"},"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-12T12:56:54.000508Z","iopub.execute_input":"2024-06-12T12:56:54.000858Z","iopub.status.idle":"2024-06-12T12:56:54.019686Z","shell.execute_reply.started":"2024-06-12T12:56:54.000834Z","shell.execute_reply":"2024-06-12T12:56:54.018787Z"},"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-12T12:56:54.020721Z","iopub.execute_input":"2024-06-12T12:56:54.021039Z","iopub.status.idle":"2024-06-12T12:56:54.035402Z","shell.execute_reply.started":"2024-06-12T12:56:54.021018Z","shell.execute_reply":"2024-06-12T12:56:54.034470Z"},"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-12T12:56:54.036717Z","iopub.execute_input":"2024-06-12T12:56:54.037062Z","iopub.status.idle":"2024-06-12T12:56:54.046876Z","shell.execute_reply.started":"2024-06-12T12:56:54.037032Z","shell.execute_reply":"2024-06-12T12:56:54.045888Z"},"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-12T12:56:54.048046Z","iopub.execute_input":"2024-06-12T12:56:54.048416Z","iopub.status.idle":"2024-06-12T12:56:54.055428Z","shell.execute_reply.started":"2024-06-12T12:56:54.048386Z","shell.execute_reply":"2024-06-12T12:56:54.054560Z"},"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":{"iopub.status.busy":"2024-06-12T12:56:54.056524Z","iopub.execute_input":"2024-06-12T12:56:54.057149Z","iopub.status.idle":"2024-06-12T12:56:54.071290Z","shell.execute_reply.started":"2024-06-12T12:56:54.057125Z","shell.execute_reply":"2024-06-12T12:56:54.070460Z"},"trusted":true},"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-12T12:56:54.075690Z","iopub.execute_input":"2024-06-12T12:56:54.076110Z","iopub.status.idle":"2024-06-12T12:56:54.082608Z","shell.execute_reply.started":"2024-06-12T12:56:54.076080Z","shell.execute_reply":"2024-06-12T12:56:54.081679Z"},"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-12T12:56:54.083696Z","iopub.execute_input":"2024-06-12T12:56:54.083956Z","iopub.status.idle":"2024-06-12T13:01:46.210976Z","shell.execute_reply.started":"2024-06-12T12:56:54.083935Z","shell.execute_reply":"2024-06-12T13:01:46.210102Z"},"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-12T13:01:46.212106Z","iopub.execute_input":"2024-06-12T13:01:46.212386Z","iopub.status.idle":"2024-06-12T13:02:40.059540Z","shell.execute_reply.started":"2024-06-12T13:01:46.212360Z","shell.execute_reply":"2024-06-12T13:02:40.058451Z"},"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":{"iopub.status.busy":"2024-06-12T13:02:40.060913Z","iopub.execute_input":"2024-06-12T13:02:40.061215Z","iopub.status.idle":"2024-06-12T13:03:15.905530Z","shell.execute_reply.started":"2024-06-12T13:02:40.061189Z","shell.execute_reply":"2024-06-12T13:03:15.904645Z"},"trusted":true},"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":{"iopub.status.busy":"2024-06-12T13:03:15.906989Z","iopub.execute_input":"2024-06-12T13:03:15.907272Z","iopub.status.idle":"2024-06-12T13:03:24.039412Z","shell.execute_reply.started":"2024-06-12T13:03:15.907248Z","shell.execute_reply":"2024-06-12T13:03:24.038496Z"},"trusted":true},"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-12T13:03:24.040687Z","iopub.execute_input":"2024-06-12T13:03:24.041393Z","iopub.status.idle":"2024-06-12T13:03:24.386511Z","shell.execute_reply.started":"2024-06-12T13:03:24.041358Z","shell.execute_reply":"2024-06-12T13:03:24.383430Z"},"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-12T13:03:24.388134Z","iopub.execute_input":"2024-06-12T13:03:24.389339Z","iopub.status.idle":"2024-06-12T13:03:24.582013Z","shell.execute_reply.started":"2024-06-12T13:03:24.389298Z","shell.execute_reply":"2024-06-12T13:03:24.581155Z"},"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-12T13:03:24.583268Z","iopub.execute_input":"2024-06-12T13:03:24.583659Z","iopub.status.idle":"2024-06-12T13:03:24.591697Z","shell.execute_reply.started":"2024-06-12T13:03:24.583605Z","shell.execute_reply":"2024-06-12T13:03:24.590777Z"},"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-12T13:03:24.592958Z","iopub.execute_input":"2024-06-12T13:03:24.593286Z","iopub.status.idle":"2024-06-12T13:03:24.933799Z","shell.execute_reply.started":"2024-06-12T13:03:24.593255Z","shell.execute_reply":"2024-06-12T13:03:24.932844Z"},"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":{"iopub.status.busy":"2024-06-12T13:03:24.935446Z","iopub.execute_input":"2024-06-12T13:03:24.935772Z","iopub.status.idle":"2024-06-12T13:03:24.945739Z","shell.execute_reply.started":"2024-06-12T13:03:24.935747Z","shell.execute_reply":"2024-06-12T13:03:24.944845Z"},"trusted":true},"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":{"iopub.status.busy":"2024-06-12T13:03:24.946669Z","iopub.execute_input":"2024-06-12T13:03:24.946931Z","iopub.status.idle":"2024-06-12T13:03:26.237778Z","shell.execute_reply.started":"2024-06-12T13:03:24.946909Z","shell.execute_reply":"2024-06-12T13:03:26.236943Z"},"trusted":true},"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-12T13:03:26.238914Z","iopub.execute_input":"2024-06-12T13:03:26.239210Z","iopub.status.idle":"2024-06-12T13:03:27.280636Z","shell.execute_reply.started":"2024-06-12T13:03:26.239184Z","shell.execute_reply":"2024-06-12T13:03:27.279476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = Path(\"/kaggle/input/models-for-credict\")/ \"model_lgb_gbdt.pkl\"\nmodel_lgb_gbdt = joblib.load(model_path)\nmodel_path = Path(\"/kaggle/input/models-for-credict\")/ \"model_lgb_goss.pkl\"\nmodel_lgb_goss = joblib.load(model_path)\nmodel_path = Path(\"/kaggle/input/models-for-credict\")/ \"model_lgb_gbdt_et.pkl\"\nmodel_lgb_gbdt_et = joblib.load(model_path)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T13:03:27.282147Z","iopub.execute_input":"2024-06-12T13:03:27.282453Z","iopub.status.idle":"2024-06-12T13:03:29.064851Z","shell.execute_reply.started":"2024-06-12T13:03:27.282425Z","shell.execute_reply":"2024-06-12T13:03:29.063936Z"},"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-12T13:03:29.066005Z","iopub.execute_input":"2024-06-12T13:03:29.066347Z","iopub.status.idle":"2024-06-12T13:03:29.398657Z","shell.execute_reply.started":"2024-06-12T13:03:29.066317Z","shell.execute_reply":"2024-06-12T13:03:29.397762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = Path(\"/kaggle/input/models-for-credict\")/ \"model_cat_1.pkl\"\ncat_model= joblib.load(model_path)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T13:03:29.399949Z","iopub.execute_input":"2024-06-12T13:03:29.400592Z","iopub.status.idle":"2024-06-12T13:03:32.287494Z","shell.execute_reply.started":"2024-06-12T13:03:29.400559Z","shell.execute_reply":"2024-06-12T13:03:32.286499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# XGBoost\nimport xgboost as xgb\nmodel_path = Path(\"/kaggle/input/models-for-credict\")/ \"xgb_model0.pkl\"\nxgb_model0= joblib.load(model_path)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T13:03:32.289054Z","iopub.execute_input":"2024-06-12T13:03:32.289356Z","iopub.status.idle":"2024-06-12T13:03:33.457474Z","shell.execute_reply.started":"2024-06-12T13:03:32.289331Z","shell.execute_reply":"2024-06-12T13:03:33.456535Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Build stacking model.","metadata":{}},{"cell_type":"code","source":"def get_stability_score(\n    dt_base,\n    # Weight for average (in week number) of Gini coefficient\n    w_G_av=1,\n    # Weight for the slope of the Gini coefficient (if negative)\n    w_a=88.0,\n    # Weight for the root mean square deviation of the linear regression Gini\n    # coefficients from the actual ones\n    w_RMSD=-0.5\n):\n    # List of Gini coefficients - one for each week number\n    # [NOTE: the base pandas dataframe is sorted and grouped by WEEK_NUM. The respective\n    # lists of labels (y) and predicted probabilities (P_pred) for each week number are\n    # taken and a respective Gini coefficient is computed.]\n    G = dt_base[[\"WEEK_NUM\", \"target\", \"P_pred\"]]\\\n        .sort_values(by=\"WEEK_NUM\")\\\n        .groupby(by=\"WEEK_NUM\")[[\"target\", \"P_pred\"]]\\\n        .apply(lambda x:\n               2 * roc_auc_score(x[\"target\"], x[\"P_pred\"]) - 1).tolist()\n    \n    # Average (in week number) Gini coefficient\n    G_av = np.mean(G)\n\n    # Array of indices for the Gini coefficients\n    i = np.arange(len(G))\n    \n    # Weight (a) and bias (_) of the linear regression\n    [a, b] = np.polyfit(x=i, y=G, deg=1)\n    \n    # Array of fit Gini coefficients\n    G_fit = a * i + b\n    \n    # Root mean square deviation of the fit Gini values from the actual ones \n    RMSD = np.sqrt(np.mean((G_fit - G)**2))\n\n    # Stability score\n    stability_score = w_G_av * G_av + w_a * min(0, a) + w_RMSD * RMSD\n    \n    # Dictionary of stability score elements\n    dt = {\n        \"g_week\": G,\n        \"a\": a,\n        \"b\": b,\n        \"RMSD\": RMSD,\n        \"stability_score\": stability_score\n    }\n    \n    return dt","metadata":{"execution":{"iopub.status.busy":"2024-06-12T13:03:33.458517Z","iopub.execute_input":"2024-06-12T13:03:33.458805Z","iopub.status.idle":"2024-06-12T13:03:33.467527Z","shell.execute_reply.started":"2024-06-12T13:03:33.458780Z","shell.execute_reply":"2024-06-12T13:03:33.466641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.ensemble import VotingClassifier, VotingRegressor\nfrom sklearn.linear_model import LinearRegression","metadata":{"execution":{"iopub.status.busy":"2024-06-12T13:03:33.468827Z","iopub.execute_input":"2024-06-12T13:03:33.469115Z","iopub.status.idle":"2024-06-12T13:03:33.664325Z","shell.execute_reply.started":"2024-06-12T13:03:33.469092Z","shell.execute_reply":"2024-06-12T13:03:33.663479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"N_train_old = len(df_train)\n\n# shuffle\ndf_train =  df_train.sample(frac=1, random_state=42).reset_index(drop=True)\n\ndf_val = df_train.head(int(N_train_old*0.2))\ndf_train = df_train.tail(N_train_old - len(df_val))\n\nprint(f\"num of train set: {len(df_train)}, num of val set: {len(df_val)}\")","metadata":{"execution":{"iopub.status.busy":"2024-06-12T13:03:33.668563Z","iopub.execute_input":"2024-06-12T13:03:33.668879Z","iopub.status.idle":"2024-06-12T13:03:41.111833Z","shell.execute_reply.started":"2024-06-12T13:03:33.668856Z","shell.execute_reply":"2024-06-12T13:03:41.110712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"estimators = [\n    ('m1', model_lgb_gbdt),\n    ('m2', model_lgb_goss),\n    ('m3', model_lgb_gbdt_et),\n    ('m4', cat_model),\n    ('m5', xgb_model0)\n] \ndf_base = df_train[[\"case_id\",\"WEEK_NUM\",\"target\"]].copy(deep=True)\nX=df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\nfor model_name, model in estimators:\n    df_base[model_name] = model.predict_proba(X)[:,1]\n\ndel X","metadata":{"execution":{"iopub.status.busy":"2024-06-12T14:59:41.132313Z","iopub.execute_input":"2024-06-12T14:59:41.133107Z","iopub.status.idle":"2024-06-12T15:44:25.130086Z","shell.execute_reply.started":"2024-06-12T14:59:41.133073Z","shell.execute_reply":"2024-06-12T15:44:25.129199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_base_test = df_base.copy(deep=True)\nfor i in range(5):\n    df_base_test[\"P_pred\"] = df_base_test[f\"m{i+1}\"]\n    print(f\"auc on m{i+1}:\", roc_auc_score(df_base_test[\"target\"],df_base_test[\"P_pred\"]))\n    print(f\"stability score:\", get_stability_score(df_base_test)['stability_score'])\n","metadata":{"execution":{"iopub.status.busy":"2024-06-12T18:04:19.665166Z","iopub.execute_input":"2024-06-12T18:04:19.665540Z","iopub.status.idle":"2024-06-12T18:04:25.241667Z","shell.execute_reply.started":"2024-06-12T18:04:19.665502Z","shell.execute_reply":"2024-06-12T18:04:25.240697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(df_base)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T15:45:25.002157Z","iopub.execute_input":"2024-06-12T15:45:25.003123Z","iopub.status.idle":"2024-06-12T15:45:25.009973Z","shell.execute_reply.started":"2024-06-12T15:45:25.003080Z","shell.execute_reply":"2024-06-12T15:45:25.008998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"'m5': 0.02, # xgb\n        'm4': 0.001,\n        'm3': 0.001,\n        'm2': 0.00,\n        'm1': 0.00,\n n_split=7  seed=0   0.693\n \n \n 'm5': 0.001, # xgb\n        'm4': 0.01,\n        'm3': 0.01,\n        'm2': 0.00,\n        'm1': 0.00,\n n_split=8  seed=8   0.75        \n \n 'm5': 0.001, # xgb\n        'm4': 0.02,\n        'm3': 0.01,\n        'm2': 0.00,\n        'm1': 0.00,\n n_split=8  seed=8   0.77     \n \n \n 'm5': 0.001, # xgb\n        'm4': 0.04,\n        'm3': 0.02,\n        'm2': 0.001,\n        'm1': 0.001,\n  n_split=8  seed=8   0.779  \n ","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def add_noise(df, col_noise_dict={}):\n    for col, noise in col_noise_dict.items():\n        if noise == 0:\n            continue\n        np.random.seed(8)\n        mu, sigma = 0, noise\n        noise = np.random.normal(mu, sigma, df.shape[0])\n        df[col] += noise\n        print(\"noise added:\", col)\n    return df\n\nX_data = df_base[[\"m1\",\"m2\",\"m3\",\"m4\",\"m5\"]].copy(deep=True)\ny_data = df_base['target']\nweeks = df_base[\"WEEK_NUM\"]\n\nX_data = add_noise(\n    X_data, \n    {\n        'm5': 0.04, # xgb\n        'm4': 0.06,\n        'm3': 0.03,\n        'm2': 0.01,\n        'm1': 0.01,\n    }\n)\n\n\nfitted_models = []\npred_meta = np.zeros(X_data.shape[0])\ncoef = 0\ncv = StratifiedGroupKFold(n_splits=8, shuffle=True, random_state=0)\nfor i, (idx_train, idx_valid) in enumerate(cv.split(X_data, y_data, groups=weeks)):\n    print(\"Fold:\", i)\n    X_train, y_train = X_data.iloc[idx_train], y_data.iloc[idx_train]\n    X_valid, y_valid = X_data.iloc[idx_valid], y_data.iloc[idx_valid]\n\n    meta_cls = LinearRegression()\n    meta_cls.fit(X_train, y_train)\n    val_pred_meta = meta_cls.predict(X_valid)\n    fitted_models.append(meta_cls)\n    pred_meta[idx_valid] += val_pred_meta\n    print(\"  lin_reg coef:\", meta_cls.coef_)\n    coef = coef + meta_cls.coef_\n    del X_train, X_valid\n    gc.collect()\nprint(coef/8)\nmeta_cls = VotingRegressor(\n    estimators=[(str(i), model) for i, model in enumerate(fitted_models)],\n)\nmeta_cls.estimators_ = fitted_models\n\ndf_base[\"P_pred\"]= pred_meta\nprint(len(pred_meta))\nprint(\"CV_auc\", roc_auc_score(y_data, pred_meta))\nprint(\"stability_score:\",get_stability_score(df_base))\n","metadata":{"execution":{"iopub.status.busy":"2024-06-12T17:46:20.824530Z","iopub.execute_input":"2024-06-12T17:46:20.825392Z","iopub.status.idle":"2024-06-12T17:46:31.556973Z","shell.execute_reply.started":"2024-06-12T17:46:20.825360Z","shell.execute_reply":"2024-06-12T17:46:31.555867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(df_base)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T16:03:43.480566Z","iopub.execute_input":"2024-06-12T16:03:43.481726Z","iopub.status.idle":"2024-06-12T16:03:43.490103Z","shell.execute_reply.started":"2024-06-12T16:03:43.481680Z","shell.execute_reply":"2024-06-12T16:03:43.488432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def cus_predict(x_df):\n#     w = [1.41964115,  1.12046925, -1.0480074,  -0.23721046, 0.20816517]\n    w = [1.4384324 ,  1.1473338,  -1.20595824, -0.42358804,  0.51934344]\n    weight = np.exp(np.array(w))\n    weight = weight/np.sum(weight)\n    w =weight\n    print(w)\n    x = [x_df[\"m1\"],x_df[\"m2\"], x_df[\"m3\"], x_df[\"m4\"] ,x_df[\"m5\"]]\n    p = 0\n    for i in range(len(w)):\n        p=p+ w[i]*x[i]\n    return p","metadata":{"execution":{"iopub.status.busy":"2024-06-12T17:46:59.059601Z","iopub.execute_input":"2024-06-12T17:46:59.059977Z","iopub.status.idle":"2024-06-12T17:46:59.066423Z","shell.execute_reply.started":"2024-06-12T17:46:59.059949Z","shell.execute_reply":"2024-06-12T17:46:59.065373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_meta = df_bases_val[0][[\"m1\",\"m2\",\"m3\",\"m4\",\"m5\"]].copy(deep=True)\nX_meta = add_noise(\n        X_meta, \n        {\n            'm5': 0., # xgb\n            'm4': 0.,\n            'm3': 0.,\n            'm2': 0.,\n            'm1': 0.,\n        }\n    )\n# df_bases_val[0][\"P_pred\"] = meta_cls.predict(X_meta)\ndf_bases_val[0][\"P_pred\"] = cus_predict(X_meta)\nprint(len(X_meta))\nprint(\"auc:\", roc_auc_score(df_bases_val[0][\"target\"], df_bases_val[0][\"P_pred\"]))\nprint(\"stability_score:\",get_stability_score(df_bases_val[0]))","metadata":{"execution":{"iopub.status.busy":"2024-06-12T17:47:04.650868Z","iopub.execute_input":"2024-06-12T17:47:04.651558Z","iopub.status.idle":"2024-06-12T17:47:05.071892Z","shell.execute_reply.started":"2024-06-12T17:47:04.651519Z","shell.execute_reply":"2024-06-12T17:47:05.070687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_bases_val = []\nfor df in  [df_val]:\n    df_base_val = df[[\"case_id\",\"WEEK_NUM\",\"target\"]]\n    X_val= df.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n    for model_name, model in estimators:\n        df_base_val[model_name] = model.predict_proba(X_val)[:,1]\n    X_meta = df_base_val[[\"m1\",\"m2\",\"m3\",\"m4\",\"m5\"]].copy(deep=True)\n    X_meta = add_noise(\n        X_meta, \n        {\n            'm5': 0.028, # xgb\n            'm4': 0.004,\n            'm3': 0.004,\n            'm2': 0.004,\n            'm1': 0.004\n        }\n    )\n    \n    df_base_val[\"P_pred\"] = meta_cls.predict(X_meta)\n    df_bases_val.append(df_base_val)\n    auc = roc_auc_score(\n            y_true=df[\"target\"],\n            y_score=df_base_val[\"P_pred\"]\n        )\n    gini = 2*auc - 1\n    print(\"auc, gini =\", auc, gini)\n    print(\"stability_score:\",get_stability_score(df_base_val))","metadata":{"execution":{"iopub.status.busy":"2024-06-12T15:49:10.263810Z","iopub.execute_input":"2024-06-12T15:49:10.264472Z","iopub.status.idle":"2024-06-12T16:00:53.558120Z","shell.execute_reply.started":"2024-06-12T15:49:10.264440Z","shell.execute_reply":"2024-06-12T16:00:53.557152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_base_test = df_base_val.copy(deep=True)\nfor i in range(5):\n    df_base_test[\"P_pred\"] = df_base_test[f\"m{i+1}\"]\n    print(f\"auc on m{i+1}:\", roc_auc_score(df_base_test[\"target\"],df_base_test[\"P_pred\"]))\n    print(f\"stability score:\", get_stability_score(df_base_test)['stability_score'])","metadata":{"execution":{"iopub.status.busy":"2024-06-12T18:05:24.291060Z","iopub.execute_input":"2024-06-12T18:05:24.291991Z","iopub.status.idle":"2024-06-12T18:05:26.159806Z","shell.execute_reply.started":"2024-06-12T18:05:24.291956Z","shell.execute_reply":"2024-06-12T18:05:26.158875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_bases = []\n# for df in [df_val]:\n#     df_base = df[[\"case_id\",\"WEEK_NUM\",\"target\"]]\n#     X_val= df.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n#     P_pred = model_lgb_gbdt_et.predict_proba(X_val)[:,1]\n#     df_base[\"P_pred\"] = P_pred\n#     df_bases.append(df_base)\n#     y_pred = (P_pred >= 0.5).astype(dtype=\"int32\")\n#     accuracy = accuracy_score(\n#             y_true=df[\"target\"],\n#             y_pred=y_pred\n#         )\n#     auc = roc_auc_score(\n#             y_true=df[\"target\"],\n#             y_score=P_pred\n#         )\n#     gini = 2*auc - 1\n#     print(\"accuray, auc, gini =\",accuracy, auc, gini)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T09:40:42.540041Z","iopub.execute_input":"2024-06-12T09:40:42.540691Z","iopub.status.idle":"2024-06-12T09:43:11.408007Z","shell.execute_reply.started":"2024-06-12T09:40:42.540660Z","shell.execute_reply":"2024-06-12T09:43:11.406966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for sm in cat_model.estimators:\n#     print(sm.__sklearn_is_fitted__())","metadata":{"execution":{"iopub.status.busy":"2024-06-12T09:51:37.393325Z","iopub.execute_input":"2024-06-12T09:51:37.394312Z","iopub.status.idle":"2024-06-12T09:51:37.426620Z","shell.execute_reply.started":"2024-06-12T09:51:37.394279Z","shell.execute_reply":"2024-06-12T09:51:37.425362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from sklearn.ensemble import StackingClassifier\n# from sklearn.linear_model import RidgeClassifier\n# from sklearn.calibration import CalibratedClassifierCV\n\n\n# estimators = [\n#     ('m1', model_lgb_gbdt),\n#     ('m2', model_lgb_goss),\n#     ('m3', model_lgb_gbdt_et),\n#     ('m4', cat_model),\n#     ('m5', xgb_model0)\n# ]\n\n# X_train = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n# y_train = df_train[\"target\"]\n\n\n# stacking_clf = StackingClassifier(estimators=estimators, final_estimator=RidgeClassifier())\n# stacking_clf.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T09:52:55.115782Z","iopub.execute_input":"2024-06-12T09:52:55.116160Z","iopub.status.idle":"2024-06-12T09:52:58.870940Z","shell.execute_reply.started":"2024-06-12T09:52:55.116133Z","shell.execute_reply":"2024-06-12T09:52:58.869237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# calibrated_clf = CalibratedClassifierCV(base_estimator=stacking_clf, method='sigmoid')\n# calibrated_clf.fit(X_train, y_train)","metadata":{},"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.1,0.3,0.2,0.3,0,1]\n#     models = [cat_model, model_lgb_goss, model_lgb_gbdt, model_lgb_gbdt_et, xgb_model0]\n#     y=0\n#     for i, submodel in enumerate(models):\n#         y = y+ weight[i]*submodel.predict_proba(X_test)\n#     return y\n\ndef predict_proba(X_test):\n    weight = [0.3,0.2,0.3,0.2]\n    models = [cat_model,model_lgb_goss, model_lgb_gbdt, model_lgb_gbdt_et]\n    y=0\n    for i, submodel in enumerate(models):\n        y = y + weight[i]*submodel.predict_proba(X_test)\n    return y","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","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":[]}]}