{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.13"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false},"papermill":{"default_parameters":{},"duration":9468.936222,"end_time":"2024-02-18T04:41:03.134316","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-02-18T02:03:14.198094","version":"2.5.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport os\nimport gc\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nprint(pl.__version__)\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nimport lightgbm as lgb","metadata":{"execution":{"iopub.status.busy":"2024-05-22T07:30:28.529056Z","iopub.execute_input":"2024-05-22T07:30:28.529807Z","iopub.status.idle":"2024-05-22T07:30:34.606680Z","shell.execute_reply.started":"2024-05-22T07:30:28.529761Z","shell.execute_reply":"2024-05-22T07:30:34.605098Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","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.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        return df\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.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":{"papermill":{"duration":0.02219,"end_time":"2024-02-18T02:03:21.046154","exception":false,"start_time":"2024-02-18T02:03:21.023964","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:30:34.608654Z","iopub.execute_input":"2024-05-22T07:30:34.609810Z","iopub.status.idle":"2024-05-22T07:30:34.629281Z","shell.execute_reply.started":"2024-05-22T07:30:34.609521Z","shell.execute_reply":"2024-05-22T07:30:34.627688Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Defines a class called Aggregator that contains several static methods for generating aggregated expressions","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_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\n\n\n    @staticmethod\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\n\n\n    @staticmethod\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\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        return exprs","metadata":{"papermill":{"duration":0.019165,"end_time":"2024-02-18T02:03:21.071306","exception":false,"start_time":"2024-02-18T02:03:21.052141","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:30:34.630962Z","iopub.execute_input":"2024-05-22T07:30:34.631825Z","iopub.status.idle":"2024-05-22T07:30:34.651545Z","shell.execute_reply.started":"2024-05-22T07:30:34.631779Z","shell.execute_reply":"2024-05-22T07:30:34.649765Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndef read_file(path, depth=None):\n  \n    df = pl.read_parquet(path)\n\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    return df\n\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    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    return df","metadata":{"papermill":{"duration":0.016236,"end_time":"2024-02-18T02:03:21.093682","exception":false,"start_time":"2024-02-18T02:03:21.077446","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:30:34.655205Z","iopub.execute_input":"2024-05-22T07:30:34.655660Z","iopub.status.idle":"2024-05-22T07:30:34.671101Z","shell.execute_reply.started":"2024-05-22T07:30:34.655624Z","shell.execute_reply":"2024-05-22T07:30:34.669792Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Feature engineering functions for adding new features and merging data frames","metadata":{}},{"cell_type":"code","source":"\ndef 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    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    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base","metadata":{"papermill":{"duration":0.015061,"end_time":"2024-02-18T02:03:21.114737","exception":false,"start_time":"2024-02-18T02:03:21.099676","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:30:34.672579Z","iopub.execute_input":"2024-05-22T07:30:34.674053Z","iopub.status.idle":"2024-05-22T07:30:34.689247Z","shell.execute_reply.started":"2024-05-22T07:30:34.673960Z","shell.execute_reply":"2024-05-22T07:30:34.687361Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndef to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    return df_data, cat_cols","metadata":{"papermill":{"duration":0.013702,"end_time":"2024-02-18T02:03:21.134273","exception":false,"start_time":"2024-02-18T02:03:21.120571","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:30:34.696506Z","iopub.execute_input":"2024-05-22T07:30:34.697874Z","iopub.status.idle":"2024-05-22T07:30:34.712312Z","shell.execute_reply.started":"2024-05-22T07:30:34.697816Z","shell.execute_reply":"2024-05-22T07:30:34.710884Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n# ROOT            = Path(\"./input\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"papermill":{"duration":0.01447,"end_time":"2024-02-18T02:03:21.165934","exception":false,"start_time":"2024-02-18T02:03:21.151464","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:30:34.714652Z","iopub.execute_input":"2024-05-22T07:30:34.715902Z","iopub.status.idle":"2024-05-22T07:30:34.733897Z","shell.execute_reply.started":"2024-05-22T07:30:34.715844Z","shell.execute_reply":"2024-05-22T07:30:34.732149Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndata_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":{"papermill":{"duration":22.271196,"end_time":"2024-02-18T02:03:43.454174","exception":false,"start_time":"2024-02-18T02:03:21.182978","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:30:34.735973Z","iopub.execute_input":"2024-05-22T07:30:34.736422Z","iopub.status.idle":"2024-05-22T07:31:17.033949Z","shell.execute_reply.started":"2024-05-22T07:30:34.736376Z","shell.execute_reply":"2024-05-22T07:31:17.032492Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"papermill":{"duration":6.172803,"end_time":"2024-02-18T02:03:49.633275","exception":false,"start_time":"2024-02-18T02:03:43.460472","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:31:17.039134Z","iopub.execute_input":"2024-05-22T07:31:17.039596Z","iopub.status.idle":"2024-05-22T07:31:25.344823Z","shell.execute_reply.started":"2024-05-22T07:31:17.039561Z","shell.execute_reply":"2024-05-22T07:31:25.343117Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndata_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":{"papermill":{"duration":0.347863,"end_time":"2024-02-18T02:03:49.999943","exception":false,"start_time":"2024-02-18T02:03:49.65208","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:31:25.350711Z","iopub.execute_input":"2024-05-22T07:31:25.351119Z","iopub.status.idle":"2024-05-22T07:31:25.842338Z","shell.execute_reply.started":"2024-05-22T07:31:25.351089Z","shell.execute_reply":"2024-05-22T07:31:25.840878Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndf_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"papermill":{"duration":0.040418,"end_time":"2024-02-18T02:03:50.047284","exception":false,"start_time":"2024-02-18T02:03:50.006866","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:31:25.844125Z","iopub.execute_input":"2024-05-22T07:31:25.844583Z","iopub.status.idle":"2024-05-22T07:31:25.893342Z","shell.execute_reply.started":"2024-05-22T07:31:25.844541Z","shell.execute_reply":"2024-05-22T07:31:25.891589Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndf_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":{"papermill":{"duration":2.067345,"end_time":"2024-02-18T02:03:52.120929","exception":false,"start_time":"2024-02-18T02:03:50.053584","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:31:25.895347Z","iopub.execute_input":"2024-05-22T07:31:25.895794Z","iopub.status.idle":"2024-05-22T07:31:28.263828Z","shell.execute_reply.started":"2024-05-22T07:31:25.895759Z","shell.execute_reply":"2024-05-22T07:31:28.262510Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)","metadata":{"papermill":{"duration":8.362466,"end_time":"2024-02-18T02:04:00.48965","exception":false,"start_time":"2024-02-18T02:03:52.127184","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:31:28.265238Z","iopub.execute_input":"2024-05-22T07:31:28.265602Z","iopub.status.idle":"2024-05-22T07:31:46.350335Z","shell.execute_reply.started":"2024-05-22T07:31:28.265571Z","shell.execute_reply":"2024-05-22T07:31:46.349315Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"papermill":{"duration":0.118213,"end_time":"2024-02-18T02:04:00.615687","exception":false,"start_time":"2024-02-18T02:04:00.497474","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:31:46.351725Z","iopub.execute_input":"2024-05-22T07:31:46.352815Z","iopub.status.idle":"2024-05-22T07:31:46.488132Z","shell.execute_reply.started":"2024-05-22T07:31:46.352781Z","shell.execute_reply":"2024-05-22T07:31:46.486707Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Training","metadata":{}},{"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":{"papermill":{"duration":0.016782,"end_time":"2024-02-18T02:04:15.554576","exception":false,"start_time":"2024-02-18T02:04:15.537794","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:31:46.492301Z","iopub.execute_input":"2024-05-22T07:31:46.494089Z","iopub.status.idle":"2024-05-22T07:31:46.504007Z","shell.execute_reply.started":"2024-05-22T07:31:46.494035Z","shell.execute_reply":"2024-05-22T07:31:46.502633Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\",\"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]","metadata":{"execution":{"iopub.status.busy":"2024-05-22T07:31:46.506413Z","iopub.execute_input":"2024-05-22T07:31:46.506848Z","iopub.status.idle":"2024-05-22T07:31:47.482167Z","shell.execute_reply.started":"2024-05-22T07:31:46.506814Z","shell.execute_reply":"2024-05-22T07:31:47.480926Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import optuna\n# from sklearn.model_selection import cross_validate\n# from lightgbm import LGBMClassifier\n\n# def objective(trial):\n#     max_depth = trial.suggest_int('max_depth', 3, 10)\n#     n_estimators = trial.suggest_int('n_estimators', 1000, 9000)\n#     gamma = trial.suggest_float('gamma', 0, 1)\n#     reg_alpha = trial.suggest_float('reg_alpha', 0, 1)\n#     reg_lambda = trial.suggest_float('reg_lambda', 0, 1)\n#     min_child_weight = trial.suggest_int('min_child_weight', 0, 10)\n#     subsample = trial.suggest_float('subsample', 0, 1)\n#     colsample_bytree = trial.suggest_float('colsample_bytree', 0, 1)\n#     learning_rate = trial.suggest_float('learning_rate', 0, 1)\n    \n# #     print('Training the model with', X.shape[1], 'features')\n    \n# #       LightGBM\n#     params = {'learning_rate': learning_rate,\n#               'n_estimators': n_estimators,\n#               'max_depth': max_depth,\n#               'lambda_l1': reg_alpha,\n#               'lambda_l2': reg_lambda,\n#               'colsample_bytree': colsample_bytree, \n#               'subsample': subsample,    \n#               'min_child_samples': min_child_weight,\n#               'class_weight': 'balanced'}\n    \n#     clf = LGBMClassifier(**params, verbose = -1, verbosity = -1)\n    \n#     cv_results = cross_validate(clf,X,y, cv=6, scoring='accuracy')\n    \n#     validation_score = np.mean(cv_results['test_score'])\n#     print(validation_score)\n    \n#     return validation_score","metadata":{"execution":{"iopub.status.busy":"2024-05-22T07:33:11.058851Z","iopub.execute_input":"2024-05-22T07:33:11.059368Z","iopub.status.idle":"2024-05-22T07:33:11.074379Z","shell.execute_reply.started":"2024-05-22T07:33:11.059334Z","shell.execute_reply":"2024-05-22T07:33:11.072656Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Uncomment this section if you want to do hyperparameter tuning\n# study = optuna.create_study(direction=\"maximize\")\n# study.optimize(objective, n_trials= 8)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T07:33:11.562574Z","iopub.execute_input":"2024-05-22T07:33:11.563087Z","iopub.status.idle":"2024-05-22T07:36:26.101958Z","shell.execute_reply.started":"2024-05-22T07:33:11.563051Z","shell.execute_reply":"2024-05-22T07:36:26.099926Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# df_study = study.trials_dataframe()\n# df_study = df_study.sort_values(by='value', ascending=False)\n\n# df_study.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T07:33:00.586562Z","iopub.status.idle":"2024-05-22T07:33:00.587122Z","shell.execute_reply.started":"2024-05-22T07:33:00.586857Z","shell.execute_reply":"2024-05-22T07:33:00.586881Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Best parameters for LightGBM obtained after Optuna optimization\n# best_params_LGBM = study.best_params\n# print(best_params_LGBM)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T07:33:00.588870Z","iopub.status.idle":"2024-05-22T07:33:00.589400Z","shell.execute_reply.started":"2024-05-22T07:33:00.589150Z","shell.execute_reply":"2024-05-22T07:33:00.589173Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import lightgbm as lgb\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import StratifiedGroupKFold\n\n# パラメータの設定例（適宜調整してください）\nparams = {\n    'learning_rate': 0.108461,\n    'n_estimators': 8000,\n    'max_depth': 7,\n    'lambda_l1': 0.553902,\n    'lambda_l2': 0.115649,\n    'colsample_bytree': 0.555968,\n    'subsample': 0.368815,\n    'min_child_samples': 8,\n    'class_weight': 'balanced'\n}\n\n# StratifiedGroupKFoldのインスタンスを作成\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\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(50), lgb.early_stopping(50)]\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\nprint(\"CV AUC scores: \", cv_scores)\n\nclass VotingModel:\n    def __init__(self, models):\n        self.models = models\n\n    def predict_proba(self, X):\n        preds = [model.predict_proba(X) for model in self.models]\n        return np.mean(preds, axis=0)\n\nvoting_model = VotingModel(fitted_models)\n\n# テストデータの処理\nX_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\n\n# 予測の実行\nlgb_pred = pd.Series(voting_model.predict_proba(X_test)[:, 1], index=X_test.index)\n\n# 提出用ファイルの作成\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\ndf_subm[\"score\"] = lgb_pred\ndf_subm.to_csv(\"submission.csv\")\n\n","metadata":{"papermill":{"duration":9405.190593,"end_time":"2024-02-18T04:41:00.752298","exception":false,"start_time":"2024-02-18T02:04:15.561705","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-05-22T07:33:00.590476Z","iopub.status.idle":"2024-05-22T07:33:00.591079Z","shell.execute_reply.started":"2024-05-22T07:33:00.590790Z","shell.execute_reply":"2024-05-22T07:33:00.590812Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{},"outputs":[],"execution_count":null}]}