{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30648,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"### <span style=\"color: red;\"> =============== LOOK HERE BEGIN =============== </span>\n# NAME: Alikhan Zimanov\n\nFACULTY: HSE AMI\n\nSource: https://www.kaggle.com/code/greysky/home-credit-baseline\n\nInitial score: 0.563\n\nMy score: 0.567\n\nChanges:\n\n1. Added 'mean_num_expr' feature in `Aggregator`.\n2. Created a stratified sampler that samples from the dataframe where every WEEK_NUM is represented and each target (0 or 1) is present for each WEEK_NUM. It is used for hyperparameter tuning futher below, since target gini stability score computes auc, which requires each target to be present among given data.\n3. Created a weighted voting model and used [hill climbing](https://en.wikipedia.org/wiki/Hill_climbing) optimization technique to optimize the weights of this voting model; target optimization function is the gini stability score from the problem statement (its implementation is taken from [here](https://www.kaggle.com/code/masahikofujita/home-credit-risk-mode-param-chenge#Loading-test-data)). It was trained on a subset of 10000 samples for 100 iterations giving a visible improvement (see logs below).\n\n### <span style=\"color: red;\"> =============== LOOK HERE END =============== </span>","metadata":{}},{"cell_type":"code","source":"import 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\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, ClassifierMixin\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-03-16T22:42:35.174344Z","iopub.execute_input":"2024-03-16T22:42:35.174754Z","iopub.status.idle":"2024-03-16T22:42:41.375929Z","shell.execute_reply.started":"2024-03-16T22:42:35.174722Z","shell.execute_reply":"2024-03-16T22:42:41.374997Z"},"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) 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-03-16T22:42:41.377555Z","iopub.execute_input":"2024-03-16T22:42:41.377840Z","iopub.status.idle":"2024-03-16T22:42:41.384701Z","shell.execute_reply.started":"2024-03-16T22:42:41.377816Z","shell.execute_reply":"2024-03-16T22:42:41.383689Z"},"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-03-16T22:42:41.386043Z","iopub.execute_input":"2024-03-16T22:42:41.386371Z","iopub.status.idle":"2024-03-16T22:42:41.400413Z","shell.execute_reply.started":"2024-03-16T22:42:41.386342Z","shell.execute_reply":"2024-03-16T22:42:41.399622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Automatic Aggregation","metadata":{}},{"cell_type":"markdown","source":"### <span style=\"color: red;\"> =============== LOOK HERE BEGIN =============== </span>","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\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n    \n    # Added this method\n    @staticmethod\n    def mean_num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n\n        return expr_mean\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\n        return expr_max\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\n        return expr_max\n\n    @staticmethod\n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\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\n        return expr_max\n\n    @staticmethod\n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.mean_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-03-16T22:42:41.402426Z","iopub.execute_input":"2024-03-16T22:42:41.402730Z","iopub.status.idle":"2024-03-16T22:42:41.415273Z","shell.execute_reply.started":"2024-03-16T22:42:41.402707Z","shell.execute_reply":"2024-03-16T22:42:41.414444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span style=\"color: red;\"> =============== LOOK HERE END =============== </span>","metadata":{}},{"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-03-16T22:42:41.416246Z","iopub.execute_input":"2024-03-16T22:42:41.416497Z","iopub.status.idle":"2024-03-16T22:42:41.428265Z","shell.execute_reply.started":"2024-03-16T22:42:41.416476Z","shell.execute_reply":"2024-03-16T22:42:41.427525Z"},"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-03-16T22:42:41.429492Z","iopub.execute_input":"2024-03-16T22:42:41.429789Z","iopub.status.idle":"2024-03-16T22:42:41.440711Z","shell.execute_reply.started":"2024-03-16T22:42:41.429767Z","shell.execute_reply":"2024-03-16T22:42:41.439979Z"},"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-03-16T22:42:41.441667Z","iopub.execute_input":"2024-03-16T22:42:41.441910Z","iopub.status.idle":"2024-03-16T22:42:41.449956Z","shell.execute_reply.started":"2024-03-16T22:42:41.441888Z","shell.execute_reply":"2024-03-16T22:42:41.449312Z"},"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-03-16T22:42:41.450885Z","iopub.execute_input":"2024-03-16T22:42:41.451157Z","iopub.status.idle":"2024-03-16T22:42:41.458621Z","shell.execute_reply.started":"2024-03-16T22:42:41.451111Z","shell.execute_reply":"2024-03-16T22:42:41.457894Z"},"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-03-16T22:42:41.459633Z","iopub.execute_input":"2024-03-16T22:42:41.459921Z","iopub.status.idle":"2024-03-16T22:44:53.301336Z","shell.execute_reply.started":"2024-03-16T22:42:41.459898Z","shell.execute_reply":"2024-03-16T22:44:53.299831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\n\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:44:53.308239Z","iopub.execute_input":"2024-03-16T22:44:53.308582Z","iopub.status.idle":"2024-03-16T22:45:06.678613Z","shell.execute_reply.started":"2024-03-16T22:44:53.308553Z","shell.execute_reply":"2024-03-16T22:45:06.677727Z"},"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-03-16T22:45:06.679581Z","iopub.execute_input":"2024-03-16T22:45:06.679860Z","iopub.status.idle":"2024-03-16T22:45:07.298457Z","shell.execute_reply.started":"2024-03-16T22:45:06.679836Z","shell.execute_reply":"2024-03-16T22:45:07.297674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\n\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:07.299633Z","iopub.execute_input":"2024-03-16T22:45:07.300008Z","iopub.status.idle":"2024-03-16T22:45:07.344578Z","shell.execute_reply.started":"2024-03-16T22:45:07.299969Z","shell.execute_reply":"2024-03-16T22:45:07.343730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Elimination","metadata":{}},{"cell_type":"code","source":"df_train = df_train.pipe(Pipeline.filter_cols)\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:07.345642Z","iopub.execute_input":"2024-03-16T22:45:07.345913Z","iopub.status.idle":"2024-03-16T22:45:10.287323Z","shell.execute_reply.started":"2024-03-16T22:45:07.345889Z","shell.execute_reply":"2024-03-16T22:45:10.286366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pandas Conversion","metadata":{}},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:10.288463Z","iopub.execute_input":"2024-03-16T22:45:10.288724Z","iopub.status.idle":"2024-03-16T22:45:29.397759Z","shell.execute_reply.started":"2024-03-16T22:45:10.288702Z","shell.execute_reply":"2024-03-16T22:45:29.396917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Garbage Collection","metadata":{}},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:29.398949Z","iopub.execute_input":"2024-03-16T22:45:29.399235Z","iopub.status.idle":"2024-03-16T22:45:29.530556Z","shell.execute_reply.started":"2024-03-16T22:45:29.399210Z","shell.execute_reply":"2024-03-16T22:45:29.529644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.columns","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:29.531702Z","iopub.execute_input":"2024-03-16T22:45:29.531992Z","iopub.status.idle":"2024-03-16T22:45:29.541540Z","shell.execute_reply.started":"2024-03-16T22:45:29.531960Z","shell.execute_reply":"2024-03-16T22:45:29.540688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### EDA","metadata":{}},{"cell_type":"code","source":"print(\"Train is duplicated:\\t\", df_train[\"case_id\"].duplicated().any())\nprint(\"Train Week Range:\\t\", (df_train[\"WEEK_NUM\"].min(), df_train[\"WEEK_NUM\"].max()))\n\nprint()\n\nprint(\"Test is duplicated:\\t\", df_test[\"case_id\"].duplicated().any())\nprint(\"Test Week Range:\\t\", (df_test[\"WEEK_NUM\"].min(), df_test[\"WEEK_NUM\"].max()))","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:29.542741Z","iopub.execute_input":"2024-03-16T22:45:29.543068Z","iopub.status.idle":"2024-03-16T22:45:29.571564Z","shell.execute_reply.started":"2024-03-16T22:45:29.543038Z","shell.execute_reply":"2024-03-16T22:45:29.570747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.lineplot(\n    data=df_train,\n    x=\"WEEK_NUM\",\n    y=\"target\",\n)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:29.572475Z","iopub.execute_input":"2024-03-16T22:45:29.572717Z","iopub.status.idle":"2024-03-16T22:45:49.156834Z","shell.execute_reply.started":"2024-03-16T22:45:29.572695Z","shell.execute_reply":"2024-03-16T22:45:49.155946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"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=False)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.05,\n    \"n_estimators\": 1000,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"device\": \"gpu\",\n}\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)],\n        callbacks=[lgb.log_evaluation(100), lgb.early_stopping(100)]\n    )\n\n    fitted_models.append(model)\n\nmodel = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T22:45:49.158044Z","iopub.execute_input":"2024-03-16T22:45:49.158406Z","iopub.status.idle":"2024-03-16T23:04:40.901969Z","shell.execute_reply.started":"2024-03-16T22:45:49.158373Z","shell.execute_reply":"2024-03-16T23:04:40.901013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The following implementation of the gini stability score is taken from: https://www.kaggle.com/code/masahikofujita/home-credit-risk-mode-param-chenge","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score\n\ndef gini_stability(base, w_fallingrate=88.0, w_resstd=-0.5):\n    gini_in_time = base.loc[:, [\"WEEK_NUM\", \"target\", \"score\"]]\\\n        .sort_values(\"WEEK_NUM\")\\\n        .groupby(\"WEEK_NUM\")[[\"target\", \"score\"]]\\\n        .apply(lambda x: 2*roc_auc_score(x[\"target\"], x[\"score\"])-1).tolist()\n    \n    x = np.arange(len(gini_in_time))\n    y = gini_in_time\n    a, b = np.polyfit(x, y, 1)\n    y_hat = a*x + b\n    residuals = y - y_hat\n    res_std = np.std(residuals)\n    avg_gini = np.mean(gini_in_time)\n    return avg_gini + w_fallingrate * min(0, a) + w_resstd * res_std","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:04:40.903467Z","iopub.execute_input":"2024-03-16T23:04:40.904113Z","iopub.status.idle":"2024-03-16T23:04:40.911423Z","shell.execute_reply.started":"2024-03-16T23:04:40.904075Z","shell.execute_reply":"2024-03-16T23:04:40.910439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span style=\"color: red;\"> =============== LOOK HERE BEGIN =============== </span>\n\n# <span style=\"color: red;\">My changes</span>","metadata":{}},{"cell_type":"markdown","source":"### <span style=\"color: red;\">Stratified sampler for creating 'validation' set. </span>","metadata":{}},{"cell_type":"code","source":"def stratified_sample(df, week_num_col='WEEK_NUM', target_col='target', n_samples=1000):\n    \"\"\"\n    Perform stratified sampling to ensure each combination of week number and target is represented.\n    \n    Parameters:\n    - df: pandas DataFrame containing the data.\n    - week_num_col: Name of the column containing week numbers.\n    - target_col: Name of the column containing target values.\n    - n_samples: Total number of samples to return.\n    \n    Returns:\n    - A sampled pandas DataFrame with n_samples (if possible) ensuring representation of each group.\n    \"\"\"\n    \n    samples_per_group = max(1, n_samples // df.groupby([week_num_col, target_col]).ngroups)\n    \n    sampled_df = df.groupby([week_num_col, target_col]).apply(\n        lambda x: x.sample(n=min(samples_per_group, len(x)), replace=True if len(x) < samples_per_group else False)\n    ).reset_index(drop=True)\n    \n    if len(sampled_df) < n_samples:\n        additional_samples = n_samples - len(sampled_df)\n        additional_sampled_df = df.sample(n=additional_samples, replace=True)\n        sampled_df = pd.concat([sampled_df, additional_sampled_df], ignore_index=True)\n    \n    return sampled_df","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:04:40.912509Z","iopub.execute_input":"2024-03-16T23:04:40.912771Z","iopub.status.idle":"2024-03-16T23:04:40.922945Z","shell.execute_reply.started":"2024-03-16T23:04:40.912741Z","shell.execute_reply":"2024-03-16T23:04:40.922249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span style=\"color: red;\"> Finding optimal validation set size which is small enough for fast computations and representable enough for actual hyperparameter tuning. </span>","metadata":{}},{"cell_type":"code","source":"%%time\n\nfor n_samples in [100, 500, 1000, 2000, 5000, 10000, 20000]:\n    small_train = stratified_sample(df_train, n_samples=n_samples)\n\n    small_train['score'] = model.predict_proba(small_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"]))[:, 1]\n\n    print(f\"n_samples: {n_samples} || gini_stability: {gini_stability(small_train)}\")","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:04:40.923890Z","iopub.execute_input":"2024-03-16T23:04:40.924120Z","iopub.status.idle":"2024-03-16T23:05:19.491424Z","shell.execute_reply.started":"2024-03-16T23:04:40.924099Z","shell.execute_reply":"2024-03-16T23:05:19.490420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span style=\"color: red;\"> This means that 10000 samples is enough to optimize weights in a voting model on. </span>","metadata":{}},{"cell_type":"markdown","source":"### <span style=\"color: red;\"> Creating a class for weighted voting model. Its `.fit()` method optimizes voting weights using hill climbing algorithm. </span>","metadata":{}},{"cell_type":"code","source":"class WeightedVotingModel(BaseEstimator, ClassifierMixin):\n    def __init__(self, estimators, num_iters=100, scale=0.1):\n        super().__init__()\n        self.estimators = estimators\n        self.weights = np.ones(len(self.estimators)) / len(self.estimators)\n        \n        self.num_iters = num_iters\n        self.scale = scale\n        \n    def fit(self, X, y=None):\n        \n        X[\"score\"] = self.predict_proba(X.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"]))[:, 1]\n        last_gini = gini_stability(X)\n        \n        for itr in range(self.num_iters):\n            idx = np.random.randint(len(self.estimators))\n            \n            new_weights = self.weights\n            \n            # choose weight to change\n            delta = np.random.normal(loc=0.0, scale=self.scale)\n            if new_weights[idx] + delta >= 0:\n                new_weights[idx] += delta\n            new_weights = new_weights / new_weights.sum()\n            \n            old_weights = self.weights\n            self.weights = new_weights\n            \n            # compute new gini score\n            X[\"score\"] = self.predict_proba(X.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\", \"score\"]))[:, 1]\n            new_gini = gini_stability(X)\n            \n            print(f\"Iteration {itr + 1}/{self.num_iters} || last_gini: {last_gini:.5f} || new_gini: {new_gini:.5f}\")\n            \n            # choose to update the weights or not\n            if new_gini < last_gini:\n                # return old weights because old gini was better\n                self.weights = old_weights\n            else:\n                # accept new weights and change current gini\n                last_gini = new_gini\n            \n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.sum(y_preds * self.weights[:, None], axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        return np.sum(y_preds * self.weights[:, None, None], axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:05:19.492795Z","iopub.execute_input":"2024-03-16T23:05:19.493086Z","iopub.status.idle":"2024-03-16T23:05:19.505260Z","shell.execute_reply.started":"2024-03-16T23:05:19.493060Z","shell.execute_reply":"2024-03-16T23:05:19.504320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"weighted_model = WeightedVotingModel(fitted_models, num_iters=30, scale=0.1)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:05:19.506466Z","iopub.execute_input":"2024-03-16T23:05:19.506781Z","iopub.status.idle":"2024-03-16T23:05:19.522014Z","shell.execute_reply.started":"2024-03-16T23:05:19.506751Z","shell.execute_reply":"2024-03-16T23:05:19.521171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_almost_val = stratified_sample(df_train, n_samples=10000)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:05:19.523107Z","iopub.execute_input":"2024-03-16T23:05:19.523399Z","iopub.status.idle":"2024-03-16T23:05:22.834151Z","shell.execute_reply.started":"2024-03-16T23:05:19.523376Z","shell.execute_reply":"2024-03-16T23:05:22.833117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nweighted_model.fit(df_almost_val)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:05:22.835572Z","iopub.execute_input":"2024-03-16T23:05:22.835919Z","iopub.status.idle":"2024-03-16T23:07:18.994653Z","shell.execute_reply.started":"2024-03-16T23:05:22.835885Z","shell.execute_reply":"2024-03-16T23:07:18.993773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"weighted_model.weights","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:07:18.996016Z","iopub.execute_input":"2024-03-16T23:07:18.996625Z","iopub.status.idle":"2024-03-16T23:07:19.002984Z","shell.execute_reply.started":"2024-03-16T23:07:18.996589Z","shell.execute_reply":"2024-03-16T23:07:19.001989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nsmall_train = stratified_sample(df_train, n_samples=10000)\n\nsmall_train['score'] = weighted_model.predict_proba(small_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"]))[:, 1]\n\nprint(f\"n_samples: {n_samples} || gini_stability: {gini_stability(small_train)}\")","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:07:19.008071Z","iopub.execute_input":"2024-03-16T23:07:19.008418Z","iopub.status.idle":"2024-03-16T23:07:26.040710Z","shell.execute_reply.started":"2024-03-16T23:07:19.008393Z","shell.execute_reply":"2024-03-16T23:07:26.039488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span style=\"color: red;\"> =============== LOOK HERE END =============== </span>","metadata":{}},{"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(weighted_model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:07:26.041759Z","iopub.execute_input":"2024-03-16T23:07:26.042017Z","iopub.status.idle":"2024-03-16T23:07:26.308057Z","shell.execute_reply.started":"2024-03-16T23:07:26.041994Z","shell.execute_reply":"2024-03-16T23:07:26.307314Z"},"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-03-16T23:07:26.309199Z","iopub.execute_input":"2024-03-16T23:07:26.309548Z","iopub.status.idle":"2024-03-16T23:07:26.321883Z","shell.execute_reply.started":"2024-03-16T23:07:26.309509Z","shell.execute_reply":"2024-03-16T23:07:26.320925Z"},"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-03-16T23:07:26.322828Z","iopub.execute_input":"2024-03-16T23:07:26.323076Z","iopub.status.idle":"2024-03-16T23:07:26.335320Z","shell.execute_reply.started":"2024-03-16T23:07:26.323054Z","shell.execute_reply":"2024-03-16T23:07:26.334382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-16T23:07:26.336418Z","iopub.execute_input":"2024-03-16T23:07:26.336742Z","iopub.status.idle":"2024-03-16T23:07:26.343170Z","shell.execute_reply.started":"2024-03-16T23:07:26.336711Z","shell.execute_reply":"2024-03-16T23:07:26.342395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}