{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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":9684817,"sourceType":"datasetVersion","datasetId":5920189},{"sourceId":9684922,"sourceType":"datasetVersion","datasetId":5920266},{"sourceId":9684995,"sourceType":"datasetVersion","datasetId":5920315},{"sourceId":9685065,"sourceType":"datasetVersion","datasetId":5920346},{"sourceId":142211,"sourceType":"modelInstanceVersion","modelInstanceId":120476,"modelId":143686},{"sourceId":142358,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":120597,"modelId":143801},{"sourceId":144465,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":122441,"modelId":145526},{"sourceId":145500,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":123363,"modelId":146431}],"dockerImageVersionId":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-24T15:32:19.490531Z","iopub.execute_input":"2024-10-24T15:32:19.490935Z","iopub.status.idle":"2024-10-24T15:32:20.907474Z","shell.execute_reply.started":"2024-10-24T15:32:19.490894Z","shell.execute_reply":"2024-10-24T15:32:20.906063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport gc\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport joblib\nimport lightgbm as lgb\nimport torch\nimport torch.nn as nn\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.preprocessing import LabelEncoder\n\nimport warnings\nfrom catboost import CatBoostClassifier, Pool","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:32:20.909357Z","iopub.execute_input":"2024-10-24T15:32:20.909857Z","iopub.status.idle":"2024-10-24T15:32:29.417488Z","shell.execute_reply.started":"2024-10-24T15:32:20.909815Z","shell.execute_reply":"2024-10-24T15:32:29.416136Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"columns_to_select_1 = pd.read_csv('/kaggle/input/colsname/cols.csv')\ncolumns_to_select_1=columns_to_select_1['0'].values.tolist()\ncolumns_to_select = pd.read_csv('/kaggle/input/colsname2/cols2.csv')\ncolumns_to_select=columns_to_select['0'].values.tolist()\nconstant_cols = pd.read_csv('/kaggle/input/cols-constant/constant_cols.csv')\nconstant_cols=constant_cols['0'].values.tolist()\ncategorical_cols = pd.read_csv('/kaggle/input/categorical-cols/categorical_cols.csv')\ncategorical_cols=categorical_cols['0'].values.tolist()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:32:29.418944Z","iopub.execute_input":"2024-10-24T15:32:29.419587Z","iopub.status.idle":"2024-10-24T15:32:29.477462Z","shell.execute_reply.started":"2024-10-24T15:32:29.419543Z","shell.execute_reply":"2024-10-24T15:32:29.476222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import xgboost as xgb\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nmodel = xgb.Booster()\nmodel.load_model('/kaggle/input/model1024v2/scikitlearn/default/1/xgboost_model.json')","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:33.292937Z","iopub.execute_input":"2024-10-23T15:28:33.293373Z","iopub.status.idle":"2024-10-23T15:28:33.405878Z","shell.execute_reply.started":"2024-10-23T15:28:33.293325Z","shell.execute_reply":"2024-10-23T15:28:33.404860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def deal_df(df):\n    for col in df.columns:\n        if df[col].dtype == pl.Utf8:\n            df = df.with_columns(pl.col(col).cast(pl.Categorical))\n    categorical_columns = [col for col in df.columns if df[col].dtype == pl.Categorical]\n    \n    # 进行独热编码\n    for col in categorical_columns:\n        unique_categories = df[col].unique().to_list()\n        for cat in unique_categories:\n            df = df.with_columns(\n                pl.when(pl.col(col) == cat).then(1).otherwise(0).alias(f'{col}_{cat}')\n            )\n    \n    # 删除原有的分类列\n    df = df.drop(categorical_columns)\n    columns_to_drop = []\n    return df.drop(columns_to_drop)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:34.121688Z","iopub.execute_input":"2024-10-23T15:28:34.122105Z","iopub.status.idle":"2024-10-23T15:28:34.131860Z","shell.execute_reply.started":"2024-10-23T15:28:34.122055Z","shell.execute_reply":"2024-10-23T15:28:34.130539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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\n\n# %% [markdown] {\"papermill\":{\"duration\":0.006776,\"end_time\":\"2024-02-10T04:58:34.934015\",\"exception\":false,\"start_time\":\"2024-02-10T04:58:34.927239\",\"status\":\"completed\"},\"tags\":[]}\n# # Data collection\n\n# %% [code] {\"jupyter\":{\"outputs_hidden\":false},\"execution\":{\"iopub.status.busy\":\"2024-05-05T00:46:20.946731Z\",\"iopub.execute_input\":\"2024-05-05T00:46:20.947315Z\",\"iopub.status.idle\":\"2024-05-05T00:46:20.973026Z\",\"shell.execute_reply.started\":\"2024-05-05T00:46:20.947282Z\",\"shell.execute_reply\":\"2024-05-05T00:46:20.972161Z\"}}\nclass Pipeline:\n    @staticmethod\n    def set_table_dtypes(df):\n        for col in df.columns:\n            if col in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Int32))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col[-1] in (\"P\", \"A\"):\n                df = df.with_columns(pl.col(col).cast(pl.Float64))\n            elif col[-1] in (\"M\",):\n                df = df.with_columns(pl.col(col).cast(pl.String))\n            elif col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col).cast(pl.Date))            \n\n        return df\n    \n    @staticmethod\n    def handle_dates(df):\n        for col in df.columns:\n            if col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col) - pl.col(\"date_decision\"))\n                df = df.with_columns(pl.col(col).dt.total_days())\n                df = df.with_columns(pl.col(col).cast(pl.Float32))\n                \n        df = df.drop(\"date_decision\", \"MONTH\")\n\n        return df\n    \n    @staticmethod\n    def filter_cols(df):\n        for col in df.columns:\n            if col not in [\"target\", \"case_id\", \"WEEK_NUM\"]:\n                isnull = df[col].is_null().mean()\n\n                # # TODO: Revisar el sentido de este filtro         \n                # if col[-1]=='M':\n                #     specific_value_ratio = df.filter(pl.col(col) == \"a55475b1\").height / df.height\n                #     if specific_value_ratio > 0.95:\n                #         df = df.drop(col)\n                        \n                if isnull > 0.95:\n                    df = df.drop(col)\n                    \n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) & (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n\n                if (freq == 1) | (freq > 50):\n                    df = df.drop(col)\n            \n            # # eliminate yaer, month feature\n            # if (col[-1] not in [\"P\", \"A\", \"L\", \"M\"]) and (('month_' in col) or ('year_' in col)):\n            #     df = df.drop(col)\n        \n        # for col in cols_drop:\n        #     if col in df.columns:\n        #         df = df.drop(col)\n            \n        return df\n\n    \n    # Añadidos los 3 siguientes metodos\n    @staticmethod\n    def reduce_memory_usage_pl(df):\n        \"\"\" Reduce memory usage by polars dataframe {df} with name {name} by changing its data types.\n            Original pandas version of this function: https://www.kaggle.com/code/arjanso/reducing-dataframe-memory-size-by-65 \n        \"\"\"\n        print(f\"Memory usage of dataframe is {round(df.estimated_size('mb'), 2)} MB\")\n        \n        Numeric_Int_types = [pl.Int8, pl.Int16, pl.Int32, pl.Int64]\n        Numeric_Float_types = [pl.Float32, pl.Float64]    \n        \n        for col in df.columns:\n            if col == 'case_id': \n                continue\n            try:\n                col_type = df[col].dtype\n                \n                if col_type == pl.Categorical:\n                    continue\n                    \n                c_min = df[col].min()\n                c_max = df[col].max()\n                \n                if col_type in Numeric_Int_types:\n                    if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                        df = df.with_columns(df[col].cast(pl.Int8))\n                    elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                        df = df.with_columns(df[col].cast(pl.Int16))\n                    elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                        df = df.with_columns(df[col].cast(pl.Int32))\n                    elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                        df = df.with_columns(df[col].cast(pl.Int64))\n                \n                elif col_type in Numeric_Float_types:\n                    if c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                        df = df.with_columns(df[col].cast(pl.Float32))\n                    else:\n                        pass\n                # elif col_type == pl.Utf8:\n                #     df = df.with_columns(df[col].cast(pl.Categorical))\n                else:\n                    pass\n            except:\n                pass\n        print(f\"Memory usage of dataframe became {round(df.estimated_size('mb'), 2)} MB\")\n        return df\n        \n    @staticmethod\n    def fill_missing_values(df):\n        num_cnt = 0\n        cat_cnt = 0\n        for col in df.columns:\n            if df[col].dtype.is_numeric():\n                df = df.with_columns(pl.col(col).fill_null(-1).alias(col))\n                num_cnt += 1\n            else:\n                df = df.with_columns(pl.col(col).fill_null(\"Missing\").alias(col))\n                cat_cnt += 1\n        print(\"num_cnt : \", num_cnt)\n        print(\"cat_cnt : \", cat_cnt)\n        return df\n\n# %% [code] {\"jupyter\":{\"outputs_hidden\":false},\"execution\":{\"iopub.status.busy\":\"2024-05-05T00:46:20.974176Z\",\"iopub.execute_input\":\"2024-05-05T00:46:20.974509Z\",\"iopub.status.idle\":\"2024-05-05T00:46:20.990447Z\",\"shell.execute_reply.started\":\"2024-05-05T00:46:20.974478Z\",\"shell.execute_reply\":\"2024-05-05T00:46:20.989676Z\"}}\nclass Aggregator:\n    @staticmethod\n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols] + [pl.min(col).alias(f\"min_{col}\") for col in cols] # + [pl.sum(col).alias(f\"sum_{col}\") for col in cols]\n        # expr_diff = [pl.col(col).diff().alias(f\"diff_{col}\") for col in cols]\n\n        return expr_max + [pl.mean(col).alias(f\"mean_{col}\") for col in cols] + [pl.std(col).alias(f\"std_{col}\") for col in cols] # + expr_diff\n    \n        # [pl.col(col).drop_nulls().last().alias(f\"last_{col}\") for col in cols]\n\n    @staticmethod\n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\",)] \n            \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols] + [pl.min(col).alias(f\"min_{col}\") for col in cols] # + [pl.sum(col).alias(f\"sum_{col}\") for col in cols]\n\n        return expr_max # + [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n\n    @staticmethod\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        \n        expr_max = [pl.last(col).alias(f\"last_{col}\") for col in cols] + \\\n            [pl.n_unique(col).alias(f\"n_unique_{col}\") for col in cols] + \\\n            [pl.first(col).alias(f\"first_{col}\") for col in cols]  # High Value\n\n        return expr_max\n\n    @staticmethod\n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols] + [pl.min(col).alias(f\"min_{col}\") for col in cols] + [pl.sum(col).alias(f\"sum_{col}\") for col in cols]\n\n        return expr_max # + [pl.mean(col).alias(f\"mean_{col}\") for col in cols] + [pl.std(col).alias(f\"std_{col}\") for col in cols]\n    \n    @staticmethod\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols] # + [pl.n_unique(col).alias(f\"n_unique_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs\n\n# %% [code] {\"jupyter\":{\"outputs_hidden\":false},\"execution\":{\"iopub.status.busy\":\"2024-05-05T00:46:20.991497Z\",\"iopub.execute_input\":\"2024-05-05T00:46:20.991771Z\",\"iopub.status.idle\":\"2024-05-05T00:46:21.007096Z\",\"shell.execute_reply.started\":\"2024-05-05T00:46:20.991749Z\",\"shell.execute_reply\":\"2024-05-05T00:46:21.006226Z\"}}\ndef read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    \n    if depth in [1]:\n        df = df.sort(\"num_group1\").group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    elif depth in [2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    df = df.pipe(Pipeline.reduce_memory_usage_pl)\n    return df\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.set_table_dtypes)\n        \n        if depth in [1]:\n            df = df.sort(\"num_group1\").group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        elif depth in [2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        \n        chunks.append(df)\n        \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    \n    df = df.pipe(Pipeline.reduce_memory_usage_pl)\n    \n    return df\n\ndef feature_eng(df_base, depth_0, depth_1, depth_2, is_train=True):\n    df_base = (\n        df_base\n        .with_columns(\n            decision_month = pl.col(\"date_decision\").dt.month(),\n            decision_weekday = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n        \n    for i, df in enumerate(depth_0 + depth_1 + depth_2):\n        df_base = df_base.join(df, how=\"left\", on=\"case_id\", suffix=f\"_{i}\")\n        \n    df_base = df_base.pipe(Pipeline.handle_dates)\n    if is_train:\n        df_base = df_base.pipe(Pipeline.filter_cols)\n    df_base = df_base.pipe(Pipeline.fill_missing_values)\n    \n    return df_base\n\ndef to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    \n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    \n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    \n    return df_data, cat_cols\n\n# %% [code] {\"jupyter\":{\"outputs_hidden\":false},\"execution\":{\"iopub.status.busy\":\"2024-05-05T00:46:21.008131Z\",\"iopub.execute_input\":\"2024-05-05T00:46:21.008411Z\",\"iopub.status.idle\":\"2024-05-05T00:46:21.020794Z\",\"shell.execute_reply.started\":\"2024-05-05T00:46:21.008389Z\",\"shell.execute_reply\":\"2024-05-05T00:46:21.019975Z\"}}\nfrom pathlib import Path\nfrom glob import glob\n\nROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\n# %% [code] {\"jupyter\":{\"outputs_hidden\":false},\"execution\":{\"iopub.status.busy\":\"2024-05-05T00:46:21.021879Z\",\"iopub.execute_input\":\"2024-05-05T00:46:21.022207Z\",\"iopub.status.idle\":\"2024-05-05T00:46:21.553731Z\",\"shell.execute_reply.started\":\"2024-05-05T00:46:21.022158Z\",\"shell.execute_reply\":\"2024-05-05T00:46:21.552792Z\"}}\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}\n\n# %% [code] {\"jupyter\":{\"outputs_hidden\":false},\"execution\":{\"iopub.status.busy\":\"2024-05-05T00:46:21.554798Z\",\"iopub.execute_input\":\"2024-05-05T00:46:21.555088Z\",\"iopub.status.idle\":\"2024-05-05T00:46:22.189875Z\",\"shell.execute_reply.started\":\"2024-05-05T00:46:21.555063Z\",\"shell.execute_reply\":\"2024-05-05T00:46:22.189053Z\"}}\ndf_test = feature_eng(**data_store, is_train=False)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:34.759397Z","iopub.execute_input":"2024-10-23T15:28:34.759917Z","iopub.status.idle":"2024-10-23T15:28:36.742202Z","shell.execute_reply.started":"2024-10-23T15:28:34.759870Z","shell.execute_reply":"2024-10-23T15:28:36.740935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"caseid=df_test['case_id']","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:38.938300Z","iopub.execute_input":"2024-10-23T15:28:38.938772Z","iopub.status.idle":"2024-10-23T15:28:38.944142Z","shell.execute_reply.started":"2024-10-23T15:28:38.938730Z","shell.execute_reply":"2024-10-23T15:28:38.942910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# 定义批次大小\nbatch_size = 50000\nnum_batches = (len(df_test) + batch_size - 1) // batch_size  # 计算批次数\n\n# 初始化一个空的列表用于存储预测结果\npredictions = []\n\n# 分批次进行预测\nfor i in range(num_batches):\n    # 提取当前批次的数据\n    batch_df = df_test[i * batch_size: (i + 1) * batch_size]\n    batch_df=deal_df(batch_df[columns_to_select])\n    batch_df = batch_df.drop(constant_cols)\n    batch_df = batch_df.to_pandas()\n    batch_df = pd.get_dummies(batch_df, columns=categorical_cols, drop_first=True)\n    missing_columns = [col for col in columns_to_select_1 if col not in df_test.columns]\n    for col in missing_columns:\n        batch_df[col] = 0\n    batch_df = batch_df[columns_to_select_1]\n    # 转换为 DMatrix 格式\n    dtest = xgb.DMatrix(batch_df)\n    \n    # 进行预测\n    batch_predictions = model.predict(dtest)\n    \n    # 将结果添加到列表\n    predictions.extend(batch_predictions)\n\n# 将预测结果转换为数据框\npredictions_df = pd.DataFrame(predictions, columns=['predicted_values'])\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:39.357850Z","iopub.execute_input":"2024-10-23T15:28:39.358269Z","iopub.status.idle":"2024-10-23T15:28:40.594488Z","shell.execute_reply.started":"2024-10-23T15:28:39.358230Z","shell.execute_reply":"2024-10-23T15:28:40.593230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"subm_df = pd.concat([caseid.to_pandas(), predictions_df ], axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:42.070294Z","iopub.execute_input":"2024-10-23T15:28:42.070721Z","iopub.status.idle":"2024-10-23T15:28:42.077932Z","shell.execute_reply.started":"2024-10-23T15:28:42.070683Z","shell.execute_reply":"2024-10-23T15:28:42.076547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"subm_df.rename(columns={'case_id': 'case_id', 'predicted_values': 'score'}, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:42.372449Z","iopub.execute_input":"2024-10-23T15:28:42.372895Z","iopub.status.idle":"2024-10-23T15:28:42.378843Z","shell.execute_reply.started":"2024-10-23T15:28:42.372853Z","shell.execute_reply":"2024-10-23T15:28:42.377760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"subm_df.reset_index(drop=True, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:42.593195Z","iopub.execute_input":"2024-10-23T15:28:42.593686Z","iopub.status.idle":"2024-10-23T15:28:42.600072Z","shell.execute_reply.started":"2024-10-23T15:28:42.593635Z","shell.execute_reply":"2024-10-23T15:28:42.598570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"subm_df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T15:28:42.854649Z","iopub.execute_input":"2024-10-23T15:28:42.855085Z","iopub.status.idle":"2024-10-23T15:28:42.865366Z","shell.execute_reply.started":"2024-10-23T15:28:42.855042Z","shell.execute_reply":"2024-10-23T15:28:42.864285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}