{"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"}],"dockerImageVersionId":30702,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport gc\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\n\n\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nimport polars.selectors as cs\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split,StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nimport xgboost as xgb\n\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)#cost7s\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-25T08:13:36.950596Z","iopub.execute_input":"2024-04-25T08:13:36.951028Z","iopub.status.idle":"2024-04-25T08:13:40.579374Z","shell.execute_reply.started":"2024-04-25T08:13:36.950996Z","shell.execute_reply":"2024-04-25T08:13:40.578479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataPath = \"/kaggle/input/home-credit-credit-risk-model-stability/\"","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:40.581402Z","iopub.execute_input":"2024-04-25T08:13:40.582029Z","iopub.status.idle":"2024-04-25T08:13:40.586992Z","shell.execute_reply.started":"2024-04-25T08:13:40.581987Z","shell.execute_reply":"2024-04-25T08:13:40.586158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_table_dtypes(df: pl.DataFrame) -> pl.DataFrame:\n    # implement here all desired dtypes for tables\n    # the following is just an example\n    for col in df.columns:\n        # last letter of column name will help you determine the type\n        if col[-1] in (\"P\", \"A\"):\n            df = df.with_columns(pl.col(col).cast(pl.Float64).alias(col))#這邊會只指\"P\",\"A\"的欄位嗎?\n        if col[-1] in (\"D\"):\n            df = df.with_columns(pl.col(col).cast(pl.Date).alias(col))\n\n    return df\n#把浮點數的col存進dataframe中，data也是\n\ndef convert_strings(df: pd.DataFrame) -> pd.DataFrame:\n    for col in df.columns:\n        if df[col].dtype.name in ['object', 'string']:\n            df[col] = df[col].astype(\"string\").astype('category')\n            current_categories = df[col].cat.categories\n            new_categories = current_categories.to_list() + [\"Unknown\"]\n            new_dtype = pd.CategoricalDtype(categories=new_categories, ordered=True)\n            df[col] = df[col].astype(new_dtype)\n    return df\n#cost1s","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:40.588284Z","iopub.execute_input":"2024-04-25T08:13:40.588572Z","iopub.status.idle":"2024-04-25T08:13:40.60192Z","shell.execute_reply.started":"2024-04-25T08:13:40.588548Z","shell.execute_reply":"2024-04-25T08:13:40.600807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Basetable","metadata":{}},{"cell_type":"code","source":"#cost2s\n# train\ntra_base_p = pl.read_csv(dataPath + \"csv_files/train/train_base.csv\")\ntra_base_p = tra_base_p.with_columns(pl.col('date_decision').str.to_date())\n\n# test\ntest_base_p = pl.read_csv(dataPath + \"csv_files/test/test_base.csv\")\ntest_base_p = test_base_p.with_columns(pl.col('date_decision').str.to_date())","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:40.603868Z","iopub.execute_input":"2024-04-25T08:13:40.605083Z","iopub.status.idle":"2024-04-25T08:13:41.371799Z","shell.execute_reply.started":"2024-04-25T08:13:40.605046Z","shell.execute_reply":"2024-04-25T08:13:41.370676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#cost15s\n# train\ntra_sta_p = pl.concat(\n    [\n        pl.read_csv(dataPath + \"csv_files/train/train_static_0_0.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + \"csv_files/train/train_static_0_1.csv\").pipe(set_table_dtypes),\n    ],\n    how=\"vertical_relaxed\",\n)\n#tra_sta_cb_p= pl.read_csv(dataPath + \"csv_files/train/train_static_cb_0.csv\").pipe(set_table_dtypes)\n\n# test\ntest_sta_p = pl.concat(\n    [\n        pl.read_csv(dataPath + \"csv_files/test/test_static_0_0.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + \"csv_files/test/test_static_0_1.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + \"csv_files/test/test_static_0_2.csv\").pipe(set_table_dtypes),\n    ],\n    how=\"vertical_relaxed\",\n)\n#test_static_cb = pl.read_csv(dataPath + \"csv_files/test/test_static_cb_0.csv\").pipe(set_table_dtypes)\n#cost14s","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:41.373708Z","iopub.execute_input":"2024-04-25T08:13:41.374163Z","iopub.status.idle":"2024-04-25T08:13:53.823842Z","shell.execute_reply.started":"2024-04-25T08:13:41.374123Z","shell.execute_reply":"2024-04-25T08:13:53.822369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#cost1s\nselected_sta_p_cols = []\nfor col in tra_sta_p.columns:\n    if col[-1] in (\"A\", \"D\", \"M\", 'P', 'T', \"L\"):\n        selected_sta_p_cols.append(col)\nprint(selected_sta_p_cols)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:53.825378Z","iopub.execute_input":"2024-04-25T08:13:53.8268Z","iopub.status.idle":"2024-04-25T08:13:53.833231Z","shell.execute_reply.started":"2024-04-25T08:13:53.826762Z","shell.execute_reply":"2024-04-25T08:13:53.83212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n# 合併tarin set的base層+0層","metadata":{}},{"cell_type":"code","source":"#cost2s\ndata_p = tra_base_p.join(\n    tra_sta_p.select([\"case_id\"]+selected_sta_p_cols), how=\"left\", on=\"case_id\"\n)\n#cost3s","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:53.835311Z","iopub.execute_input":"2024-04-25T08:13:53.835762Z","iopub.status.idle":"2024-04-25T08:13:54.936485Z","shell.execute_reply.started":"2024-04-25T08:13:53.835703Z","shell.execute_reply":"2024-04-25T08:13:54.93543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#cost2s\ndata_p","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:54.937395Z","iopub.execute_input":"2024-04-25T08:13:54.937714Z","iopub.status.idle":"2024-04-25T08:13:54.97078Z","shell.execute_reply.started":"2024-04-25T08:13:54.937688Z","shell.execute_reply":"2024-04-25T08:13:54.969919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def calculate_date_difference(df):\n    for col in df.columns:\n        if col[-1] == \"D\":\n            df = df.with_columns(\n                (pl.col('date_decision') - pl.col(col)).cast(pl.Int64).alias(col)#計算日期差異，可能以秒計算\n            )\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:54.97181Z","iopub.execute_input":"2024-04-25T08:13:54.972909Z","iopub.status.idle":"2024-04-25T08:13:54.978379Z","shell.execute_reply.started":"2024-04-25T08:13:54.972875Z","shell.execute_reply":"2024-04-25T08:13:54.977366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_p = calculate_date_difference(data_p)\ndata_p","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:54.981487Z","iopub.execute_input":"2024-04-25T08:13:54.981852Z","iopub.status.idle":"2024-04-25T08:13:55.537864Z","shell.execute_reply.started":"2024-04-25T08:13:54.981825Z","shell.execute_reply":"2024-04-25T08:13:55.536762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_submission_p = test_base_p.join(\n    test_sta_p.select([\"case_id\"]+selected_sta_p_cols), how=\"left\", on=\"case_id\"\n)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:55.539169Z","iopub.execute_input":"2024-04-25T08:13:55.539909Z","iopub.status.idle":"2024-04-25T08:13:55.547045Z","shell.execute_reply.started":"2024-04-25T08:13:55.539868Z","shell.execute_reply":"2024-04-25T08:13:55.545701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_submission_p = calculate_date_difference(data_submission_p)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:55.549041Z","iopub.execute_input":"2024-04-25T08:13:55.549573Z","iopub.status.idle":"2024-04-25T08:13:55.562515Z","shell.execute_reply.started":"2024-04-25T08:13:55.549534Z","shell.execute_reply":"2024-04-25T08:13:55.561238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_submission_p","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:55.566589Z","iopub.execute_input":"2024-04-25T08:13:55.566961Z","iopub.status.idle":"2024-04-25T08:13:55.588584Z","shell.execute_reply.started":"2024-04-25T08:13:55.56693Z","shell.execute_reply":"2024-04-25T08:13:55.587198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 交叉驗證","metadata":{}},{"cell_type":"code","source":"#cost27s\ncase_ids = data_p[\"case_id\"].unique().shuffle(seed=1)#cost29s\ncase_ids_train, case_ids_test = train_test_split(case_ids, train_size=0.6, random_state=1)\ncase_ids_valid, case_ids_test = train_test_split(case_ids_test, train_size=0.5, random_state=1)\n\ncols_pred = []\nfor col in data_p.columns:\n    if col[-1].isupper() and col[:-1].islower():\n        cols_pred.append(col)\n\nprint(cols_pred)\n\ndef from_polars_to_pandas(case_ids: pl.DataFrame) -> pl.DataFrame:\n    return (\n        data_p.filter(pl.col(\"case_id\").is_in(case_ids))[[\"case_id\", \"WEEK_NUM\", \"target\"]].to_pandas(),\n        data_p.filter(pl.col(\"case_id\").is_in(case_ids))[cols_pred].to_pandas(),\n        data_p.filter(pl.col(\"case_id\").is_in(case_ids))[\"target\"].to_pandas()\n    )\n\nbase_train, X_train, y_train = from_polars_to_pandas(case_ids_train)\nbase_valid, X_valid, y_valid = from_polars_to_pandas(case_ids_valid)\nbase_test, X_test, y_test = from_polars_to_pandas(case_ids_test)\n\nfor df in [X_train, X_valid, X_test]:\n    df = convert_strings(df)\n\nprint('\\n')\nprint(f\"Train: {X_train.shape}\")\nprint(f\"Valid: {X_valid.shape}\")\nprint(f\"Test: {X_test.shape}\")","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:13:55.590075Z","iopub.execute_input":"2024-04-25T08:13:55.590506Z","iopub.status.idle":"2024-04-25T08:14:12.014078Z","shell.execute_reply.started":"2024-04-25T08:13:55.590467Z","shell.execute_reply":"2024-04-25T08:14:12.013154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# GINI & AUC","metadata":{}},{"cell_type":"code","source":"#cost26s\nfor base, X in [(base_train, X_train), (base_valid, X_valid), (base_test, X_test)]:\n    y_pred = gbm.predict(X, num_iteration=gbm.best_iteration)\n    base[\"score\"] = y_pred\n\nprint(f'The AUC score on the train set is: {roc_auc_score(base_train[\"target\"], base_train[\"score\"])}')\nprint(f'The AUC score on the valid set is: {roc_auc_score(base_valid[\"target\"], base_valid[\"score\"])}')\nprint(f'The AUC score on the test set is: {roc_auc_score(base_test[\"target\"], base_test[\"score\"])}')\n\n\ndef gini_stability(base, w_fallingrate=88.0, w_resstd=-0.5):\n    gini_in_time = base.loc[:, [\"WEEK_NUM\", \"target\", \"score\"]]\\\n        .sort_values(\"WEEK_NUM\")\\\n        .groupby(\"WEEK_NUM\")[[\"target\", \"score\"]]\\\n        .apply(lambda x: 2*roc_auc_score(x[\"target\"], x[\"score\"])-1).tolist()\n\n    x = np.arange(len(gini_in_time))\n    y = gini_in_time\n    a, b = np.polyfit(x, y, 1)\n    y_hat = a*x + b\n    residuals = y - y_hat\n    res_std = np.std(residuals)\n    avg_gini = np.mean(gini_in_time)\n    return avg_gini + w_fallingrate * min(0, a) + w_resstd * res_std\n\nstability_score_train = gini_stability(base_train)\nstability_score_valid = gini_stability(base_valid)\nstability_score_test = gini_stability(base_test)\n\nprint('\\n')\nprint(f'The stability score on the train set is: {stability_score_train}')\nprint(f'The stability score on the valid set is: {stability_score_valid}')\nprint(f'The stability score on the test set is: {stability_score_test}')","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:14:12.015314Z","iopub.execute_input":"2024-04-25T08:14:12.015828Z","iopub.status.idle":"2024-04-25T08:14:12.403454Z","shell.execute_reply.started":"2024-04-25T08:14:12.015798Z","shell.execute_reply":"2024-04-25T08:14:12.402292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# XGBOOST model","metadata":{}},{"cell_type":"code","source":"#cost344s\nimport xgboost as xgb\n\nxgb_model = xgb.XGBClassifier(\n    #device=\"cuda\",\n    objective='binary:logistic',\n    tree_method=\"hist\",\n    enable_categorical=True,\n    eval_metric='auc',\n    #gamma=0.7,\n    #reg_alpha=0.7,\n    max_depth=10,\n    n_estimators=1200,\n    random_state=42,\n)\n\n# Training the model on the training data\nxgb_model.fit(\n    X_train, y_train,\n    eval_set=[(X_valid, y_valid)],\n    early_stopping_rounds=100,\n    verbose=True,\n)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:14:12.404512Z","iopub.status.idle":"2024-04-25T08:14:12.405124Z","shell.execute_reply.started":"2024-04-25T08:14:12.404891Z","shell.execute_reply":"2024-04-25T08:14:12.404909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"X_submission = data_submission_p[cols_pred].to_pandas()\nX_submission = convert_strings(X_submission)\nX_submission_processed = X_submission.copy()\ncategorical_cols = X_train.select_dtypes(include=['category']).columns\n\nfor col in categorical_cols:\n    train_categories = set(X_train[col].cat.categories)\n#    submission_categories = set(X_submission[col].cat.categories)\n#    new_categories = submission_categories - train_categories\n#    X_submission.loc[X_submission[col].isin(new_categories), col] = \"Unknown\"\n    new_dtype = pd.CategoricalDtype(categories=train_categories, ordered=True)\n    X_train[col] = X_train[col].astype(new_dtype)\n    X_submission[col] = X_submission[col].astype(new_dtype)\n\n#for col in cat_features:\n#    X_submission_processed[col] = X_submission_processed[col].cat.add_categories('Missing').fillna('Missing')\n\n#lgb_pred = lgb_model.predict(X_submission)\nxgb_pred = xgb_model.predict(X_submission)\n\n\ny_submission_pred = np.mean([xgb_pred], axis=0)\nsubmission = pd.DataFrame({\n    \"case_id\": data_submission_p[\"case_id\"].to_numpy(),\n    \"score\": y_submission_pred\n}).set_index('case_id')\nsubmission.to_csv(\"./submission.csv\")\nsubmission","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:14:12.406258Z","iopub.status.idle":"2024-04-25T08:14:12.409032Z","shell.execute_reply.started":"2024-04-25T08:14:12.408809Z","shell.execute_reply":"2024-04-25T08:14:12.408828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\n    \"case_id\": data_submission_p[\"case_id\"].to_numpy(),\n    \"score\": y_submission_pred\n}).set_index('case_id')\nsubmission.to_csv(\"./submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-04-25T08:14:12.410136Z","iopub.status.idle":"2024-04-25T08:14:12.410767Z","shell.execute_reply.started":"2024-04-25T08:14:12.410563Z","shell.execute_reply":"2024-04-25T08:14:12.41058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 以上完成</br>\n並完成lgbm的建模與交叉驗證</br>\n是參考這個程式碼：https://www.kaggle.com/code/cwhybe/team9-baseline-v4/notebook#Submission</br>\n-----------------------------------</br>","metadata":{}}]}