{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7602123,"sourceType":"competition"}],"dockerImageVersionId":30635,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Example Notebook\n\nWelcome to the example notebook for the Home Credit Kaggle competition. The goal of this competition is to determine how likely a customer is going to default on an issued loan. The main difference between the [first](https://www.kaggle.com/c/home-credit-default-risk) and this competition is that now your submission will be scored with a custom metric that will take into account how well the model performs in future. A decline in performance will be penalized. The goal is to create a model that is stable and performs well in the future.\n\nIn this notebook you will see how to:\n* Load the data\n* Join tables with Polars - a DataFrame library implemented in Rust language, designed to be blazingy fast and memory efficient.  \n* Create simple aggregation features\n* Train a LightGBM model\n* Create a submission table\n\n## Load the data","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"import polars as pl ## 0.20.3\nimport numpy as np ## 1.24.3\nimport pandas as pd ## 2.0.3\nimport lightgbm as lgb ## 3.3.2\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score \n## sklearn ## 1.2.2\n\ndataPath = \"/kaggle/input/home-credit-credit-risk-model-stability/\"","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:13:50.714068Z","iopub.execute_input":"2024-02-20T11:13:50.714633Z","iopub.status.idle":"2024-02-20T11:13:56.169042Z","shell.execute_reply.started":"2024-02-20T11:13:50.714602Z","shell.execute_reply":"2024-02-20T11:13:56.168166Z"},"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))\n\n    return df\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","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:13:56.170914Z","iopub.execute_input":"2024-02-20T11:13:56.171691Z","iopub.status.idle":"2024-02-20T11:13:56.178996Z","shell.execute_reply.started":"2024-02-20T11:13:56.171662Z","shell.execute_reply":"2024-02-20T11:13:56.177999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_basetable = pl.read_csv(dataPath + \"csv_files/train/train_base.csv\")\ntrain_static = 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)\ntrain_static_cb = pl.read_csv(dataPath + \"csv_files/train/train_static_cb_0.csv\").pipe(set_table_dtypes)\n# train_person_1 = pl.read_csv(dataPath + \"csv_files/train/train_person_1.csv\").pipe(set_table_dtypes) \n# train_credit_bureau_b_2 = pl.read_csv(dataPath + \"csv_files/train/train_credit_bureau_b_2.csv\").pipe(set_table_dtypes) \ntrain_applprev = pl.concat(\n    [\n        pl.read_csv(dataPath + \"csv_files/train/train_applprev_1_0.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + 'csv_files/train/train_applprev_1_1.csv').pipe(set_table_dtypes),\n    ],\n    how='vertical_relaxed',\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:13:56.180123Z","iopub.execute_input":"2024-02-20T11:13:56.180417Z","iopub.status.idle":"2024-02-20T11:14:17.025365Z","shell.execute_reply.started":"2024-02-20T11:13:56.180392Z","shell.execute_reply":"2024-02-20T11:14:17.024556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_applprev = train_applprev[['case_id',\n                                 'maxdpdtolerance_577P',\n                                 'employedfrom_700D',\n                                 'pmtnum_8L',\n                                 'creationdate_885D',\n                                 'credamount_590A',\n                                 'mainoccupationinc_437A',\n                                 'firstnonzeroinstldate_307D',\n                                 'dtlastpmtallstes_3545839D',\n                                 'annuity_853A',\n                                 'familystate_726L',\n                                 'approvaldate_319D',\n                                 'district_544M',\n                                 'dateactivated_425D',\n                                 'education_1138M']]","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:17.027583Z","iopub.execute_input":"2024-02-20T11:14:17.027901Z","iopub.status.idle":"2024-02-20T11:14:17.139298Z","shell.execute_reply.started":"2024-02-20T11:14:17.027874Z","shell.execute_reply":"2024-02-20T11:14:17.138155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 결측치 많은 column 제거\n# train_applprev = train_applprev.drop('outstandingdebt_522A', 'revolvingaccount_394A',\n#                                      'isdebitcard_527L', 'credacc_actualbalance_314A', 'credacc_maxhisbal_375A',\n#                                      'credacc_minhisbal_90A', 'credacc_status_367L', 'credacc_transactions_402L')\n","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:17.140540Z","iopub.execute_input":"2024-02-20T11:14:17.140853Z","iopub.status.idle":"2024-02-20T11:14:17.151446Z","shell.execute_reply.started":"2024-02-20T11:14:17.140828Z","shell.execute_reply":"2024-02-20T11:14:17.150416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_basetable = pl.read_csv(dataPath + \"csv_files/test/test_base.csv\")\ntest_static = 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\ntest_applprev = pl.concat(\n    [\n        pl.read_csv(dataPath + \"csv_files/test/test_applprev_1_0.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + 'csv_files/test/test_applprev_1_1.csv').pipe(set_table_dtypes),\n        pl.read_csv(dataPath + 'csv_files/test/test_applprev_1_2.csv').pipe(set_table_dtypes),\n    ],\n    how='vertical_relaxed',\n)\ntest_static_cb = pl.read_csv(dataPath + \"csv_files/test/test_static_cb_0.csv\").pipe(set_table_dtypes)\n# test_person_1 = pl.read_csv(dataPath + \"csv_files/test/test_person_1.csv\").pipe(set_table_dtypes) \n# test_credit_bureau_b_2 = pl.read_csv(dataPath + \"csv_files/test/test_credit_bureau_b_2.csv\").pipe(set_table_dtypes) \n","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:17.152543Z","iopub.execute_input":"2024-02-20T11:14:17.152802Z","iopub.status.idle":"2024-02-20T11:14:17.243399Z","shell.execute_reply.started":"2024-02-20T11:14:17.152781Z","shell.execute_reply":"2024-02-20T11:14:17.242542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_applprev = test_applprev[['case_id',\n                               'maxdpdtolerance_577P',\n                               'employedfrom_700D',\n                               'pmtnum_8L',\n                               'creationdate_885D',\n                               'credamount_590A',\n                               'mainoccupationinc_437A',\n                               'firstnonzeroinstldate_307D',\n                               'dtlastpmtallstes_3545839D',\n                               'annuity_853A',\n                               'familystate_726L',\n                               'approvaldate_319D',\n                               'district_544M',\n                               'dateactivated_425D',\n                               'education_1138M']]","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:17.244446Z","iopub.execute_input":"2024-02-20T11:14:17.244738Z","iopub.status.idle":"2024-02-20T11:14:17.250101Z","shell.execute_reply.started":"2024-02-20T11:14:17.244707Z","shell.execute_reply":"2024-02-20T11:14:17.249118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# test_applprev = test_applprev.drop('outstandingdebt_522A', 'revolvingaccount_394A',\n#                                     'isdebitcard_527L', 'credacc_actualbalance_314A', 'credacc_maxhisbal_375A',\n#                                     'credacc_minhisbal_90A', 'credacc_status_367L', 'credacc_transactions_402L')","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:17.251334Z","iopub.execute_input":"2024-02-20T11:14:17.251607Z","iopub.status.idle":"2024-02-20T11:14:17.263601Z","shell.execute_reply.started":"2024-02-20T11:14:17.251573Z","shell.execute_reply":"2024-02-20T11:14:17.262618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## Feature engineering\n\n# We will process in this examples only A-type and M-type columns, so we need to select them.\nselected_static_cols = []\nfor col in train_static.columns:\n    if col[-1] in (\"A\", \"M\"):\n        selected_static_cols.append(col)\nprint(selected_static_cols)\n\nselected_static_cb_cols = []\nfor col in train_static_cb.columns:\n    if col[-1] in (\"A\", \"M\"):\n        selected_static_cb_cols.append(col)\nprint(selected_static_cb_cols)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:17.264791Z","iopub.execute_input":"2024-02-20T11:14:17.265617Z","iopub.status.idle":"2024-02-20T11:14:17.274430Z","shell.execute_reply.started":"2024-02-20T11:14:17.265584Z","shell.execute_reply":"2024-02-20T11:14:17.273504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Join all tables together.\ndata = train_basetable.join(\n    train_static.select([\"case_id\"]+selected_static_cols), how=\"left\", on=\"case_id\"\n).join(\n    train_static_cb.select([\"case_id\"]+selected_static_cb_cols), how=\"left\", on=\"case_id\"\n).join(\n    train_applprev, how=\"left\", on=\"case_id\"\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:17.277893Z","iopub.execute_input":"2024-02-20T11:14:17.278156Z","iopub.status.idle":"2024-02-20T11:14:22.316006Z","shell.execute_reply.started":"2024-02-20T11:14:17.278133Z","shell.execute_reply":"2024-02-20T11:14:22.314983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data = data[['case_id', 'MONTH', 'WEEK_NUM',\n# 'date_decision', 'num_group1', 'target', 'price_1097A',\n#  'amtinstpaidbefduel24m_4187115A', 'maxdpdtolerance_577P',\n#  'totalsettled_863A', 'maxannuity_159A', 'pmtssum_45A', 'employedfrom_700D',\n#  'annuity_780A', 'pmtnum_8L', 'inittransactionamount_650A', 'pmtaverage_3A',\n#  'lastrejectreason_759M', 'pmtaverage_4527227A', 'creationdate_885D',\n#  'maxinstallast24m_3658928A', 'lastrejectcredamount_222A', 'credamount_770A',\n#  'disbursedcredamount_1113A', 'pmtaverage_4955615A', 'avginstallast24m_3658937A',\n#  'dtlastpmtallstes_3545839D', 'firstnonzeroinstldate_307D', 'currdebt_22A',\n#  'mainoccupationinc_437A', 'education_1103M', 'lastapprcredamount_781A',\n#  'annuity_853A', 'maxannuity_4075009A', 'familystate_726L', 'maininc_215A',\n#  'sumoutstandtotal_3546847A', 'credamount_590A', 'downpmt_116A', 'totaldebt_9A',\n#  'lastrejectcommoditycat_161M', 'avglnamtstart24m_4525187A', 'approvaldate_319D',\n#  'description_5085714M', 'dateactivated_425D', 'maritalst_385M',\n#  'maxlnamtstart6m_4525199A', 'lastapprcommoditycat_1041M', 'education_1138M',\n#  'totinstallast1m_4525188A', 'dtlastpmt_581D', 'maxoutstandbalancel12m_4187113A',\n#  'maxpmtlast3m_4525190A', 'actualdpd_943P', 'avgpmtlast12m_4525200A',\n#  'district_544M', 'sumoutstandtotalest_4493215A', 'avgoutstandbalancel6m_4187114A',\n#  'maxdebt4_972A', 'credacc_actualbalance_314A', 'credacc_credlmt_575A',\n#  'outstandingdebt_522A', 'status_219L', 'currdebtcredtyperange_828A',\n#  'rejectreason_755M', 'cancelreason_3545846M', 'previouscontdistrict_112M',\n#  'maritalst_893M', 'currdebt_94A', 'credacc_minhisbal_90A', 'postype_4733339M',\n#  'isbidproduct_390L', 'credacc_maxhisbal_375A', 'childnum_21L',\n#  'annuitynextmonth_57A', 'revolvingaccount_394A', 'downpmt_134A',\n#  'lastrejectreasonclient_4145040M', 'rejectreasonclient_4145042M',\n#  'credtype_587L', 'inittransactioncode_279L', 'education_88M', 'credacc_status_367L']]\n","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:22.317141Z","iopub.execute_input":"2024-02-20T11:14:22.317437Z","iopub.status.idle":"2024-02-20T11:14:22.322933Z","shell.execute_reply.started":"2024-02-20T11:14:22.317413Z","shell.execute_reply":"2024-02-20T11:14:22.322010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = data.unique(subset='case_id', keep='first') # case_id 중복되므로 첫 값만 넣음","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:22.324333Z","iopub.execute_input":"2024-02-20T11:14:22.324705Z","iopub.status.idle":"2024-02-20T11:14:25.033312Z","shell.execute_reply.started":"2024-02-20T11:14:22.324678Z","shell.execute_reply":"2024-02-20T11:14:25.032496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_submission = test_basetable.join(\n    test_static.select([\"case_id\"]+selected_static_cols), how=\"left\", on=\"case_id\"\n).join(\n    test_static_cb.select([\"case_id\"]+selected_static_cb_cols), how=\"left\", on=\"case_id\"\n).join(\n    test_applprev, how=\"left\", on=\"case_id\"\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:25.034770Z","iopub.execute_input":"2024-02-20T11:14:25.035119Z","iopub.status.idle":"2024-02-20T11:14:25.044026Z","shell.execute_reply.started":"2024-02-20T11:14:25.035085Z","shell.execute_reply":"2024-02-20T11:14:25.043331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data_submission = data_submission[['case_id', 'MONTH', 'WEEK_NUM',\n# 'date_decision', 'num_group1', 'price_1097A', 'amtinstpaidbefduel24m_4187115A',\n#  'maxdpdtolerance_577P', 'totalsettled_863A', 'maxannuity_159A', 'pmtssum_45A',\n#  'employedfrom_700D', 'annuity_780A', 'pmtnum_8L', 'inittransactionamount_650A',\n#  'pmtaverage_3A', 'lastrejectreason_759M', 'pmtaverage_4527227A',\n#  'creationdate_885D', 'maxinstallast24m_3658928A', 'lastrejectcredamount_222A',\n#  'credamount_770A', 'disbursedcredamount_1113A', 'pmtaverage_4955615A',\n#  'avginstallast24m_3658937A', 'dtlastpmtallstes_3545839D', 'firstnonzeroinstldate_307D',\n#  'currdebt_22A', 'mainoccupationinc_437A', 'education_1103M',\n#  'lastapprcredamount_781A', 'annuity_853A', 'maxannuity_4075009A',\n#  'familystate_726L', 'maininc_215A', 'sumoutstandtotal_3546847A',\n#  'credamount_590A', 'downpmt_116A', 'totaldebt_9A', 'lastrejectcommoditycat_161M',\n#  'avglnamtstart24m_4525187A', 'approvaldate_319D', 'description_5085714M',\n#  'dateactivated_425D', 'maritalst_385M', 'maxlnamtstart6m_4525199A',\n#  'lastapprcommoditycat_1041M', 'education_1138M', 'totinstallast1m_4525188A',\n#  'dtlastpmt_581D', 'maxoutstandbalancel12m_4187113A', 'maxpmtlast3m_4525190A',\n#  'actualdpd_943P', 'avgpmtlast12m_4525200A', 'district_544M',\n#  'sumoutstandtotalest_4493215A', 'avgoutstandbalancel6m_4187114A',\n#  'maxdebt4_972A', 'credacc_actualbalance_314A', 'credacc_credlmt_575A',\n#  'outstandingdebt_522A', 'status_219L', 'currdebtcredtyperange_828A',\n#  'rejectreason_755M', 'cancelreason_3545846M', 'previouscontdistrict_112M',\n#  'maritalst_893M', 'currdebt_94A', 'credacc_minhisbal_90A',\n#  'postype_4733339M', 'isbidproduct_390L', 'credacc_maxhisbal_375A',\n#  'childnum_21L', 'annuitynextmonth_57A', 'revolvingaccount_394A',\n#  'downpmt_134A', 'lastrejectreasonclient_4145040M',\n#  'rejectreasonclient_4145042M', 'credtype_587L', 'inittransactioncode_279L',\n#  'education_88M', 'credacc_status_367L']]","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:25.045419Z","iopub.execute_input":"2024-02-20T11:14:25.045756Z","iopub.status.idle":"2024-02-20T11:14:25.056453Z","shell.execute_reply.started":"2024-02-20T11:14:25.045724Z","shell.execute_reply":"2024-02-20T11:14:25.055666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_submission = data_submission.unique(subset='case_id', keep='first') # case_id 중복되므로 첫 값만 넣음","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:25.057539Z","iopub.execute_input":"2024-02-20T11:14:25.057829Z","iopub.status.idle":"2024-02-20T11:14:25.069721Z","shell.execute_reply.started":"2024-02-20T11:14:25.057806Z","shell.execute_reply":"2024-02-20T11:14:25.068951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"case_ids = data[\"case_id\"].unique().shuffle(seed=1)\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)\ncols_pred = []\nfor col in data.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.filter(pl.col(\"case_id\").is_in(case_ids))[[\"case_id\", \"WEEK_NUM\", \"target\"]].to_pandas(),\n        data.filter(pl.col(\"case_id\").is_in(case_ids))[cols_pred].to_pandas(),\n        data.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)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:25.071014Z","iopub.execute_input":"2024-02-20T11:14:25.071830Z","iopub.status.idle":"2024-02-20T11:14:36.989617Z","shell.execute_reply.started":"2024-02-20T11:14:25.071804Z","shell.execute_reply":"2024-02-20T11:14:36.988614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Train: {X_train.shape}\")\nprint(f\"Valid: {X_valid.shape}\")\nprint(f\"Test: {X_test.shape}\")","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:36.990895Z","iopub.execute_input":"2024-02-20T11:14:36.991261Z","iopub.status.idle":"2024-02-20T11:14:36.997308Z","shell.execute_reply.started":"2024-02-20T11:14:36.991228Z","shell.execute_reply":"2024-02-20T11:14:36.996268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## Training LightGBM\n\nlgb_train = lgb.Dataset(X_train, label=y_train)\nlgb_valid = lgb.Dataset(X_valid, label=y_valid, reference=lgb_train)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 3,\n    \"num_leaves\": 31,\n    \"learning_rate\": 0.05,\n    \"feature_fraction\": 0.9,\n    \"bagging_fraction\": 0.8,\n    \"bagging_freq\": 5,\n    \"n_estimators\": 1000,\n    \"verbose\": -1,\n}\n\ngbm = lgb.train(\n    params,\n    lgb_train,\n    valid_sets=lgb_valid,\n    callbacks=[lgb.log_evaluation(50), lgb.early_stopping(10)]\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:14:36.998804Z","iopub.execute_input":"2024-02-20T11:14:36.999142Z","iopub.status.idle":"2024-02-20T11:16:19.343957Z","shell.execute_reply.started":"2024-02-20T11:14:36.999111Z","shell.execute_reply":"2024-02-20T11:16:19.343258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for 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\"])}')","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:19.344878Z","iopub.execute_input":"2024-02-20T11:16:19.345661Z","iopub.status.idle":"2024-02-20T11:16:45.164862Z","shell.execute_reply.started":"2024-02-20T11:16:19.345633Z","shell.execute_reply":"2024-02-20T11:16:45.163880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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(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-02-20T11:16:45.166009Z","iopub.execute_input":"2024-02-20T11:16:45.166310Z","iopub.status.idle":"2024-02-20T11:16:46.186612Z","shell.execute_reply.started":"2024-02-20T11:16:45.166284Z","shell.execute_reply":"2024-02-20T11:16:46.185703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # 특성 중요도 가져오기\n# importances = gbm.feature_importance()\n\n# # 중요도를 데이터프레임으로 변환\n# feature_importances = pd.DataFrame({'feature': X_train.columns, 'importance': importances})\n\n# # 중요도에 따라 특성 정렬\n# feature_importances = feature_importances.sort_values('importance', ascending=False)\n\n# # 중요도가 높은 특성 출력\n# print(feature_importances)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:46.187668Z","iopub.execute_input":"2024-02-20T11:16:46.187962Z","iopub.status.idle":"2024-02-20T11:16:46.192593Z","shell.execute_reply.started":"2024-02-20T11:16:46.187937Z","shell.execute_reply":"2024-02-20T11:16:46.191586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# feature_importances[feature_importances['importance'] >= 200]['feature'].to_list()","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:46.193741Z","iopub.execute_input":"2024-02-20T11:16:46.194026Z","iopub.status.idle":"2024-02-20T11:16:46.202520Z","shell.execute_reply.started":"2024-02-20T11:16:46.194002Z","shell.execute_reply":"2024-02-20T11:16:46.201720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_submission = data_submission[cols_pred].to_pandas()\nX_submission = convert_strings(X_submission)\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# X_submission.byoccupationinc_3656910L.astype(float)\n# X_submission['byoccupationinc_3656910L']  = pd.to_numeric(X_submission['byoccupationinc_3656910L'], errors='coerce')\n# X_submission['childnum_21L']              = pd.to_numeric(X_submission['childnum_21L'], errors='coerce')\n# X_submission['credacc_transactions_402L'] = pd.to_numeric(X_submission['credacc_transactions_402L'], errors='coerce')\n\ny_submission_pred = gbm.predict(X_submission, num_iteration=gbm.best_iteration)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:46.203559Z","iopub.execute_input":"2024-02-20T11:16:46.203844Z","iopub.status.idle":"2024-02-20T11:16:46.402072Z","shell.execute_reply.started":"2024-02-20T11:16:46.203815Z","shell.execute_reply":"2024-02-20T11:16:46.401253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\n    \"case_id\": data_submission[\"case_id\"].to_numpy(),\n    \"score\": y_submission_pred\n}).set_index('case_id')\n\nsample = pd.read_csv(dataPath + 'sample_submission.csv')\n# sample['case_id']\n\nsubmission = pd.merge(sample['case_id'], submission, on='case_id').set_index('case_id')\n# submission\n\nsubmission.to_csv(\"./submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:46.403059Z","iopub.execute_input":"2024-02-20T11:16:46.403692Z","iopub.status.idle":"2024-02-20T11:16:46.426011Z","shell.execute_reply.started":"2024-02-20T11:16:46.403657Z","shell.execute_reply":"2024-02-20T11:16:46.425244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data_submission","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:46.427034Z","iopub.execute_input":"2024-02-20T11:16:46.427333Z","iopub.status.idle":"2024-02-20T11:16:46.431137Z","shell.execute_reply.started":"2024-02-20T11:16:46.427308Z","shell.execute_reply":"2024-02-20T11:16:46.430244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:46.432254Z","iopub.execute_input":"2024-02-20T11:16:46.432515Z","iopub.status.idle":"2024-02-20T11:16:46.450538Z","shell.execute_reply.started":"2024-02-20T11:16:46.432492Z","shell.execute_reply":"2024-02-20T11:16:46.449680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# submission = pd.DataFrame({\n#     \"case_id\": data_submission[\"case_id\"].to_numpy(),\n#     \"score\": y_submission_pred\n# }).set_index('case_id')\n# submission.to_csv(\"./submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-02-20T11:16:46.451890Z","iopub.execute_input":"2024-02-20T11:16:46.452287Z","iopub.status.idle":"2024-02-20T11:16:46.456570Z","shell.execute_reply.started":"2024-02-20T11:16:46.452253Z","shell.execute_reply":"2024-02-20T11:16:46.455643Z"},"trusted":true},"execution_count":null,"outputs":[]}]}