{"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":9675124,"sourceType":"datasetVersion","datasetId":5913017},{"sourceId":9694864,"sourceType":"datasetVersion","datasetId":5927607},{"sourceId":142222,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":120486,"modelId":143694}],"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:05:43.769894Z","iopub.execute_input":"2024-10-24T15:05:43.770391Z","iopub.status.idle":"2024-10-24T15:05:43.798816Z","shell.execute_reply.started":"2024-10-24T15:05:43.770347Z","shell.execute_reply":"2024-10-24T15:05:43.796438Z"},"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:05:43.801978Z","iopub.execute_input":"2024-10-24T15:05:43.802479Z","iopub.status.idle":"2024-10-24T15:05:43.811939Z","shell.execute_reply.started":"2024-10-24T15:05:43.802434Z","shell.execute_reply":"2024-10-24T15:05:43.810413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df = pl.read_parquet('/kaggle/input/train-df/train_df.parquet')\n# columns_to_select = df.columns\n# columns_to_select = [col for col in columns_to_select if col != 'target']","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.814203Z","iopub.execute_input":"2024-10-24T15:05:43.814659Z","iopub.status.idle":"2024-10-24T15:05:43.835386Z","shell.execute_reply.started":"2024-10-24T15:05:43.814592Z","shell.execute_reply":"2024-10-24T15:05:43.833851Z"},"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)\n# df=deal_df(df)\n# constant_cols = [col for col in df.columns if df[col].n_unique() <= 1]\n# df = df.drop(constant_cols)\n# df = df.to_pandas()\n# categorical_cols = df.select_dtypes(include=['object']).columns\n# df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.837477Z","iopub.execute_input":"2024-10-24T15:05:43.837908Z","iopub.status.idle":"2024-10-24T15:05:43.862408Z","shell.execute_reply.started":"2024-10-24T15:05:43.837846Z","shell.execute_reply":"2024-10-24T15:05:43.860304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# columns_to_select_1 = df.drop(columns=['target','case_id']).columns","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.867634Z","iopub.execute_input":"2024-10-24T15:05:43.868393Z","iopub.status.idle":"2024-10-24T15:05:43.884253Z","shell.execute_reply.started":"2024-10-24T15:05:43.868338Z","shell.execute_reply":"2024-10-24T15:05:43.882112Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.886684Z","iopub.execute_input":"2024-10-24T15:05:43.887344Z","iopub.status.idle":"2024-10-24T15:05:43.907593Z","shell.execute_reply.started":"2024-10-24T15:05:43.887295Z","shell.execute_reply":"2024-10-24T15:05:43.905980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# num_rows_to_read = len(df) // 15","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.909813Z","iopub.execute_input":"2024-10-24T15:05:43.910396Z","iopub.status.idle":"2024-10-24T15:05:43.932218Z","shell.execute_reply.started":"2024-10-24T15:05:43.910348Z","shell.execute_reply":"2024-10-24T15:05:43.929753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model= None\n# gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.937513Z","iopub.execute_input":"2024-10-24T15:05:43.939321Z","iopub.status.idle":"2024-10-24T15:05:43.956002Z","shell.execute_reply.started":"2024-10-24T15:05:43.939250Z","shell.execute_reply":"2024-10-24T15:05:43.952656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df.shape","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.959247Z","iopub.execute_input":"2024-10-24T15:05:43.960190Z","iopub.status.idle":"2024-10-24T15:05:43.972028Z","shell.execute_reply.started":"2024-10-24T15:05:43.960106Z","shell.execute_reply":"2024-10-24T15:05:43.969562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for i in range(0, len(df), num_rows_to_read):\n#         X_batch = df.drop(columns=['target','case_id']).iloc[i:i + num_rows_to_read]\n#         y_batch = df['target'].iloc[i:i + num_rows_to_read]\n#         dtrain_batch = xgb.DMatrix(X_batch, label=y_batch)\n\n#         # 初始化或增量训练模型\n#         if model is None:\n#             model = xgb.train({\n#                 'objective': 'binary:logistic',\n#                 'eval_metric': 'logloss',\n#                 'eta': 0.1,\n#                 'max_depth': 3,\n#                 'seed': 42\n#             }, dtrain_batch, num_boost_round=50)\n#         else:\n#             model = xgb.train({\n#                 'objective': 'binary:logistic',\n#                 'eval_metric': 'logloss',\n#                 'eta': 0.1,\n#                 'max_depth': 3,\n#                 'seed': 42\n#             }, dtrain_batch, num_boost_round=50, xgb_model=model)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.974096Z","iopub.execute_input":"2024-10-24T15:05:43.976998Z","iopub.status.idle":"2024-10-24T15:05:43.994584Z","shell.execute_reply.started":"2024-10-24T15:05:43.976891Z","shell.execute_reply":"2024-10-24T15:05:43.992107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# X_batch.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:43.997045Z","iopub.execute_input":"2024-10-24T15:05:43.997757Z","iopub.status.idle":"2024-10-24T15:05:44.013349Z","shell.execute_reply.started":"2024-10-24T15:05:43.997680Z","shell.execute_reply":"2024-10-24T15:05:44.011253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# del X_batch,y_batch,dtrain_batch,df\n# gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:44.015899Z","iopub.execute_input":"2024-10-24T15:05:44.016408Z","iopub.status.idle":"2024-10-24T15:05:44.029116Z","shell.execute_reply.started":"2024-10-24T15:05:44.016353Z","shell.execute_reply":"2024-10-24T15:05:44.027342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.save_model('xgboost_model.json') ","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:44.031293Z","iopub.execute_input":"2024-10-24T15:05:44.031844Z","iopub.status.idle":"2024-10-24T15:05:44.051800Z","shell.execute_reply.started":"2024-10-24T15:05:44.031770Z","shell.execute_reply":"2024-10-24T15:05:44.049960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import polars as pl\n\n# 读取Parquet文件或创建数据框\ndf = pl.read_parquet('/kaggle/input/train-df/train_df.parquet')  # 如果是已有的文件\n\n# 随机打乱数据框\ndf_shuffled = df.sample(n=df.height, shuffle=True)\n\n# 保存为新的Parquet文件\ndf_shuffled.write_parquet('shuffled_output_file.parquet')\ndel df_shuffled,df\ngc.collect()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:44.060247Z","iopub.execute_input":"2024-10-24T15:05:44.061083Z","iopub.status.idle":"2024-10-24T15:05:56.795271Z","shell.execute_reply.started":"2024-10-24T15:05:44.061022Z","shell.execute_reply":"2024-10-24T15:05:56.793079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import polars as pl\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nimport numpy as np\n\n# 文件路径和批次大小\ndata_path = 'shuffled_output_file.parquet'  # Parquet文件路径\nbatch_size = 502219 #763330 # 305332-0.847 #152666-0.8412  # 每次读取的数据行数\ntotal_rows=1526659\nnum_boost_round = 200  # 每次训练的轮数\ntotal_batches = (total_rows + batch_size - 1) // batch_size  # 计算总批次数\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.796580Z","iopub.status.idle":"2024-10-24T15:05:56.797338Z","shell.execute_reply.started":"2024-10-24T15:05:56.796906Z","shell.execute_reply":"2024-10-24T15:05:56.796934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"columns_to_select_1 = pd.read_csv('/kaggle/input/cols-name/cols.csv')\ncolumns_to_select_1=columns_to_select_1['0'].values.tolist()\ncolumns_to_select = pd.read_csv('/kaggle/input/cols-name/cols2.csv')\ncolumns_to_select=columns_to_select['0'].values.tolist()\nconstant_cols = pd.read_csv('/kaggle/input/cols-name/constant_cols.csv')\nconstant_cols=constant_cols['0'].values.tolist()\ncategorical_cols = pd.read_csv('/kaggle/input/cols-name/categorical_cols.csv')\ncategorical_cols=categorical_cols['0'].values.tolist()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.799410Z","iopub.status.idle":"2024-10-24T15:05:56.800059Z","shell.execute_reply.started":"2024-10-24T15:05:56.799782Z","shell.execute_reply":"2024-10-24T15:05:56.799820Z"},"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-24T15:05:56.803885Z","iopub.status.idle":"2024-10-24T15:05:56.804614Z","shell.execute_reply.started":"2024-10-24T15:05:56.804267Z","shell.execute_reply":"2024-10-24T15:05:56.804304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_in_batches(file_path, batch_size):\n    \"\"\"每次读取batch_size行数据.\"\"\"\n    parquet_file = pl.read_parquet(file_path)\n    total_rows = parquet_file.height  # 获取总行数\n    print(f\"Total rows in the file: {total_rows}\")  # 添加调试信息\n    \n    for start in range(0, total_rows, batch_size):\n        yield parquet_file.slice(start, batch_size)","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.806738Z","iopub.status.idle":"2024-10-24T15:05:56.807433Z","shell.execute_reply.started":"2024-10-24T15:05:56.807072Z","shell.execute_reply":"2024-10-24T15:05:56.807105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 初始化模型\nfinal_model = None\n\n# 设置XGBoost参数\nparams = {\n    'objective': 'binary:logistic',\n    'eval_metric': 'auc',\n    'learning_rate': 0.1,\n    'max_depth': 6\n}\nnum_boost_round = 300  # 每次训练的轮数\n# 读取数据分批训练，最后一批用于验证","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.809471Z","iopub.status.idle":"2024-10-24T15:05:56.810194Z","shell.execute_reply.started":"2024-10-24T15:05:56.809829Z","shell.execute_reply":"2024-10-24T15:05:56.809863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nbatch_generator = read_in_batches(data_path, batch_size)\nfinal_model = None\n# 获取前 n-1 批次用于训练，最后一批用于验证\n\nfor i, batch_df in enumerate(batch_generator):\n    # 如果是最后一个批次，则用作验证集\n    if i == (total_batches - 1):\n        # 将当前批次作为验证集\n        target=batch_df['target']\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 batch_df.columns]\n        for col in missing_columns:\n            batch_df[col] = 0\n        batch_df = batch_df[columns_to_select_1]\n        val_df = batch_df\n        #X_val = val_df.drop('target').to_numpy()  # 用to_numpy()获取数组\n        #y_val = val_df['target'].to_numpy()  # 用to_numpy()获取数组\n        dval = xgb.DMatrix(batch_df, label=target)\n        print(f\"Using last batch as validation set. Batch {i + 1}\")\n        break\n\n    # 准备当前批次数据\n    target=batch_df['target']\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 batch_df.columns]\n    for col in missing_columns:\n        batch_df[col] = 0\n    batch_df = batch_df[columns_to_select_1]\n    #X_train_batch = batch_df.drop('target').to_numpy()  # 用to_numpy()获取数组\n    #y_train_batch = batch_df['target'].to_numpy()  # 用to_numpy()获取数组\n    dtrain = xgb.DMatrix(batch_df, label=target)\n\n    # 训练模型\n    if final_model:\n        final_model = xgb.train(params, dtrain, num_boost_round=num_boost_round, xgb_model=final_model)\n    else:\n        final_model = xgb.train(params, dtrain, num_boost_round=num_boost_round)\n\n    # 删除不必要的数据释放内存\n    del batch_df, dtrain #X_train_batch, y_train_batch\n    gc.collect()\n\n# 进行验证\ny_pred_val = final_model.predict(dval)\n\n# 计算AUC\nauc_val = roc_auc_score(target, y_pred_val)\nprint(f\"Validation AUC: {auc_val}\")","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.815548Z","iopub.status.idle":"2024-10-24T15:05:56.816385Z","shell.execute_reply.started":"2024-10-24T15:05:56.815992Z","shell.execute_reply":"2024-10-24T15:05:56.816027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_model.save_model('xgboost_model.json') ","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.818379Z","iopub.status.idle":"2024-10-24T15:05:56.818852Z","shell.execute_reply.started":"2024-10-24T15:05:56.818630Z","shell.execute_reply":"2024-10-24T15:05:56.818652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # 读取完整数据集，随机抽取20%作为验证集\n# full_df = pl.read_parquet(data_path)\n# train_df, val_df = train_test_split(full_df.to_pandas(), test_size=0.2, random_state=42)\n\n# # 将验证集转换为DMatrix\n# X_val = val_df.drop('target', axis=1).values\n# y_val = val_df['target'].values\n# dval = xgb.DMatrix(X_val, label=y_val)\n\n# # 读取训练集的分批次生成器函数\n# def read_in_batches(df, batch_size):\n#     total_rows = df.shape[0]\n#     for start in range(0, total_rows, batch_size):\n#         yield df[start:start + batch_size]\n\n# # 分批训练模型\n# dtrain_batches = read_in_batches(train_df, batch_size)\n\n# # 设置XGBoost参数\n# params = {\n#     'objective': 'binary:logistic',  # 二分类任务\n#     'eval_metric': 'auc',  # 使用AUC作为评价指标\n#     'learning_rate': 0.1,\n#     'max_depth': 6\n# }\n\n# # 初始化模型\n# final_model = None\n\n# # 分批次读取数据并训练模型\n# for batch_df in dtrain_batches:\n#     X_train_batch = batch_df.drop('target', axis=1).values\n#     y_train_batch = batch_df['target'].values\n    \n#     dtrain = xgb.DMatrix(X_train_batch, label=y_train_batch)\n    \n#     # 如果模型已经存在，则继续训练\n#     if final_model:\n#         final_model = xgb.train(params, dtrain, num_boost_round=num_boost_round, xgb_model=final_model)\n#     else:\n#         final_model = xgb.train(params, dtrain, num_boost_round=num_boost_round)\n\n# # 使用固定的验证集进行预测\n# y_pred_val = final_model.predict(dval)\n\n# # 计算AUC\n# auc_val = roc_auc_score(y_val, y_pred_val)\n# print(f\"Validation AUC: {auc_val}\")","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.820430Z","iopub.status.idle":"2024-10-24T15:05:56.821272Z","shell.execute_reply.started":"2024-10-24T15:05:56.820889Z","shell.execute_reply":"2024-10-24T15:05:56.820941Z"},"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\"}}\n# class Pipeline:\n#     @staticmethod\n#     def set_table_dtypes(df):\n#         for col in df.columns:\n#             if col in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"]:\n#                 df = df.with_columns(pl.col(col).cast(pl.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\"}}\n# class 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\"}}\n# def 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\n# def 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\n# def 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\n# def 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\"}}\n# from pathlib import Path\n# from glob import glob\n\n# ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n# TRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\n# TEST_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\"}}\n# 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# }\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\"}}\n# df_test = feature_eng(**data_store, is_train=False)\n# print(\"test data shape:\\t\", df_test.shape)\n# del data_store\n# gc.collect()\n\n# # %% [code] {\"jupyter\":{\"outputs_hidden\":false},\"execution\":{\"iopub.status.busy\":\"2024-05-05T00:46:22.192593Z\",\"iopub.execute_input\":\"2024-05-05T00:46:22.192868Z\",\"iopub.status.idle\":\"2024-05-05T00:46:22.744567Z\",\"shell.execute_reply.started\":\"2024-05-05T00:46:22.192845Z\",\"shell.execute_reply\":\"2024-05-05T00:46:22.743676Z\"}}\n# # df_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n# #df_test = df_test.select(['case_id', 'WEEK_NUM'] + cat_features)\n# # print(\"train data shape:\\t\", df_train.shape)\n# #print(\"test data shape:\\t\", df_test.shape)\n\n# #df_test, cat_cols = to_pandas(df_test)\n# # df_test = reduce_mem_usage(df_test)\n\n# #gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.824499Z","iopub.status.idle":"2024-10-24T15:05:56.825086Z","shell.execute_reply.started":"2024-10-24T15:05:56.824820Z","shell.execute_reply":"2024-10-24T15:05:56.824848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# caseid=df_test['case_id']\n# df_test[columns_to_select].head()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.828361Z","iopub.status.idle":"2024-10-24T15:05:56.828843Z","shell.execute_reply.started":"2024-10-24T15:05:56.828609Z","shell.execute_reply":"2024-10-24T15:05:56.828633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_test=deal_df(df_test[columns_to_select])","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.831190Z","iopub.status.idle":"2024-10-24T15:05:56.831912Z","shell.execute_reply.started":"2024-10-24T15:05:56.831553Z","shell.execute_reply":"2024-10-24T15:05:56.831588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_test = df_test.drop(constant_cols)","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.833736Z","iopub.status.idle":"2024-10-24T15:05:56.834592Z","shell.execute_reply.started":"2024-10-24T15:05:56.834215Z","shell.execute_reply":"2024-10-24T15:05:56.834251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_test = df_test.to_pandas()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.839512Z","iopub.status.idle":"2024-10-24T15:05:56.841695Z","shell.execute_reply.started":"2024-10-24T15:05:56.840376Z","shell.execute_reply":"2024-10-24T15:05:56.840418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_test = pd.get_dummies(df_test, columns=categorical_cols, drop_first=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.845705Z","iopub.status.idle":"2024-10-24T15:05:56.846451Z","shell.execute_reply.started":"2024-10-24T15:05:56.846089Z","shell.execute_reply":"2024-10-24T15:05:56.846144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# missing_columns = [col for col in columns_to_select_1 if col not in df_test.columns]","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.848272Z","iopub.status.idle":"2024-10-24T15:05:56.848974Z","shell.execute_reply.started":"2024-10-24T15:05:56.848617Z","shell.execute_reply":"2024-10-24T15:05:56.848649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for col in missing_columns:\n#     df_test[col] = 0\n# df_test = df_test[columns_to_select_1]","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.851757Z","iopub.status.idle":"2024-10-24T15:05:56.852690Z","shell.execute_reply.started":"2024-10-24T15:05:56.852427Z","shell.execute_reply":"2024-10-24T15:05:56.852456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_test.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.855816Z","iopub.status.idle":"2024-10-24T15:05:56.856360Z","shell.execute_reply.started":"2024-10-24T15:05:56.856089Z","shell.execute_reply":"2024-10-24T15:05:56.856115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# # 定义批次大小\n# batch_size = 5\n# num_batches = (len(df_test) + batch_size - 1) // batch_size  # 计算批次数\n\n# # 初始化一个空的列表用于存储预测结果\n# predictions = []\n\n# # 分批次进行预测\n# for i in range(num_batches):\n#     # 提取当前批次的数据\n#     batch_df = df_test[i * batch_size: (i + 1) * batch_size]\n    \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# # 将预测结果转换为数据框\n# predictions_df = pd.DataFrame(predictions, columns=['predicted_values'])\n","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.859212Z","iopub.status.idle":"2024-10-24T15:05:56.859911Z","shell.execute_reply.started":"2024-10-24T15:05:56.859553Z","shell.execute_reply":"2024-10-24T15:05:56.859587Z"},"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-24T15:05:56.861410Z","iopub.status.idle":"2024-10-24T15:05:56.862044Z","shell.execute_reply.started":"2024-10-24T15:05:56.861723Z","shell.execute_reply":"2024-10-24T15:05:56.861765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# subm_df.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-10-24T15:05:56.864097Z","iopub.status.idle":"2024-10-24T15:05:56.864769Z","shell.execute_reply.started":"2024-10-24T15:05:56.864445Z","shell.execute_reply":"2024-10-24T15:05:56.864478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}