{"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":7602123,"sourceType":"competition"}],"dockerImageVersionId":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport gc\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport pandas as pd\nimport numpy as np\nimport polars as pl\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:13:54.266303Z","iopub.execute_input":"2024-03-03T12:13:54.267419Z","iopub.status.idle":"2024-03-03T12:13:55.407869Z","shell.execute_reply.started":"2024-03-03T12:13:54.267384Z","shell.execute_reply":"2024-03-03T12:13:55.407094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.Int64))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col[-1] in (\"P\", \"A\"):\n                df = df.with_columns(pl.col(col).cast(pl.Float64))\n            elif col[-1] in (\"M\",):\n                df = df.with_columns(pl.col(col).cast(pl.String))\n            elif col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col).cast(pl.Date))            \n\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                \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-03T12:13:55.409816Z","iopub.execute_input":"2024-03-03T12:13:55.410327Z","iopub.status.idle":"2024-03-03T12:13:55.423651Z","shell.execute_reply.started":"2024-03-03T12:13:55.410293Z","shell.execute_reply":"2024-03-03T12:13:55.422590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    @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.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-03T12:13:55.424617Z","iopub.execute_input":"2024-03-03T12:13:55.424862Z","iopub.status.idle":"2024-03-03T12:13:55.436533Z","shell.execute_reply.started":"2024-03-03T12:13:55.424840Z","shell.execute_reply":"2024-03-03T12:13:55.435614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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        chunks.append(pl.read_parquet(path).pipe(Pipeline.set_table_dtypes))\n        \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:13:55.438379Z","iopub.execute_input":"2024-03-03T12:13:55.438644Z","iopub.status.idle":"2024-03-03T12:13:55.449926Z","shell.execute_reply.started":"2024-03-03T12:13:55.438622Z","shell.execute_reply":"2024-03-03T12:13:55.449172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T12:13:55.451366Z","iopub.execute_input":"2024-03-03T12:13:55.451684Z","iopub.status.idle":"2024-03-03T12:13:55.460422Z","shell.execute_reply.started":"2024-03-03T12:13:55.451659Z","shell.execute_reply":"2024-03-03T12:13:55.459623Z"},"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-03T12:13:55.461395Z","iopub.execute_input":"2024-03-03T12:13:55.461649Z","iopub.status.idle":"2024-03-03T12:13:55.473921Z","shell.execute_reply.started":"2024-03-03T12:13:55.461626Z","shell.execute_reply":"2024-03-03T12:13:55.473099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T12:13:55.474909Z","iopub.execute_input":"2024-03-03T12:13:55.475221Z","iopub.status.idle":"2024-03-03T12:13:55.484256Z","shell.execute_reply.started":"2024-03-03T12:13:55.475192Z","shell.execute_reply":"2024-03-03T12:13:55.483454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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_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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:13:55.485292Z","iopub.execute_input":"2024-03-03T12:13:55.485604Z","iopub.status.idle":"2024-03-03T12:14:25.989120Z","shell.execute_reply.started":"2024-03-03T12:13:55.485575Z","shell.execute_reply":"2024-03-03T12:14:25.988327Z"},"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-03T12:14:25.990149Z","iopub.execute_input":"2024-03-03T12:14:25.990417Z","iopub.status.idle":"2024-03-03T12:14:31.329436Z","shell.execute_reply.started":"2024-03-03T12:14:25.990394Z","shell.execute_reply":"2024-03-03T12:14:31.328523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:14:31.332631Z","iopub.execute_input":"2024-03-03T12:14:31.332900Z","iopub.status.idle":"2024-03-03T12:14:31.745867Z","shell.execute_reply.started":"2024-03-03T12:14:31.332878Z","shell.execute_reply":"2024-03-03T12:14:31.744799Z"},"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-03T12:14:31.747351Z","iopub.execute_input":"2024-03-03T12:14:31.747679Z","iopub.status.idle":"2024-03-03T12:14:31.776001Z","shell.execute_reply.started":"2024-03-03T12:14:31.747652Z","shell.execute_reply":"2024-03-03T12:14:31.775094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T12:14:31.777143Z","iopub.execute_input":"2024-03-03T12:14:31.777423Z","iopub.status.idle":"2024-03-03T12:14:33.967002Z","shell.execute_reply.started":"2024-03-03T12:14:31.777399Z","shell.execute_reply":"2024-03-03T12:14:33.966101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T12:14:33.968213Z","iopub.execute_input":"2024-03-03T12:14:33.968500Z","iopub.status.idle":"2024-03-03T12:14:49.074986Z","shell.execute_reply.started":"2024-03-03T12:14:33.968475Z","shell.execute_reply":"2024-03-03T12:14:49.073869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:14:49.076370Z","iopub.execute_input":"2024-03-03T12:14:49.076649Z","iopub.status.idle":"2024-03-03T12:14:49.143113Z","shell.execute_reply.started":"2024-03-03T12:14:49.076624Z","shell.execute_reply":"2024-03-03T12:14:49.142116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.base import BaseEstimator, RegressorMixin\n\nimport joblib\n\nimport lightgbm as lgb","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:14:49.144386Z","iopub.execute_input":"2024-03-03T12:14:49.144643Z","iopub.status.idle":"2024-03-03T12:14:54.519628Z","shell.execute_reply.started":"2024-03-03T12:14:49.144621Z","shell.execute_reply":"2024-03-03T12:14:54.518847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        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-03T12:14:54.520669Z","iopub.execute_input":"2024-03-03T12:14:54.520948Z","iopub.status.idle":"2024-03-03T12:14:54.527475Z","shell.execute_reply.started":"2024-03-03T12:14:54.520923Z","shell.execute_reply":"2024-03-03T12:14:54.526512Z"},"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\nX_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:14:54.528801Z","iopub.execute_input":"2024-03-03T12:14:54.529094Z","iopub.status.idle":"2024-03-03T12:14:55.488952Z","shell.execute_reply.started":"2024-03-03T12:14:54.529045Z","shell.execute_reply":"2024-03-03T12:14:55.488165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# nc = [3, 4, 7, 8, 9, 10, 11, 12, 15, 22, 31, 39, 41, 42, 61, 66, 69, 74, 75, 86, 96, 99, 100, 101, 102, 103, 104, 111, 112, 116, 118, 120, 121, 122, 124, 126, 127, 129, 130, 131, 132, 134, 137, 138, 139, 140, 141, 143, 145, 146, 147, 148, 149, 152, 154, 168, 171, 172, 174, 185, 187, 189, 198, 201, 201]\nnc = [1, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 31, 36, 37, 38, 39, 41, 42, 57, 58, 61, 63, 64, 65, 66, 67, 69, 71, 74, 75, 76, 77, 80, 81, 86, 93, 94, 96, 98, 99, 100, 101, 102, 103, 104, 109, 111, 112, 114, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 163, 168, 169, 171, 172, 173, 174, 177, 180, 185, 187, 189, 191, 193, 194, 196, 198, 200, 201, 203]\ncolumns = [col for col in X.columns if not col=='category']\nncc = [col for col in columns if col=='category']\nX = X[columns]\nX_test = X_test[columns]\nc = []\nfor ind, col in enumerate(X.columns):\n    if ind in nc:\n        c.append(col)\nX = X[c + ncc]\nX_test = X_test[c + ncc]","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:14:55.490022Z","iopub.execute_input":"2024-03-03T12:14:55.490381Z","iopub.status.idle":"2024-03-03T12:14:56.995483Z","shell.execute_reply.started":"2024-03-03T12:14:55.490352Z","shell.execute_reply":"2024-03-03T12:14:56.994546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score\n\n# X = df_train.drop(columns=[\"target\", \"case_id\",\"WEEK_NUM\"])\n# y = df_train[\"target\"]\n# weeks = d f_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\": 10,\n    \"learning_rate\": 0.05,\n    \"max_bin\": 255,\n    \"n_estimators\": 1000,\n    \"colsample_bytree\": 0.9, \n    \"colsample_bynode\": 0.9,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"reg_alpha\": 0.1, \n    \"reg_lambda\": 3.25, \n    \"extra_trees\":True,\n    \"device\": \"gpu\",\n}\n\nfitted_models = []\ncv_scores = []  \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    print(\"Valid week range: \", (weeks.iloc[idx_valid].min(), weeks.iloc[idx_valid].max()))\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\n    y_pred_valid = model.predict_proba(X_valid)[:, 1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n\nmodel = VotingModel(fitted_models)\nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Average CV AUC score: \", sum(cv_scores) / len(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:14:56.996618Z","iopub.execute_input":"2024-03-03T12:14:56.996927Z","iopub.status.idle":"2024-03-03T12:27:42.644510Z","shell.execute_reply.started":"2024-03-03T12:14:56.996902Z","shell.execute_reply":"2024-03-03T12:27:42.643432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# X_test = df_test.drop(columns=[\"WEEK_NUM\"])\n# X_test = X_test.set_index(\"case_id\")\n \nlgb_pred = pd.Series(model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:27:42.645574Z","iopub.execute_input":"2024-03-03T12:27:42.645837Z","iopub.status.idle":"2024-03-03T12:27:42.708954Z","shell.execute_reply.started":"2024-03-03T12:27:42.645814Z","shell.execute_reply":"2024-03-03T12:27:42.708011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del model\n# del X_test\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:27:42.710423Z","iopub.execute_input":"2024-03-03T12:27:42.710978Z","iopub.status.idle":"2024-03-03T12:27:42.839717Z","shell.execute_reply.started":"2024-03-03T12:27:42.710945Z","shell.execute_reply":"2024-03-03T12:27:42.838703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import xgboost as xgb\n\nfitted_models = []\ncv_scores = []  \n\nparams = {\n    \"device\":\"cuda\",\n    \"objective\":'binary:logistic',\n    \"tree_method\":\"hist\",\n    \"enable_categorical\":True,\n    \"eval_metric\":'auc',\n    \"subsample\":1,\n    \"colsample_bytree\":1,\n    \"min_child_weight\":1,\n    \"max_depth\":20,\n    #gamma=0.7,\n    #reg_alpha=0.7,\n    \"n_estimators\":1200,\n    \"random_state\":42,\n}\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    print(\"Valid week range: \", (weeks.iloc[idx_valid].min(), weeks.iloc[idx_valid].max()))\n    \n    xgb_model = xgb.XGBClassifier(**params)\n\n    # Training the model on the training data\n    xgb_model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid)],\n        early_stopping_rounds=100,\n        verbose=True,\n    )\n    fitted_models.append(xgb_model)\n\n    y_pred_valid = xgb_model.predict_proba(X_valid)[:, 1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n    break\n\nxgb_fitted_model = VotingModel(fitted_models)\nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Average CV AUC score: \", sum(cv_scores) / len(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:27:42.840836Z","iopub.execute_input":"2024-03-03T12:27:42.841173Z","iopub.status.idle":"2024-03-03T12:28:57.306375Z","shell.execute_reply.started":"2024-03-03T12:27:42.841149Z","shell.execute_reply":"2024-03-03T12:28:57.305347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# X_test = df_test.drop(columns=[\"WEEK_NUM\"])\n# X_test = X_test.set_index(\"case_id\")\n\nxgb_pred = pd.Series(xgb_fitted_model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:28:57.307765Z","iopub.execute_input":"2024-03-03T12:28:57.308164Z","iopub.status.idle":"2024-03-03T12:28:57.349592Z","shell.execute_reply.started":"2024-03-03T12:28:57.308130Z","shell.execute_reply":"2024-03-03T12:28:57.348785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\ndf_subm[\"score\"] = (lgb_pred + xgb_pred)*0.5","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:28:57.350762Z","iopub.execute_input":"2024-03-03T12:28:57.351313Z","iopub.status.idle":"2024-03-03T12:28:57.364162Z","shell.execute_reply.started":"2024-03-03T12:28:57.351280Z","shell.execute_reply":"2024-03-03T12:28:57.363314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"/kaggle/working/submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:28:57.365111Z","iopub.execute_input":"2024-03-03T12:28:57.365355Z","iopub.status.idle":"2024-03-03T12:28:57.371690Z","shell.execute_reply.started":"2024-03-03T12:28:57.365333Z","shell.execute_reply":"2024-03-03T12:28:57.370814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}