{"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":8659455,"sourceType":"datasetVersion","datasetId":5188033},{"sourceId":8680045,"sourceType":"datasetVersion","datasetId":5203425},{"sourceId":8685986,"sourceType":"datasetVersion","datasetId":5207723}],"dockerImageVersionId":30733,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\n\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\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\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\nimport joblib\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import KNNImputer","metadata":{"_uuid":"f5343ca9-48ac-4dd7-b2c3-a32cc448e834","_cell_guid":"e51361db-2d8e-4dba-aadd-b1550bdd1276","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.827844Z","iopub.execute_input":"2024-06-13T22:06:06.828729Z","iopub.status.idle":"2024-06-13T22:06:06.837155Z","shell.execute_reply.started":"2024-06-13T22:06:06.828688Z","shell.execute_reply":"2024-06-13T22:06:06.835833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import joblib","metadata":{"_uuid":"30c7ad57-77f8-4f95-aaf1-7a8b3e7ccd03","_cell_guid":"7cf01104-fff9-4cc9-a751-1fb6b2ae4835","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.839712Z","iopub.execute_input":"2024-06-13T22:06:06.840086Z","iopub.status.idle":"2024-06-13T22:06:06.851908Z","shell.execute_reply.started":"2024-06-13T22:06:06.840056Z","shell.execute_reply":"2024-06-13T22:06:06.850705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class HiddenPrints:\n    def __enter__(self):\n        self._original_stdout = sys.stdout\n        sys.stdout = open(os.devnull, 'w')\n        \n    def __exit__(self, exc_type, exc_val, exc_tb):\n        sys.stdout.close()\n        sys.stdout = self._original_stdout\n\n# Use the context manager to suppress the output\nwith HiddenPrints():\n    info = joblib.load(\"/kaggle/input/catmodel-cols-info427/notebook_info (1).joblib\")\n    encoding_cols = info[\"encoding_cols\"]\n    df_train_cols = info['cols']\n    cat_cols = info['cat_cols']","metadata":{"execution":{"iopub.status.busy":"2024-06-13T22:06:06.854032Z","iopub.execute_input":"2024-06-13T22:06:06.854433Z","iopub.status.idle":"2024-06-13T22:06:06.869380Z","shell.execute_reply.started":"2024-06-13T22:06:06.854402Z","shell.execute_reply":"2024-06-13T22:06:06.867918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#infer model to test","metadata":{"_uuid":"bec1c096-bac3-42c8-b057-c54a7b3a8438","_cell_guid":"e9ccd0b9-8efe-441c-b87a-469bf034d7e0","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.870993Z","iopub.execute_input":"2024-06-13T22:06:06.871449Z","iopub.status.idle":"2024-06-13T22:06:06.876980Z","shell.execute_reply.started":"2024-06-13T22:06:06.871407Z","shell.execute_reply":"2024-06-13T22:06:06.875713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#prepare df_test","metadata":{"_uuid":"696f511f-0c56-4dc4-b56e-27d67a934e5b","_cell_guid":"e6ec1a51-a6df-4b03-a15c-12f5a523e350","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.879529Z","iopub.execute_input":"2024-06-13T22:06:06.879986Z","iopub.status.idle":"2024-06-13T22:06:06.891795Z","shell.execute_reply.started":"2024-06-13T22:06:06.879954Z","shell.execute_reply":"2024-06-13T22:06:06.890298Z"},"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()/ -365)\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\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_cv = [(pl.std(col) / pl.mean(col)).alias(f\"cv_{col}\") for col in cols if pl.mean(col) != 0]\n        #expr_cv = [(pl.std(col) / pl.mean(col).filter(pl.mean(col) != 0)).alias(f\"cv_{col}\") for col in cols]\n        #expr_cv = [(pl.when(pl.col(col).mean() != 0).then(pl.col(col).std() / pl.col(col).mean()).otherwise(None)).alias(f\"cv_{col}\") for col in cols] #is std()/mean() really useful\n        return expr_max +expr_last+expr_mean#+expr_cv\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        return  expr_max+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        #expr_cv = [(pl.std(col) / pl.mean(col)).alias(f\"cv_{col}\") for col in cols if pl.mean(col) != 0]\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\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":{"_uuid":"6051f636-8358-4c01-99aa-e4b79a2bda8e","_cell_guid":"32b80d7c-0c70-489a-b201-8e894a65f626","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.894026Z","iopub.execute_input":"2024-06-13T22:06:06.894799Z","iopub.status.idle":"2024-06-13T22:06:06.947110Z","shell.execute_reply.started":"2024-06-13T22:06:06.894747Z","shell.execute_reply":"2024-06-13T22:06:06.945550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_new_feature(df):\n    \n    df = df.with_columns([\n    (pl.col('eir_270L') / pl.col('price_1097A')).alias('interest_share'),\n    (pl.col('disbursedcredamount_1113A') / pl.col('credamount_770A')).alias('cred_disbursed_ratio'),\n    (pl.col('totaldebt_9A') / (1 + pl.col('credamount_770A'))).alias('totaldebt_credamount_ratio'),\n    (pl.col('price_1097A') / pl.col('annuity_780A')).alias('credit_annuity_ratio')\n])\n    df=df.with_columns((pl.col('maxannuity_159A')/pl.col('credamount_770A')).alias('Rate_of_maxandcred'))#0.563提升到0.566\n    df=df.with_columns(((pl.col('currdebt_22A')/pl.col('credamount_770A')).alias('Debt_rate_nonapp')))\n    df=df.with_columns(((pl.col('currdebtcredtyperange_828A')/pl.col('credamount_770A')).alias('Debt_rate')))                \n#     df = df.with_columns(\n#     (df['last_contaddr_matchlist_1032L'] == df['last_contaddr_smempladdr_334L']).cast(pl.Int32).alias(\"comparison_contaddr\")\n# )#这个可以试一下，如果没啥增加把这个删了\n#     df= df.with_columns(\n#     (df['avgoutstandbalancel6m_4187114A'] <= (df['avgpmtlast12m_4525200A']/2)).cast(pl.Int8).alias(\"ability\"))#4.19\n#     df=df.with_columns((pl.col('amtinstpaidbefduel24m_4187115A')/24*pl.col('annuity_780A')).alias('crredit_annuity_ratio'))\n#     df = df.with_columns(\n#     (df['maininc_215A'] / df['currdebtcredtyperange_828A'].replace(0,0.1))  # 将0替换为0.1避免分母为0\n#     .cast(pl.Float32)  # 使用Float64明确指定数据类型\n#     .alias(\"rate_of_money\") \n# )\n    return df","metadata":{"_uuid":"22530739-3e92-4a6f-9e30-8bbdbd2bbb17","_cell_guid":"7815af84-ff35-4c22-9b8a-fe13422e64ff","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.949528Z","iopub.execute_input":"2024-06-13T22:06:06.950014Z","iopub.status.idle":"2024-06-13T22:06:06.965130Z","shell.execute_reply.started":"2024-06-13T22:06:06.949970Z","shell.execute_reply":"2024-06-13T22:06:06.963868Z"},"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\"","metadata":{"_uuid":"1918bb39-5d8a-4d56-ba44-20ce11d29cf6","_cell_guid":"faf57c69-9176-4fdb-8498-f5f6e69b751d","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.966699Z","iopub.execute_input":"2024-06-13T22:06:06.967191Z","iopub.status.idle":"2024-06-13T22:06:06.981405Z","shell.execute_reply.started":"2024-06-13T22:06:06.967147Z","shell.execute_reply":"2024-06-13T22:06:06.980281Z"},"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":{"_uuid":"2abb04dd-4620-4997-a569-69fddb2b513b","_cell_guid":"f53f7122-56f5-4b92-9fe8-970cc11d048e","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:06.984090Z","iopub.execute_input":"2024-06-13T22:06:06.984680Z","iopub.status.idle":"2024-06-13T22:06:07.211250Z","shell.execute_reply.started":"2024-06-13T22:06:06.984646Z","shell.execute_reply":"2024-06-13T22:06:07.209436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndf_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()\n#df_test = df_test.pipe(Pipeline.filter_cols)","metadata":{"_uuid":"dd0bb1c6-cdc2-4ec0-8a2e-f2c7017553a3","_cell_guid":"78fb9018-37e5-4a6f-981c-a6ff407af7bb","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:07.212719Z","iopub.execute_input":"2024-06-13T22:06:07.213091Z","iopub.status.idle":"2024-06-13T22:06:07.455709Z","shell.execute_reply.started":"2024-06-13T22:06:07.213058Z","shell.execute_reply":"2024-06-13T22:06:07.454609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import tqdm\nnum_cols = df_test.select('^*A$').columns#挑选出全部跟钱有关的列\nfor col in tqdm(num_cols,total=len(num_cols)):#将所有数字如果null的全部设置为0\n    df_test=df_test.with_columns(pl.col(col).fill_null(0))\ndel num_cols\ngc.collect()","metadata":{"_uuid":"1cfa9456-a388-471e-a4b4-4ddf9bd129e6","_cell_guid":"664435ec-14d1-45a8-9eaa-2634bf3ae08d","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:07.457093Z","iopub.execute_input":"2024-06-13T22:06:07.457444Z","iopub.status.idle":"2024-06-13T22:06:07.733190Z","shell.execute_reply.started":"2024-06-13T22:06:07.457413Z","shell.execute_reply":"2024-06-13T22:06:07.731685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import re\n# encoding_cols_other = df_test.select(pl.selectors.by_dtype([pl.String, pl.Categorical])).columns\n# filtered_cols = [col for col in encoding_cols_other if not re.match(r\"^(max|mean|first|last)\", col)]\nfor col in encoding_cols:\n    df_test = df_test.with_columns(pl.col(col).fill_null('Missing'))\n\n#del encoding_cols\ngc.collect()","metadata":{"_uuid":"ab1c678d-5d36-4508-9e41-bc48454603a5","_cell_guid":"97056b83-33cc-41d1-b437-3d545e86dc34","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:07.734876Z","iopub.execute_input":"2024-06-13T22:06:07.735331Z","iopub.status.idle":"2024-06-13T22:06:07.934556Z","shell.execute_reply.started":"2024-06-13T22:06:07.735296Z","shell.execute_reply":"2024-06-13T22:06:07.933268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#cnt_encoding_cols = df_train.select(pl.selectors.by_dtype([pl.Boolean])).columns\n\nmappings = {}\nfor col in encoding_cols:\n    mappings[col] = df_test.group_by(col).len()\n\ndf_test_lazy = df_test.select(mappings.keys()).lazy()\n# df_train_lazy = pl.LazyFrame(df_train.select('case_id'))\n\nfor col, mapping in mappings.items():\n    remapping = {category: count for category, count in mapping.rows()}\n    remapping[None] = -2\n    expr = pl.col(col).replace(\n                remapping,\n                default=-1,\n            )\n    df_test_lazy = df_test_lazy.with_columns(expr.alias(col + '_cnt'))\n    del col, mapping, remapping\n    gc.collect()\n\ndel mappings\ntransformed_test = df_test_lazy.collect()\n\ndf_test = pl.concat([df_test, transformed_test.select(\"^*cnt$\")], how='horizontal')\ndel transformed_test\ndel encoding_cols\n\ngc.collect()","metadata":{"_uuid":"4e77f815-fb67-45e5-836e-880e20ef940b","_cell_guid":"f8308c93-740a-43b1-aca9-0a560da858c2","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:07.936043Z","iopub.execute_input":"2024-06-13T22:06:07.936446Z","iopub.status.idle":"2024-06-13T22:06:24.527632Z","shell.execute_reply.started":"2024-06-13T22:06:07.936412Z","shell.execute_reply":"2024-06-13T22:06:24.526303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test=create_new_feature(df_test)","metadata":{"_uuid":"ac73b0a2-51f6-483e-9fbf-544fc6c9abfe","_cell_guid":"811148e5-5593-4d44-8b2c-b79814793a8f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:24.529558Z","iopub.execute_input":"2024-06-13T22:06:24.530051Z","iopub.status.idle":"2024-06-13T22:06:24.539111Z","shell.execute_reply.started":"2024-06-13T22:06:24.530006Z","shell.execute_reply":"2024-06-13T22:06:24.537806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ndf_test = df_test.select([col for col in df_train_cols if col not in [\"target\"]])\n\n#print(\"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":{"_uuid":"d927d215-42f5-490f-9a19-da85aa322877","_cell_guid":"36e192c3-a57b-4240-a085-8726ee3a721a","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:24.542713Z","iopub.execute_input":"2024-06-13T22:06:24.543139Z","iopub.status.idle":"2024-06-13T22:06:24.968387Z","shell.execute_reply.started":"2024-06-13T22:06:24.543106Z","shell.execute_reply":"2024-06-13T22:06:24.967039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the VotingModel class\nclass 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[:5]]\n        return np.mean(y_preds, axis=0)\n\nwith HiddenPrints():\n    model = joblib.load(\"/kaggle/input/catmodel427/cat_model.pkl\")","metadata":{"_uuid":"b7eb2a18-df74-45a6-b7c6-ede5c3a663d3","_cell_guid":"f4eca360-ea03-4569-8ab2-3085b3c78882","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:24.969943Z","iopub.execute_input":"2024-06-13T22:06:24.970401Z","iopub.status.idle":"2024-06-13T22:06:28.625151Z","shell.execute_reply.started":"2024-06-13T22:06:24.970361Z","shell.execute_reply":"2024-06-13T22:06:28.623866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{"_uuid":"710ba53d-1e62-4136-b460-e1d9af6c08fc","_cell_guid":"2580e5f2-47be-4632-b17d-755c4e2f1d41","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:28.626510Z","iopub.execute_input":"2024-06-13T22:06:28.626853Z","iopub.status.idle":"2024-06-13T22:06:28.666033Z","shell.execute_reply.started":"2024-06-13T22:06:28.626826Z","shell.execute_reply":"2024-06-13T22:06:28.664809Z"},"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\")\n\n\ny_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\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"_uuid":"aa872d3c-efa8-4242-b1fd-0038f71d1e2d","_cell_guid":"d3425cb9-a82e-49be-95ff-806ff3050320","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-06-13T22:06:28.667375Z","iopub.execute_input":"2024-06-13T22:06:28.667863Z","iopub.status.idle":"2024-06-13T22:06:28.824524Z","shell.execute_reply.started":"2024-06-13T22:06:28.667822Z","shell.execute_reply":"2024-06-13T22:06:28.823273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean up all other files in the working directory\nfor filepath in glob('/kaggle/working/*'):\n    if filepath != \"/kaggle/working/submission.csv\":\n        try:\n            os.remove(filepath)\n        except Exception as e:\n            print(f\"Error deleting file {filepath}: {e}\")\n\nprint(f\"Files remaining in working directory: {os.listdir('/kaggle/working/')}\")","metadata":{"execution":{"iopub.status.busy":"2024-06-13T22:14:49.131244Z","iopub.execute_input":"2024-06-13T22:14:49.131692Z","iopub.status.idle":"2024-06-13T22:14:49.140385Z","shell.execute_reply.started":"2024-06-13T22:14:49.131658Z","shell.execute_reply":"2024-06-13T22:14:49.139141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}