{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nimport subprocess\nimport os\nimport gc\nimport lightgbm as lgb\nimport xgboost as xgb\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom catboost import CatBoostClassifier, Pool\nfrom pathlib import Path\nfrom glob import glob\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:47:53.334895Z","iopub.execute_input":"2024-05-27T14:47:53.335174Z","iopub.status.idle":"2024-05-27T14:47:58.702005Z","shell.execute_reply.started":"2024-05-27T14:47:53.335148Z","shell.execute_reply":"2024-05-27T14:47:58.701249Z"},"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:  # 删除缺失率超过70%的特征\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\nclass Aggregator:\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        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        expr_var = [pl.var(col).alias(f\"var_{col}\") for col in cols]\n        \n        \n        return expr_max + expr_last + expr_mean + expr_var + expr_count\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_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{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_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n\n        return  expr_max + expr_last\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_last = [pl.last(col).alias(f\"last_{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_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        \n        return  expr_max +expr_last+expr_count\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\n\ndef 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\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\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\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-05-27T14:47:58.703539Z","iopub.execute_input":"2024-05-27T14:47:58.703815Z","iopub.status.idle":"2024-05-27T14:47:58.742974Z","shell.execute_reply.started":"2024-05-27T14:47:58.703792Z","shell.execute_reply":"2024-05-27T14:47:58.742297Z"},"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-05-27T14:47:58.743869Z","iopub.execute_input":"2024-05-27T14:47:58.744110Z","iopub.status.idle":"2024-05-27T14:47:58.756324Z","shell.execute_reply.started":"2024-05-27T14:47:58.744089Z","shell.execute_reply":"2024-05-27T14:47:58.755626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\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}\n","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:47:58.758215Z","iopub.execute_input":"2024-05-27T14:47:58.758481Z","iopub.status.idle":"2024-05-27T14:50:18.428943Z","shell.execute_reply.started":"2024-05-27T14:47:58.758455Z","shell.execute_reply":"2024-05-27T14:50:18.427945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndf_train_2 = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train_2.shape)\ndel data_store\ngc.collect()\ndf_train_2 = df_train_2.pipe(Pipeline.filter_cols)\ndf_train_2, cat_cols = to_pandas(df_train_2)\ndf_train_2 = reduce_mem_usage(df_train_2)\nprint(\"train data shape:\\t\", df_train_2.shape)\n\nnums = df_train_2.select_dtypes(exclude='category').columns\nnans_df = df_train_2[nums].isna()\nnans_groups = {}\nfor col in nums:\n    cur_group = nans_df[col].sum()\n    try:\n        nans_groups[cur_group].append(col)\n    except:\n        nans_groups[cur_group]=[col]\ndel nans_df; x = gc.collect()\n\ndef reduce_group(grps):\n    use = []\n    for g in grps:\n        mx = 0; vx = g[0]\n        for gg in g:\n            n = df_train_2[gg].nunique()\n            if n > mx:\n                mx = n\n                vx = gg\n        use.append(vx)\n    return use\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    # 计算列之间的相关性\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\nuses = []\nfor k,v in nans_groups.items():\n    if len(v) > 1:\n            Vs = nans_groups[k]\n            grps = group_columns_by_correlation(df_train_2[Vs], threshold=0.8)\n            use = reduce_group(grps)\n            uses = uses + use\n    else:\n        uses = uses + v\n        \nprint(len(uses))\nuses = uses + list(df_train_2.select_dtypes(include='category').columns)\nprint(len(uses))\nprint(uses)\ndf_train_2 = df_train_2[uses]","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:50:18.430193Z","iopub.execute_input":"2024-05-27T14:50:18.430561Z","iopub.status.idle":"2024-05-27T14:52:10.158074Z","shell.execute_reply.started":"2024-05-27T14:50:18.430528Z","shell.execute_reply":"2024-05-27T14:52:10.157143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv(\"/kaggle/input/home-credit-credit-risk-model-stability/sample_submission.csv\")\ndevice='gpu'\nn_est = 8000\nDRY_RUN = True if sample.shape[0] == 10 else False\nif DRY_RUN:\n    device='cpu'\n    df_train_2 = df_train_2.iloc[:50000]\n    n_est=800\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:10.159206Z","iopub.execute_input":"2024-05-27T14:52:10.159507Z","iopub.status.idle":"2024-05-27T14:52:10.174848Z","shell.execute_reply.started":"2024-05-27T14:52:10.159483Z","shell.execute_reply":"2024-05-27T14:52:10.174004Z"},"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_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-05-27T14:52:10.175947Z","iopub.execute_input":"2024-05-27T14:52:10.176259Z","iopub.status.idle":"2024-05-27T14:52:10.492395Z","shell.execute_reply.started":"2024-05-27T14:52:10.176229Z","shell.execute_reply":"2024-05-27T14:52:10.491687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_2 = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test_2.shape)\ndel data_store\ngc.collect()\ndf_test_2 = df_test_2.select([col for col in df_train_2.columns if col != \"target\"])\nprint(\"train data shape:\\t\", df_train_2.shape)\nprint(\"test data shape:\\t\", df_test_2.shape)\n\ndf_test_2, cat_cols = to_pandas(df_test_2, cat_cols)\ndf_test_2 = reduce_mem_usage(df_test_2)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:10.493612Z","iopub.execute_input":"2024-05-27T14:52:10.493947Z","iopub.status.idle":"2024-05-27T14:52:11.018599Z","shell.execute_reply.started":"2024-05-27T14:52:10.493917Z","shell.execute_reply":"2024-05-27T14:52:11.017747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_2 = df_train_2[\"target\"]\nweeks = df_train_2[\"WEEK_NUM\"]\ndf_train_2 = df_train_2.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:11.019636Z","iopub.execute_input":"2024-05-27T14:52:11.019880Z","iopub.status.idle":"2024-05-27T14:52:11.161378Z","shell.execute_reply.started":"2024-05-27T14:52:11.019859Z","shell.execute_reply":"2024-05-27T14:52:11.160587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train_2[cat_cols] = df_train_2[cat_cols].astype(str)\ndf_test_2[cat_cols] = df_test_2[cat_cols].astype(str)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:11.165611Z","iopub.execute_input":"2024-05-27T14:52:11.165903Z","iopub.status.idle":"2024-05-27T14:52:11.443146Z","shell.execute_reply.started":"2024-05-27T14:52:11.165879Z","shell.execute_reply":"2024-05-27T14:52:11.442372Z"},"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.05,\n    \"n_estimators\": 2000,  \n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"random_state\": 1024,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    'num_leaves':64,\n    \"device\": device, \n    \"verbose\": -1,\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:11.444185Z","iopub.execute_input":"2024-05-27T14:52:11.444460Z","iopub.status.idle":"2024-05-27T14:52:11.449695Z","shell.execute_reply.started":"2024-05-27T14:52:11.444415Z","shell.execute_reply":"2024-05-27T14:52:11.448823Z"},"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\": 2000,  \n#     \"colsample_bytree\": 0.8,\n#     \"random_state\": 1024,\n#     \"reg_alpha\": 0.5,\n#     \"reg_lambda\": 15,\n#     \"extra_trees\": True,\n#     'num_leaves': 64,\n#     \"device\": device, \n#     \"verbose\": -1,\n# }\n\n# params2 = {\n#     \"booster\": \"gbtree\",\n#     \"objective\": \"binary:logistic\",\n#     \"eval_metric\": \"auc\",\n#     \"max_depth\": 10,\n#     \"learning_rate\": 0.03,\n#     \"n_estimators\": 1000,\n#     \"colsample_bytree\": 0.8,\n#     \"colsample_bynode\": 0.8,\n#     \"alpha\": 0.5,  \n#     \"lambda\": 15,  \n#     \"tree_method\": 'gpu_hist' if device == 'gpu' else 'auto',\n#     \"random_state\": 1024,\n#     \"verbosity\": 0,\n#     \"enable_categorical\": True,\n# }","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:11.450813Z","iopub.execute_input":"2024-05-27T14:52:11.451119Z","iopub.status.idle":"2024-05-27T14:52:11.459235Z","shell.execute_reply.started":"2024-05-27T14:52:11.451097Z","shell.execute_reply":"2024-05-27T14:52:11.458465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fitted_models_cat = []\n# fitted_models_lgb = []\n# fitted_models_xgb = []\n\n# cv_scores_cat = []\n# cv_scores_lgb = []\n# cv_scores_xgb = []\n\n\n# for idx_train, idx_valid in cv.split(df_train_2, y_2, groups=weeks):\n#     X_train, y_train = df_train_2.iloc[idx_train], y_2.iloc[idx_train]\n#     X_valid, y_valid = df_train_2.iloc[idx_valid], y_2.iloc[idx_valid]\n    \n#     train_pool = Pool(X_train, y_train, cat_features=cat_cols)\n#     val_pool = Pool(X_valid, y_valid, cat_features=cat_cols)\n    \n#     clf = CatBoostClassifier(\n#     eval_metric='AUC',\n#     task_type='GPU',\n#     learning_rate=0.03,\n#     iterations=n_est)\n    \n#     clf.fit(train_pool, eval_set=val_pool, verbose=300)\n#     fitted_models_cat.append(clf)\n    \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(60)])\n#     fitted_models_lgb.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_lgb.append(auc_score)\n    \n    \n#     model2 = xgb.XGBClassifier(**params2)\n#     model2.fit(\n#         X_train, y_train,\n#         eval_set=[(X_valid, y_valid)],\n#         early_stopping_rounds=60, verbose=False)\n    \n#     fitted_models_xgb.append(model2)\n    \n#     y_pred_valid = model2.predict_proba(X_valid)[:, 1]\n#     auc_score = roc_auc_score(y_valid, y_pred_valid)\n#     cv_scores_xgb.append(auc_score)\n    \n#     del clf, model, model2, X_train, y_train, X_valid, y_valid, y_pred_valid\n#     gc.collect()\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))\n\n# print(\"CV AUC scores: \", cv_scores_xgb)\n# print(\"Maximum CV AUC score: \", max(cv_scores_xgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:11.460582Z","iopub.execute_input":"2024-05-27T14:52:11.460963Z","iopub.status.idle":"2024-05-27T14:52:11.469608Z","shell.execute_reply.started":"2024-05-27T14:52:11.460904Z","shell.execute_reply":"2024-05-27T14:52:11.468686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fitted_models_cat = []\nfitted_models_lgb = []\n\ncv_scores_cat = []\ncv_scores_lgb = []\n\n\nfor idx_train, idx_valid in cv.split(df_train_2, y_2, groups=weeks):#\n    X_train, y_train = df_train_2.iloc[idx_train], y_2.iloc[idx_train]# \n    X_valid, y_valid = df_train_2.iloc[idx_valid], y_2.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(\n    eval_metric='AUC',\n    task_type='GPU',\n    learning_rate=0.03,\n    iterations=n_est)\n    random_seed=3107\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    \nprint(\"CV AUC scores: \", cv_scores_cat)\nprint(\"Maximum CV AUC score: \", max(cv_scores_cat))\n\n\nprint(\"CV AUC scores: \", cv_scores_lgb)\nprint(\"Maximum CV AUC score: \", max(cv_scores_lgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:52:11.470733Z","iopub.execute_input":"2024-05-27T14:52:11.471052Z","iopub.status.idle":"2024-05-27T15:00:06.795883Z","shell.execute_reply.started":"2024-05-27T14:52:11.471019Z","shell.execute_reply":"2024-05-27T15:00:06.794918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del y_2 \ndel df_train_2\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:06.797116Z","iopub.execute_input":"2024-05-27T15:00:06.797561Z","iopub.status.idle":"2024-05-27T15:00:06.970335Z","shell.execute_reply.started":"2024-05-27T15:00:06.797527Z","shell.execute_reply":"2024-05-27T15:00:06.969490Z"},"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) for estimator in self.estimators[5:]]\n#         y_preds += y_preds\n#         y_preds += [estimator.predict_proba(X) for estimator in self.estimators[10:]]\n        print(len(y_preds))\n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models_cat + fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:06.971516Z","iopub.execute_input":"2024-05-27T15:00:06.971806Z","iopub.status.idle":"2024-05-27T15:00:06.981197Z","shell.execute_reply.started":"2024-05-27T15:00:06.971783Z","shell.execute_reply":"2024-05-27T15:00:06.980419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del fitted_models_cat, fitted_models_lgb\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:06.982219Z","iopub.execute_input":"2024-05-27T15:00:06.982523Z","iopub.status.idle":"2024-05-27T15:00:07.071034Z","shell.execute_reply.started":"2024-05-27T15:00:06.982483Z","shell.execute_reply":"2024-05-27T15:00:07.070221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_2 = df_test_2.drop(columns=[\"WEEK_NUM\"])\ndf_test_2 = df_test_2.set_index(\"case_id\")","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:07.072107Z","iopub.execute_input":"2024-05-27T15:00:07.072418Z","iopub.status.idle":"2024-05-27T15:00:07.102422Z","shell.execute_reply.started":"2024-05-27T15:00:07.072393Z","shell.execute_reply":"2024-05-27T15:00:07.101769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_2 = pd.Series(model.predict_proba(df_test_2)[:, 1], index=df_test_2.index)\n\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred_2\n","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:07.103615Z","iopub.execute_input":"2024-05-27T15:00:07.103936Z","iopub.status.idle":"2024-05-27T15:00:07.600107Z","shell.execute_reply.started":"2024-05-27T15:00:07.103907Z","shell.execute_reply":"2024-05-27T15:00:07.599158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del df_test_2\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:07.601503Z","iopub.execute_input":"2024-05-27T15:00:07.601998Z","iopub.status.idle":"2024-05-27T15:00:07.703379Z","shell.execute_reply.started":"2024-05-27T15:00:07.601971Z","shell.execute_reply":"2024-05-27T15:00:07.702452Z"},"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())\n        df = df.drop(\"date_decision\", \"MONTH\")\n        return df\n\n    def filter_cols(df):\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\ndef get_exprs(df):\n    cols = [col for col in df.columns if col[-1] in (\"P\", \"A\", \"D\", \"M\", \"T\", \"L\") or \"num_group\" in col]\n    expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols] \n    return expr_max\n\ndef 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(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(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\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\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\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    \n    for col in df.columns:\n        col_type = df[col].dtype\n        if str(col_type)==\"category\":\n            continue\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            continue\n    end_mem = df.memory_usage().sum() / 1024**2    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:07.705041Z","iopub.execute_input":"2024-05-27T15:00:07.705680Z","iopub.status.idle":"2024-05-27T15:00:07.733522Z","shell.execute_reply.started":"2024-05-27T15:00:07.705644Z","shell.execute_reply":"2024-05-27T15:00:07.732544Z"},"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_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    ]\n}\n\n\ndf_train = feature_eng(**data_store)\ndel data_store\ngc.collect()\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nnums = df_train.select_dtypes(exclude='category').columns\nnans_df = df_train[nums].isna()\nnans_groups={}\nfor col in nums:\n    cur_group = nans_df[col].sum()\n    try:\n        nans_groups[cur_group].append(col)\n    except:\n        nans_groups[cur_group]=[col]\ndel nans_df; x=gc.collect()\n\ndef reduce_group(grps):\n    use = []\n    for g in grps:\n        mx = 0; vx = g[0]\n        for gg in g:\n            n = df_train[gg].nunique()\n            if n>mx:\n                mx = n\n                vx = gg\n        use.append(vx)\n    return use\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    correlation_matrix = matrix.corr()\n    groups = []\n    remaining_cols = list(matrix.columns)\n    while remaining_cols:\n        col = remaining_cols.pop(0)\n        group = [col]\n        correlated_cols = [col]\n        for c in remaining_cols:\n            if correlation_matrix.loc[col, c] >= threshold:\n                group.append(c)\n                correlated_cols.append(c)\n        groups.append(group)\n        remaining_cols = [c for c in remaining_cols if c not in correlated_cols]\n    \n    return groups\n\nuses = []\nfor k,v in nans_groups.items():\n    if len(v) > 1:\n            Vs = nans_groups[k]\n            grps = group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use = reduce_group(grps)\n            uses = uses + use\n    else:\n        uses = uses + v\n\ndf_train = df_train[uses]\n\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    ]\n}\n\ndf_test = feature_eng(**data_store)\ndel data_store\ngc.collect()\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\ndf_test, cat_cols = to_pandas(df_test)\ndf_test = reduce_mem_usage(df_test)\ngc.collect()\n\ndf_train['target'] = 0\ndf_test['target'] = 1\n\ndf_train = pd.concat([df_train,df_test])\ndf_train = reduce_mem_usage(df_train)\n\ny = df_train[\"target\"]\ndf_train = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:00:07.735170Z","iopub.execute_input":"2024-05-27T15:00:07.735606Z","iopub.status.idle":"2024-05-27T15:02:31.932492Z","shell.execute_reply.started":"2024-05-27T15:00:07.735563Z","shell.execute_reply":"2024-05-27T15:02:31.931692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fitted_models_lgb = []\nmodel = lgb.LGBMClassifier()\nmodel.fit(df_train, y)\nfitted_models_lgb.append(model)  ","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:02:31.934034Z","iopub.execute_input":"2024-05-27T15:02:31.934357Z","iopub.status.idle":"2024-05-27T15:04:12.438825Z","shell.execute_reply.started":"2024-05-27T15:02:31.934327Z","shell.execute_reply":"2024-05-27T15:04:12.437873Z"},"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        \n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:04:12.440087Z","iopub.execute_input":"2024-05-27T15:04:12.440371Z","iopub.status.idle":"2024-05-27T15:04:12.449186Z","shell.execute_reply.started":"2024-05-27T15:04:12.440348Z","shell.execute_reply":"2024-05-27T15:04:12.448443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\",'target'])\ndf_test = df_test.set_index(\"case_id\")\n\ny_pred = pd.Series(model.predict_proba(df_test)[:,1], index=df_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:04:12.450297Z","iopub.execute_input":"2024-05-27T15:04:12.450658Z","iopub.status.idle":"2024-05-27T15:04:12.479417Z","shell.execute_reply.started":"2024-05-27T15:04:12.450627Z","shell.execute_reply":"2024-05-27T15:04:12.478743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ncondition = y_pred < 0.978\ndf_subm.loc[condition, 'score'] = (df_subm.loc[condition, 'score'] * 0.978 - 0.0718).clip(0)\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:04:12.963007Z","iopub.status.idle":"2024-05-27T15:04:12.963479Z","shell.execute_reply.started":"2024-05-27T15:04:12.963228Z","shell.execute_reply":"2024-05-27T15:04:12.963246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del df_test, df_train\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-27T15:04:12.965075Z","iopub.status.idle":"2024-05-27T15:04:12.965475Z","shell.execute_reply.started":"2024-05-27T15:04:12.965259Z","shell.execute_reply":"2024-05-27T15:04:12.965275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}