{"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"}],"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-11T14:37:35.334278Z","iopub.execute_input":"2024-06-11T14:37:35.334934Z","iopub.status.idle":"2024-06-11T14:37:38.213944Z","shell.execute_reply.started":"2024-06-11T14:37:35.334901Z","shell.execute_reply":"2024-06-11T14:37:38.213094Z"},"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-11T14:37:48.607164Z","iopub.execute_input":"2024-06-11T14:37:48.607836Z","iopub.status.idle":"2024-06-11T14:37:48.614820Z","shell.execute_reply.started":"2024-06-11T14:37:48.607803Z","shell.execute_reply":"2024-06-11T14:37:48.613823Z"},"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":{"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":{"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":{"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":{"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":{"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":{"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":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Handling Missing Values and Reducing Columns Based on Correlation\n\nfrom https://www.kaggle.com/code/hlfen567/explained-home-credit-pipeline","metadata":{}},{"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":{"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)\n\n","metadata":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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(\"memery usage after reduction:\",df_test.memory_usage().sum() / 1024**2)","metadata":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# For compatibility reasons, make categories of the feature validation, test and\n# submission dataframes which do not pertain to the the training dataframe be replaced\n# by the category \"Unknown\"\n\ndf_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":{"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.1))\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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump((df_train,df_val,df_test), \"data.pkl\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"cell_type":"code","source":"df_train,df_val,df_test = joblib.load(\"data.pkl\")\ncat_cols = df_train.select_dtypes(include=['category']).columns","metadata":{"execution":{"iopub.status.busy":"2024-06-11T14:38:33.982748Z","iopub.execute_input":"2024-06-11T14:38:33.983467Z","iopub.status.idle":"2024-06-11T14:38:35.046895Z","shell.execute_reply.started":"2024-06-11T14:38:33.983434Z","shell.execute_reply":"2024-06-11T14:38:35.046094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True)\n\nparams = {\n    \"boosting_type\": \"dart\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 6,\n    \"learning_rate\": 0.04,\n    \"n_estimators\": 1000,\n    \"num_leaves\":64,\n    \"feature_fraction\": 0.9,\n    \"bagging_fraction\": 0.8,\n    \"bagging_freq\": 5,\n    \"reg_alpha\" :0.1,\n    \"reg_lambda\" : 10,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"sample_weight\": \"balanced\",\n    \"random_state\": 42,\n    \"max_bin\" :250,\n    \"device\": \"gpu\",\n}\nfitted_models_dart = []\n\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid), (X_train, y_train)],\n        callbacks=[lgb.log_evaluation(100), \n                  ]\n    )\n\n    fitted_models_dart.append(model)\n\nmodel_lgb_dart = VotingModel(fitted_models_dart)\njoblib.dump(model_lgb_dart, \"model_lgb_dart.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-06-11T14:38:54.562971Z","iopub.execute_input":"2024-06-11T14:38:54.563342Z","iopub.status.idle":"2024-06-11T17:19:27.000155Z","shell.execute_reply.started":"2024-06-11T14:38:54.563314Z","shell.execute_reply":"2024-06-11T17:19:26.998762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.04,\n    \"n_estimators\": 1000,\n    \"num_leaves\":64,\n    \"feature_fraction\": 0.9,\n    \"bagging_fraction\": 0.8,\n    \"bagging_freq\": 5,\n    \"reg_alpha\" :0.1,\n    \"reg_lambda\" : 10,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"sample_weight\": \"balanced\",\n    \"random_state\": 42,\n    \"max_bin\" :250,\n    \"device\": \"gpu\",\n    \"extra_tree\": True\n}\nfitted_models3 = []\n\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid), (X_train, y_train)],\n        callbacks=[lgb.log_evaluation(100), \n                   lgb.early_stopping(first_metric_only=True,\n                        stopping_rounds=40,\n                        verbose=True,\n                        min_delta=0),\n                  ]\n    )\n\n    fitted_models3.append(model)\n\nmodel_lgb_gbdt_et = VotingModel(fitted_models3)\njoblib.dump(model_lgb_gbdt_et, \"model_lgb_gbdt_et.pkl\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.04,\n    \"n_estimators\": 1000,\n    \"num_leaves\":64,\n    \"feature_fraction\": 0.9,\n    \"bagging_fraction\": 0.8,\n    \"bagging_freq\": 5,\n    \"reg_alpha\" :0.1,\n    \"reg_lambda\" : 10,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"sample_weight\": \"balanced\",\n    \"random_state\": 42,\n    \"max_bin\" :250,\n    \"device\": \"gpu\",\n}\nfitted_models = []\n\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid), (X_train, y_train)],\n        callbacks=[lgb.log_evaluation(100), \n                   lgb.early_stopping(first_metric_only=True,\n                        stopping_rounds=40,\n                        verbose=True,\n                        min_delta=0),\n                  ]\n    )\n\n    fitted_models.append(model)\n\nmodel_lgb_balanced = VotingModel(fitted_models)\njoblib.dump(model_lgb_balanced, \"model_lgb_gbdt.pkl\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# cal accuray and gini_score:\ndf_bases = []\nfor df in [df_train, 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_balanced.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":{"trusted":true},"execution_count":null,"outputs":[]},{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"On training set:\")\nprint(get_stability_score(df_bases[0]))\n\nprint(\"On validation set:\")\nprint(get_stability_score(df_bases[1]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lbg model saving\njoblib.dump(model_lgb_balanced, \"model_lgb_gbdt.pkl\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lgb model2 use goss boosting_type\nX = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True)\n\nparams = {\n    \"boosting_type\": \"goss\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.04,\n    \"n_estimators\": 1000,\n    \"num_leaves\":64,\n    \"feature_fraction\": 0.9,\n    \"reg_alpha\" :0.1,\n    \"reg_lambda\" : 10,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"sample_weight\": \"balanced\",\n    \"random_state\": 42,\n    \"max_bin\" :250,\n    \"device\": \"gpu\",\n}\nfitted_models2 = []\n\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid), (X_train, y_train)],\n        callbacks=[lgb.log_evaluation(100), \n                   lgb.early_stopping(first_metric_only=True,\n                        stopping_rounds=40,\n                        verbose=True,\n                        min_delta=0),\n                  ]\n    )\n\n    fitted_models2.append(model)\n\nmodel_lgb_goss = VotingModel(fitted_models2)\n# lbg model saving\njoblib.dump(model_lgb_goss, \"model_lgb_goss.pkl\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_lgb_goss = joblib.load(\"model_lgb_goss.pkl\")\ndf_bases = []\nfor 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_goss.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)\n    \nprint(\"On validation set:\")\nprint(get_stability_score(df_bases[0]))","metadata":{},"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-11T13:22:55.741034Z","iopub.execute_input":"2024-06-11T13:22:55.741763Z","iopub.status.idle":"2024-06-11T13:22:55.796394Z","shell.execute_reply.started":"2024-06-11T13:22:55.741732Z","shell.execute_reply":"2024-06-11T13:22:55.795681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True)\n\ncat_fitted_models = []\ncv_scores_cat=[]\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n    train_pool = Pool(X_train, y_train, cat_features=cat_cols)\n    val_pool = Pool(X_valid, y_valid, cat_features=cat_cols)\n\n    clf = CatBoostClassifier(\n#         best_model_min_trees = 1200,\n        best_model_min_trees = 500,\n        boosting_type = \"Plain\",\n        eval_metric = \"AUC\",\n        iterations = 1000,\n        learning_rate = 0.04,\n        l2_leaf_reg = 10,\n        depth = 6,\n        early_stopping_rounds = 20,\n        max_leaves = 64,\n        random_seed = 42,\n        task_type = \"GPU\",\n        use_best_model = True,\n        verbose = 50,\n#         logging_level='Verbose'\n    )\n\n    clf.fit(train_pool, eval_set=val_pool)\n    y_pred_valid = clf.predict_proba(X_valid)[:, 1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    print(\"val auc:\", auc_score)\n    cv_scores_cat.append(auc_score)\n    cat_fitted_models.append(clf)\n\ncat_model = VotingModel_cat(cat_fitted_models)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train,df_val,df_test = joblib.load(\"data.pkl\")\ncat_cols = df_train.select_dtypes(include=['category']).columns","metadata":{"execution":{"iopub.status.busy":"2024-06-11T13:23:04.169050Z","iopub.execute_input":"2024-06-11T13:23:04.169797Z","iopub.status.idle":"2024-06-11T13:23:05.227306Z","shell.execute_reply.started":"2024-06-11T13:23:04.169765Z","shell.execute_reply":"2024-06-11T13:23:05.226483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# XGBoost\nimport xgboost as xgb\n\nX = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ncv = StratifiedGroupKFold(n_splits=5, shuffle=True)\n\nxgb_fitted_models = []\ncv_scores_xgb=[]\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n    xgb_model = xgb.XGBClassifier(\n        learning_rate = 0.02,\n        device=\"cuda\",\n        objective='binary:logistic',\n        tree_method='hist',\n        enable_categorical=True,\n        eval_metric='auc',\n        subsample=0.85,\n        colsample_bytree=0.9,\n        min_child_weight=20,\n        max_depth=17,\n        gamma=0.0003,\n        #reg_alpha=0.7,\n        n_estimators=1200,\n        random_state=42,\n        early_stopping_rounds=40,\n    )\n    xgb_model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid)],\n        verbose=50,\n    )\n    xgb_fitted_models.append(xgb_model)\nxgb_model0 = VotingModel_cat(xgb_fitted_models)\njoblib.dump(xgb_model0,\"xgb_model0.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-06-11T13:38:35.919439Z","iopub.execute_input":"2024-06-11T13:38:35.919828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction","metadata":{}},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\n\ny_pred = pd.Series(model_lgb_balanced.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Check null: \", df_subm[\"score\"].isnull().any())\n\ndf_subm.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}