{"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":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"},{"sourceId":8172284,"sourceType":"datasetVersion","datasetId":4836804},{"sourceId":8190841,"sourceType":"datasetVersion","datasetId":4850615},{"sourceId":8192782,"sourceType":"datasetVersion","datasetId":4852130},{"sourceId":8192787,"sourceType":"datasetVersion","datasetId":4852134},{"sourceId":8194214,"sourceType":"datasetVersion","datasetId":4853292},{"sourceId":8217086,"sourceType":"datasetVersion","datasetId":4870592},{"sourceId":8217447,"sourceType":"datasetVersion","datasetId":4870841}],"dockerImageVersionId":30683,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Home Credit Ensemble Model","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:48:32.207334Z","iopub.execute_input":"2024-04-15T06:48:32.207714Z","iopub.status.idle":"2024-04-15T06:48:32.212318Z","shell.execute_reply.started":"2024-04-15T06:48:32.207682Z","shell.execute_reply":"2024-04-15T06:48:32.211463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\nfrom tqdm import tqdm_notebook\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pickle as pkl\nfrom sklearn.model_selection import GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nimport lightgbm as lgb\n\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import KNNImputer\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-25T01:42:32.633577Z","iopub.execute_input":"2024-04-25T01:42:32.634063Z","iopub.status.idle":"2024-04-25T01:42:37.952598Z","shell.execute_reply.started":"2024-04-25T01:42:32.634023Z","shell.execute_reply":"2024-04-25T01:42:37.951388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Pipeline:\n\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\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()) # t - t-1\n        df = df.drop(\"date_decision\", \"MONTH\")\n        return df\n\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                if isnull > 0.7:\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                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n        \n        return df\n\n\n\nclass Aggregator:\n    # Please add or subtract features yourself, be aware that too many features will take up too much space.\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\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        expr_median = [pl.median(col).alias(f\"median_{col}\") for col in cols]\n        expr_var = [pl.var(col).alias(f\"var_{col}\") for col in cols]\n\n        return expr_max + expr_last + expr_mean \n\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        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        expr_median = [pl.median(col).alias(f\"median_{col}\") for col in cols]\n\n        return expr_max + expr_last + expr_mean \n\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        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        # expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        return expr_max + expr_last  # +expr_count\n\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        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return expr_max + expr_last\n\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        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return expr_max + expr_last\n\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-04-25T01:42:37.954681Z","iopub.execute_input":"2024-04-25T01:42:37.955307Z","iopub.status.idle":"2024-04-25T01:42:37.980200Z","shell.execute_reply.started":"2024-04-25T01:42:37.955270Z","shell.execute_reply":"2024-04-25T01:42:37.978684Z"},"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    if depth in [1,2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df)) \n    return df\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    \n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.set_table_dtypes)\n        if depth in [1, 2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        chunks.append(df)\n    \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    return df\n\n\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\n\n\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\n\n\ndef 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    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\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    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:42:37.982605Z","iopub.execute_input":"2024-04-25T01:42:37.983008Z","iopub.status.idle":"2024-04-25T01:42:38.002570Z","shell.execute_reply.started":"2024-04-25T01:42:37.982977Z","shell.execute_reply":"2024-04-25T01:42:38.000949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\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_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        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:42:38.005161Z","iopub.execute_input":"2024-04-25T01:42:38.005542Z","iopub.status.idle":"2024-04-25T01:45:19.791584Z","shell.execute_reply.started":"2024-04-25T01:42:38.005510Z","shell.execute_reply":"2024-04-25T01:45:19.790271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ndf_train = df_train.pipe(Pipeline.filter_cols)\nprint(\"train data shape:\\t\", df_train.shape)\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:45:19.796819Z","iopub.execute_input":"2024-04-25T01:45:19.799237Z","iopub.status.idle":"2024-04-25T01:45:50.694115Z","shell.execute_reply.started":"2024-04-25T01:45:19.799188Z","shell.execute_reply":"2024-04-25T01:45:50.692801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\nnums = df_train.select_dtypes(exclude='category').columns\nfrom itertools import combinations, permutations\n\n# df_train=df_train[nums]\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;\nx = gc.collect()\n\n\ndef reduce_group(grps):\n    use = []\n    for g in grps:\n        mx = 0;\n        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            # print(str(gg)+'-'+str(n),', ',end='')\n        use.append(vx)\n        # print()\n    print('Use these', use)\n    return use\n\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    # 计算列之间的相关性\n    correlation_matrix = matrix.corr()\n\n    # 分组列\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\n\nuses = []\nfor k, v in nans_groups.items():\n    if len(v) > 1:\n        Vs = nans_groups[k]\n        # cross_features=list(combinations(Vs, 2))\n        # make_corr(Vs)\n        grps = group_columns_by_correlation(df_train[Vs], threshold=0.8)\n        use = reduce_group(grps)\n        uses = uses + use\n        # make_corr(use)\n    else:\n        uses = uses + v\n    print('####### NAN count =', k)\nprint(uses)\nprint(len(uses))\nuses = uses + list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train = df_train[uses]","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:45:50.695991Z","iopub.execute_input":"2024-04-25T01:45:50.696333Z","iopub.status.idle":"2024-04-25T01:47:15.329600Z","shell.execute_reply.started":"2024-04-25T01:45:50.696305Z","shell.execute_reply":"2024-04-25T01:47:15.328063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# missing_percentages = df_train.isna().mean() * 100\n\n# # Identify columns where the percentage of missing values is greater than 60%\n# columns_to_drop = missing_percentages[missing_percentages > 50].index\n\n# # Drop these columns from the DataFrame\n# df_train_cleaned = df_train.drop(columns=columns_to_drop)\n\n# # Display the columns dropped and the cleaned DataFrame\n# print(\"Columns dropped due to high missing values:\", columns_to_drop)\n# print(\"Cleaned DataFrame preview:\")\n# print(df_train_cleaned.head())","metadata":{"execution":{"iopub.status.busy":"2024-04-24T16:57:56.058595Z","iopub.execute_input":"2024-04-24T16:57:56.058831Z","iopub.status.idle":"2024-04-24T16:57:56.064493Z","shell.execute_reply.started":"2024-04-24T16:57:56.058811Z","shell.execute_reply":"2024-04-24T16:57:56.063928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\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_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        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:47:15.331216Z","iopub.execute_input":"2024-04-25T01:47:15.331606Z","iopub.status.idle":"2024-04-25T01:47:15.712912Z","shell.execute_reply.started":"2024-04-25T01:47:15.331570Z","shell.execute_reply":"2024-04-25T01:47:15.711519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()\n\ndf_test = df_test.select([col for col in df_train.columns if col not in [\"target\"]])\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:47:15.715850Z","iopub.execute_input":"2024-04-25T01:47:15.716220Z","iopub.status.idle":"2024-04-25T01:47:16.361877Z","shell.execute_reply.started":"2024-04-25T01:47:15.716192Z","shell.execute_reply":"2024-04-25T01:47:16.360584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=10, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:47:16.363324Z","iopub.execute_input":"2024-04-25T01:47:16.364388Z","iopub.status.idle":"2024-04-25T01:47:17.933993Z","shell.execute_reply.started":"2024-04-25T01:47:16.364350Z","shell.execute_reply":"2024-04-25T01:47:17.932708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)\ndf_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:47:17.935320Z","iopub.execute_input":"2024-04-25T01:47:17.935670Z","iopub.status.idle":"2024-04-25T01:47:30.370410Z","shell.execute_reply.started":"2024-04-25T01:47:17.935640Z","shell.execute_reply":"2024-04-25T01:47:30.368978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:53:09.622539Z","iopub.execute_input":"2024-04-25T01:53:09.624071Z","iopub.status.idle":"2024-04-25T01:53:09.662654Z","shell.execute_reply.started":"2024-04-25T01:53:09.624011Z","shell.execute_reply":"2024-04-25T01:53:09.661397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:47:30.372607Z","iopub.execute_input":"2024-04-25T01:47:30.373404Z","iopub.status.idle":"2024-04-25T01:47:30.380058Z","shell.execute_reply.started":"2024-04-25T01:47:30.373351Z","shell.execute_reply":"2024-04-25T01:47:30.379079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# params = {\n#     \"boosting_type\": \"gbdt\",\n#     \"objective\": \"binary\",\n#     \"metric\": \"auc\",\n#     \"max_depth\": 10,  \n#     \"learning_rate\": 0.03,\n#     \"n_estimators\": 3000,  \n#     \"colsample_bytree\": 0.8,\n#     \"colsample_bynode\": 0.8,\n#     \"subsample\": 0.8,  # New: Subsample ratio of the training instances\n#     \"subsample_freq\": 1,  # New: Frequence of subsample, <=0 means no enable\n#     \"min_child_samples\": 20,  # New: Minimum number of data in one leaf\n#     \"verbose\": -1,\n#     \"random_state\": 42,\n#     \"reg_alpha\": 0.1,\n#     \"reg_lambda\": 10,\n#     \"extra_trees\": True,\n#     \"num_leaves\": 64,\n#     \"sample_weight\": 'balanced',\n#     \"device\": \"cpu\"\n# }\n# best_params_cat = {\n#     'iterations': 1000,\n#     'learning_rate': 0.02,\n#     'depth': 6,\n#     'loss_function': 'Logloss',\n#     'eval_metric': 'AUC',\n#     'random_seed': 3107,\n#     'l2_leaf_reg': 3,\n#     'bootstrap_type': 'Bayesian',\n#     'bagging_temperature': 1,\n#     'task_type': 'CPU'\n# }","metadata":{"execution":{"iopub.status.busy":"2024-04-24T16:58:03.746328Z","iopub.execute_input":"2024-04-24T16:58:03.747038Z","iopub.status.idle":"2024-04-24T16:58:03.752337Z","shell.execute_reply.started":"2024-04-24T16:58:03.747017Z","shell.execute_reply":"2024-04-24T16:58:03.751653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# %%time\n# from catboost import CatBoostClassifier, Pool\n\n# fitted_models_cat = []\n# fitted_models_lgb = []\n\n# cv_scores_cat = []\n# cv_scores_lgb = []\n\n\n# for idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n#     X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# \n#     X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\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#     clf = CatBoostClassifier(**best_params_cat)\n#     clf.fit(train_pool, eval_set=val_pool,verbose=300)\n#     fitted_models_cat.append(clf)\n#     y_pred_valid = clf.predict_proba(X_valid)[:,1]\n#     auc_score = roc_auc_score(y_valid, y_pred_valid)\n#     cv_scores_cat.append(auc_score)\n    \n    \n#     X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n#     X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\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(200), lgb.early_stopping(100)] )\n    \n#     fitted_models_lgb.append(model)\n#     y_pred_valid = model.predict_proba(X_valid)[:,1]\n#     auc_score = roc_auc_score(y_valid, y_pred_valid)\n#     cv_scores_lgb.append(auc_score)\n    \n    \n# print(\"CV AUC scores: \", cv_scores_cat)\n# print(\"Maximum CV AUC score: \", max(cv_scores_cat))\n\n\n# print(\"CV AUC scores: \", cv_scores_lgb)\n# print(\"Maximum CV AUC score: \", max(cv_scores_lgb))","metadata":{"execution":{"iopub.status.busy":"2024-04-24T16:58:03.753211Z","iopub.execute_input":"2024-04-24T16:58:03.753423Z","iopub.status.idle":"2024-04-24T16:58:03.760688Z","shell.execute_reply.started":"2024-04-24T16:58:03.753404Z","shell.execute_reply":"2024-04-24T16:58:03.760085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb_models = []\n# TODO load trained models\nn_fold = 5\nfor i in range(n_fold):\n    with open(f'/kaggle/input/lgbmver4/model_{i}.pkl', 'rb') as fin:\n        lgb_models.append(pkl.load(fin))\nprint('load lgb done.')","metadata":{"execution":{"iopub.status.busy":"2024-04-25T02:08:22.828111Z","iopub.execute_input":"2024-04-25T02:08:22.828612Z","iopub.status.idle":"2024-04-25T02:08:23.830508Z","shell.execute_reply.started":"2024-04-25T02:08:22.828560Z","shell.execute_reply":"2024-04-25T02:08:23.829185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat_models = []\n\n# TODO load trained models\nn_fold = 5\nfor i in range(n_fold):\n    with open(f'/kaggle/input/catboostver3/model_{i}.pkl', 'rb') as fin:\n        cat_models.append(pkl.load(fin))\nprint('load cat done.')","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:50:57.186552Z","iopub.execute_input":"2024-04-25T01:50:57.186935Z","iopub.status.idle":"2024-04-25T01:50:59.569620Z","shell.execute_reply.started":"2024-04-25T01:50:57.186903Z","shell.execute_reply":"2024-04-25T01:50:59.568161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xg_models = []\n\n# TODO load trained models\nn_fold = 5\nfor i in range(n_fold):\n    with open(f'/kaggle/input/xgboostver3/model_{i}.pkl', 'rb') as fin:\n        xg_models.append(pkl.load(fin))\nprint('load xg done.')","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:50:59.573983Z","iopub.execute_input":"2024-04-25T01:50:59.574401Z","iopub.status.idle":"2024-04-25T01:51:00.487614Z","shell.execute_reply.started":"2024-04-25T01:50:59.574365Z","shell.execute_reply":"2024-04-25T01:51:00.486348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.base import BaseEstimator, RegressorMixin, ClassifierMixin","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:54:24.870805Z","iopub.execute_input":"2024-04-25T01:54:24.871245Z","iopub.status.idle":"2024-04-25T01:54:24.876847Z","shell.execute_reply.started":"2024-04-25T01:54:24.871215Z","shell.execute_reply":"2024-04-25T01:54:24.875392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModelForCatboost(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_proba(self, X):\n        X[cat_cols] = X[cat_cols].astype(str)\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        \n        return np.mean(y_preds, axis=0)\n\nmodel1 = VotingModelForCatboost(cat_models)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T02:08:31.023447Z","iopub.execute_input":"2024-04-25T02:08:31.023957Z","iopub.status.idle":"2024-04-25T02:08:31.032638Z","shell.execute_reply.started":"2024-04-25T02:08:31.023918Z","shell.execute_reply":"2024-04-25T02:08:31.031584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModelForLgbm(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_proba(self, X):\n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        \n        return np.mean(y_preds, axis=0)\n\nmodel2 = VotingModelForLgbm(lgb_models)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T02:08:31.251301Z","iopub.execute_input":"2024-04-25T02:08:31.252454Z","iopub.status.idle":"2024-04-25T02:08:31.278109Z","shell.execute_reply.started":"2024-04-25T02:08:31.252403Z","shell.execute_reply":"2024-04-25T02:08:31.276794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModelForXgboost(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_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        \n        return np.mean(y_preds, axis=0)\n\nmodel3 = VotingModelForXgboost(xg_models)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T02:08:32.237695Z","iopub.execute_input":"2024-04-25T02:08:32.238159Z","iopub.status.idle":"2024-04-25T02:08:32.246102Z","shell.execute_reply.started":"2024-04-25T02:08:32.238126Z","shell.execute_reply":"2024-04-25T02:08:32.244568Z"},"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        \n#         y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]\n        \n#         X[cat_cols] = X[cat_cols].astype(\"category\")\n#         y_preds += [estimator.predict_proba(X) + 0.015 for estimator in self.estimators[5:]]\n        \n#         return np.mean(y_preds, axis=0)\n\n# model = VotingModel(fitted_models_cat+fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-04-24T17:09:08.583608Z","iopub.execute_input":"2024-04-24T17:09:08.583908Z","iopub.status.idle":"2024-04-24T17:09:08.588662Z","shell.execute_reply.started":"2024-04-24T17:09:08.583884Z","shell.execute_reply":"2024-04-24T17:09:08.587764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:54:36.738133Z","iopub.execute_input":"2024-04-25T01:54:36.739090Z","iopub.status.idle":"2024-04-25T01:54:36.771053Z","shell.execute_reply.started":"2024-04-25T01:54:36.739049Z","shell.execute_reply":"2024-04-25T01:54:36.769701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_cat = pd.Series(model1.predict_proba(df_test)[:, 1], index=df_test.index)\ny_pred_cat","metadata":{"execution":{"iopub.status.busy":"2024-04-25T02:08:34.895981Z","iopub.execute_input":"2024-04-25T02:08:34.896434Z","iopub.status.idle":"2024-04-25T02:08:35.018661Z","shell.execute_reply.started":"2024-04-25T02:08:34.896399Z","shell.execute_reply":"2024-04-25T02:08:35.017207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#LGBM VER 4\ny_pred_lgbm = pd.Series(model2.predict_proba(df_test)[:, 1], index=df_test.index)\ny_pred_lgbm","metadata":{"execution":{"iopub.status.busy":"2024-04-25T02:08:35.646380Z","iopub.execute_input":"2024-04-25T02:08:35.647174Z","iopub.status.idle":"2024-04-25T02:08:36.245104Z","shell.execute_reply.started":"2024-04-25T02:08:35.647106Z","shell.execute_reply":"2024-04-25T02:08:36.243809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import xgboost as xgb\ny_pred_xgb = pd.Series(model3.predict_proba(df_test)[:, 1], index=df_test.index)\ny_pred_xgb","metadata":{"execution":{"iopub.status.busy":"2024-04-25T01:54:38.484113Z","iopub.execute_input":"2024-04-25T01:54:38.484436Z","iopub.status.idle":"2024-04-25T01:54:39.216707Z","shell.execute_reply.started":"2024-04-25T01:54:38.484409Z","shell.execute_reply":"2024-04-25T01:54:39.215537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = (y_pred_lgbm + 3*y_pred_cat) / 4\ny_pred","metadata":{"execution":{"iopub.status.busy":"2024-04-24T17:09:29.067661Z","iopub.execute_input":"2024-04-24T17:09:29.068114Z","iopub.status.idle":"2024-04-24T17:09:29.074890Z","shell.execute_reply.started":"2024-04-24T17:09:29.068090Z","shell.execute_reply":"2024-04-24T17:09:29.074148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# y_pred = pd.Series(model.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred_lgbm\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-04-25T02:08:57.035211Z","iopub.execute_input":"2024-04-25T02:08:57.035673Z","iopub.status.idle":"2024-04-25T02:08:57.057471Z","shell.execute_reply.started":"2024-04-25T02:08:57.035635Z","shell.execute_reply":"2024-04-25T02:08:57.056004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}