{"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":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30664,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# https://blog.csdn.net/s09094031/article/details/92428209?app_version=6.3.1&csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%2292428209%22%2C%22source%22%3A%22unlogin%22%7D&utm_source=app","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-28T13:23:01.086062Z","iopub.execute_input":"2024-03-28T13:23:01.086408Z","iopub.status.idle":"2024-03-28T13:23:02.319909Z","shell.execute_reply.started":"2024-03-28T13:23:01.086378Z","shell.execute_reply":"2024-03-28T13:23:02.318990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nimport lightgbm as lgb\n\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import KNNImputer","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:23:02.321616Z","iopub.execute_input":"2024-03-28T13:23:02.322010Z","iopub.status.idle":"2024-03-28T13:23:06.668982Z","shell.execute_reply.started":"2024-03-28T13:23:02.321986Z","shell.execute_reply":"2024-03-28T13:23:06.667999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Pipeline:\n\n    def set_table_dtypes(df):\n        for col in df.columns:\n            if col in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Int64))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col[-1] in (\"P\", \"A\"):\n                df = df.with_columns(pl.col(col).cast(pl.Float64))\n            elif col[-1] in (\"M\",):\n                df = df.with_columns(pl.col(col).cast(pl.String))\n            elif col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n        return df\n\n    def handle_dates(df):\n        for col in df.columns:\n            if col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col) - pl.col(\"date_decision\"))  #!!?\n                df = df.with_columns(pl.col(col).dt.total_days()) # t - t-1\n        df = df.drop(\"date_decision\", \"MONTH\")\n        return df\n\n    def filter_cols(df):\n        for col in df.columns:\n            if col not in [\"target\", \"case_id\", \"WEEK_NUM\"]:\n                isnull = df[col].is_null().mean()\n                if isnull > 0.7:\n                    df = df.drop(col)\n        \n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) & (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n        \n        return df","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:23:06.670085Z","iopub.execute_input":"2024-03-28T13:23:06.670609Z","iopub.status.idle":"2024-03-28T13:23:06.683111Z","shell.execute_reply.started":"2024-03-28T13:23:06.670585Z","shell.execute_reply":"2024-03-28T13:23:06.681920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Aggregator:\n    \n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\n    \n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\n    \n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\n    \n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\n    \n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]  # max & replace col name\n        return expr_max\n    \n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:23:06.686261Z","iopub.execute_input":"2024-03-28T13:23:06.686761Z","iopub.status.idle":"2024-03-28T13:23:06.701357Z","shell.execute_reply.started":"2024-03-28T13:23:06.686731Z","shell.execute_reply":"2024-03-28T13:23:06.700543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    if depth in [1,2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df)) \n    return df\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    \n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.set_table_dtypes)\n        if depth in [1, 2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        chunks.append(df)\n    \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:23:06.702706Z","iopub.execute_input":"2024-03-28T13:23:06.703086Z","iopub.status.idle":"2024-03-28T13:23:06.716633Z","shell.execute_reply.started":"2024-03-28T13:23:06.703013Z","shell.execute_reply":"2024-03-28T13:23:06.715810Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n    for i, df in enumerate(depth_0 + depth_1 + depth_2):\n        df_base = df_base.join(df, how=\"left\", on=\"case_id\", suffix=f\"_{i}\")\n    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:23:06.717599Z","iopub.execute_input":"2024-03-28T13:23:06.717925Z","iopub.status.idle":"2024-03-28T13:23:06.727465Z","shell.execute_reply.started":"2024-03-28T13:23:06.717902Z","shell.execute_reply":"2024-03-28T13:23:06.726629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    return df_data, cat_cols","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:23:06.728727Z","iopub.execute_input":"2024-03-28T13:23:06.729025Z","iopub.status.idle":"2024-03-28T13:23:06.742499Z","shell.execute_reply.started":"2024-03-28T13:23:06.729003Z","shell.execute_reply":"2024-03-28T13:23:06.741743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:23:06.743592Z","iopub.execute_input":"2024-03-28T13:23:06.743919Z","iopub.status.idle":"2024-03-28T13:23:06.753488Z","shell.execute_reply.started":"2024-03-28T13:23:06.743889Z","shell.execute_reply":"2024-03-28T13:23:06.752732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:24:38.795483Z","iopub.execute_input":"2024-03-28T13:24:38.796174Z","iopub.status.idle":"2024-03-28T13:26:45.819089Z","shell.execute_reply.started":"2024-03-28T13:24:38.796144Z","shell.execute_reply":"2024-03-28T13:26:45.817930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:26:45.821151Z","iopub.execute_input":"2024-03-28T13:26:45.821996Z","iopub.status.idle":"2024-03-28T13:26:55.730589Z","shell.execute_reply.started":"2024-03-28T13:26:45.821963Z","shell.execute_reply":"2024-03-28T13:26:55.729695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:29:22.257741Z","iopub.execute_input":"2024-03-28T13:29:22.258090Z","iopub.status.idle":"2024-03-28T13:29:22.413525Z","shell.execute_reply.started":"2024-03-28T13:29:22.258065Z","shell.execute_reply":"2024-03-28T13:29:22.412727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:29:25.877199Z","iopub.execute_input":"2024-03-28T13:29:25.877546Z","iopub.status.idle":"2024-03-28T13:29:25.917163Z","shell.execute_reply.started":"2024-03-28T13:29:25.877520Z","shell.execute_reply":"2024-03-28T13:29:25.916261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Selection","metadata":{}},{"cell_type":"code","source":"# drop_list = ['max_empl_employedtotal_800L', 'monthsannuity_845L', 'lastactivateddate_801D', \n#              'max_numberofoverdueinstls_725L', 'requesttype_4525192L', 'max_pmts_year_507T', \n#              'lastrejectcommodtypec_5251769M', 'numinstpaidlate1d_3546852L', 'numinstmatpaidtearly2d_4499204L', \n#              'max_overdueamountmaxdateyear_2T', 'max_overdueamountmaxdateyear_994T', 'twobodfilling_608L', \n#              'maxdpdlast12m_727P', 'numinsttopaygrest_4493213L', 'currdebtcredtyperange_828A', 'maxdpdlast9m_1059P', \n#              'numinstpaid_4499208L', 'applicationscnt_867L', 'numinstlswithoutdpd_562L', 'fourthquarter_440L', \n#              'max_num_group1_6', 'max_safeguarantyflag_411L', 'max_dpdmaxdateyear_896T', 'numinstregularpaid_973L', \n#              'avgdbdtollast24m_4525197P', 'numinstpaidearly5dest_4493211L', 'numinstpaidearly5dobd_4499205L', \n#              'homephncnt_628L', 'max_role_1084L', 'max_remitter_829L', 'numrejects9m_859L', \n#              'numinstlallpaidearly3d_817L', 'numinstpaidearly3dest_4493216L', 'annuitynextmonth_57A', \n#              'numinstregularpaidest_4493210L', 'firstquarter_103L', 'clientscnt_533L', 'maxdpdlast3m_392P', \n#              'sellerplacescnt_216L', 'secondquarter_766L', 'max_periodicityofpmts_1102L', 'numinstlsallpaid_934L', \n#              'opencred_647L', 'numinstls_657L', 'numactivecredschannel_414L', 'numinstpaidearly3d_3546850L', \n#              'numinstpaidearlyest_4493214L', 'max_totaldebtoverduevalue_718A', 'paytype1st_925L', \n#              'max_inittransactioncode_279L', 'max_contractst_545M', 'max_cancelreason_3545846M', \n#              'max_rejectreason_755M', 'max_personindex_1023L', 'max_subjectroles_name_838M', 'maxdpdlast6m_474P', \n#              'max_subjectrole_182M', 'actualdpdtolerance_344P', 'max_num_group1_9', 'max_collaterals_typeofguarante_669M', \n#              'numinstpaidearly_338L', 'clientscnt_887L', 'maritalst_893M', 'max_subjectrole_93M', 'max_type_25L', \n#              'max_refreshdate_3813885D', 'numinstpaidearly5d_1087L', 'max_actualdpd_943P', 'max_description_351M', \n#              'education_88M', 'clientscnt_946L', 'clientscnt12m_3712952L', 'numactiverelcontr_750L', \n#              'max_education_927M', 'applicationscnt_1086L', 'sellerplacecnt_915L', 'max_purposeofcred_426M', \n#              'max_subjectroles_name_541M', 'clientscnt_1022L', 'clientscnt_360L', 'max_totaloutstanddebtvalue_668A', \n#              'applicationscnt_629L', 'max_outstandingamount_354A', 'clientscnt_1071L', 'numactivecreds_622L', \n#              'clientscnt_493L', 'paytype_783L', 'clientscnt6m_3712949L', 'clientscnt_304L', 'max_classificationofcontr_13M', \n#              'numnotactivated_1143L', 'commnoinclast6m_3546845L', 'max_numberofoutstandinstls_520L', \n#              'applicationscnt_464L', 'clientscnt_1130L', 'max_numberofoverdueinstls_834L', 'clientscnt3m_3712950L', \n#              'max_rejectreasonclient_4145042M', 'max_contaddr_smempladdr_334L', 'numpmtchanneldd_318L', \n#              'numcontrs3months_479L', 'max_overdueamount_31A', 'max_collaterals_typeofguarante_359M', \n#              'clientscnt_257L', 'clientscnt_157L', 'applications30d_658L', 'clientscnt_100L', \n#              'max_collater_typofvalofguarant_298M', 'max_pmts_month_706T', 'max_pmts_month_158T', \n#              'mastercontrexist_109L', 'max_collater_typofvalofguarant_407M', 'mastercontrelectronic_519L', \n#              'applicationcnt_361L', 'max_persontype_1072L', 'max_empladdr_district_926M', 'deferredmnthsnum_166L', \n#              'max_empladdr_zipcode_114M', 'max_persontype_792L', 'max_contaddr_matchlist_1032L']","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_train = df_train.drop(drop_list)\n# df_test = df_test.drop(drop_list)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T12:49:24.065186Z","iopub.execute_input":"2024-03-27T12:49:24.065543Z","iopub.status.idle":"2024-03-27T12:49:24.076367Z","shell.execute_reply.started":"2024-03-27T12:49:24.065512Z","shell.execute_reply":"2024-03-27T12:49:24.075466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Drop the insignificant features\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:29:32.559415Z","iopub.execute_input":"2024-03-28T13:29:32.559800Z","iopub.status.idle":"2024-03-28T13:29:35.595035Z","shell.execute_reply.started":"2024-03-28T13:29:32.559772Z","shell.execute_reply":"2024-03-28T13:29:35.594105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:29:35.596904Z","iopub.execute_input":"2024-03-28T13:29:35.597290Z","iopub.status.idle":"2024-03-28T13:29:56.674660Z","shell.execute_reply.started":"2024-03-28T13:29:35.597253Z","shell.execute_reply":"2024-03-28T13:29:56.673670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:29:56.675883Z","iopub.execute_input":"2024-03-28T13:29:56.676191Z","iopub.status.idle":"2024-03-28T13:29:56.820056Z","shell.execute_reply.started":"2024-03-28T13:29:56.676165Z","shell.execute_reply":"2024-03-28T13:29:56.819107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display(df_train.head())\ndisplay(df_test.head())","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:29:56.821949Z","iopub.execute_input":"2024-03-28T13:29:56.822232Z","iopub.status.idle":"2024-03-28T13:29:56.878627Z","shell.execute_reply.started":"2024-03-28T13:29:56.822209Z","shell.execute_reply":"2024-03-28T13:29:56.877749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Handle categorical features (Ordinal encoding)","metadata":{}},{"cell_type":"code","source":"# cat_list = [col for col in df_train.columns if df_train[col].dtype.name == 'category']\n\n# catfreq_dict = {}\n# catcatfreq_dict = {}\n\n# for col in cat_list:\n#     catfreq_dict[col] = len(list(df_train[col].value_counts()))\n#     catcatfreq_dict[col] = {}\n#     for d in dict(df_train[col].value_counts()).items():\n#         catcatfreq_dict[col][d[0]] = d[1]\n\n# catfreq_df = pd.DataFrame.from_dict(catfreq_dict, orient='index', columns=['Categories'])\n# display(catfreq_df.sort_values(by=\"Categories\", ascending=False).head())\n# display(catfreq_df.sort_values(by=\"Categories\", ascending=True).head())","metadata":{"execution":{"iopub.status.busy":"2024-03-27T12:12:23.358982Z","iopub.execute_input":"2024-03-27T12:12:23.359251Z","iopub.status.idle":"2024-03-27T12:12:23.363443Z","shell.execute_reply.started":"2024-03-27T12:12:23.359228Z","shell.execute_reply":"2024-03-27T12:12:23.362616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ordinal_enc = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=np.nan)\n# df_train[cat_list] = ordinal_enc.fit_transform(df_train[cat_list])\n# df_test[cat_list] = ordinal_enc.transform(df_test[cat_list])\n# df_train[cat_list].head()","metadata":{"execution":{"iopub.status.busy":"2024-03-26T15:28:34.248570Z","iopub.execute_input":"2024-03-26T15:28:34.249296Z","iopub.status.idle":"2024-03-26T15:28:51.354789Z","shell.execute_reply.started":"2024-03-26T15:28:34.249265Z","shell.execute_reply":"2024-03-26T15:28:51.353866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Handle NaN","metadata":{}},{"cell_type":"code","source":"# nan_list = []\n# for col, boo in df_train.isnull().any().items():\n#     if boo == True:\n#         nan_list.append(col)\n\n# print(f\"Number of col contains Nan value: {len(nan_list)}\")\n# for i, v in df_train.isna().sum().items():\n#     if v/len(df_train)>0.6:\n#         print(f\"{i} : \\t {round((v/len(df_train))*100)}% Nan \")","metadata":{"execution":{"iopub.status.busy":"2024-03-26T15:28:51.356395Z","iopub.execute_input":"2024-03-26T15:28:51.356671Z","iopub.status.idle":"2024-03-26T15:28:52.025413Z","shell.execute_reply.started":"2024-03-26T15:28:51.356647Z","shell.execute_reply":"2024-03-26T15:28:52.024446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ### trial\n# from sklearn.impute import SimpleImputer\n# imp = SimpleImputer(missing_values=np.nan, strategy='mean')\n# df_train[nan_list] = imp.fit_transform(df_train[nan_list])\n# df_test[nan_list] = imp.transform(df_test[nan_list])","metadata":{"execution":{"iopub.status.busy":"2024-03-26T15:28:52.026717Z","iopub.execute_input":"2024-03-26T15:28:52.027120Z","iopub.status.idle":"2024-03-26T15:29:01.039101Z","shell.execute_reply.started":"2024-03-26T15:28:52.027086Z","shell.execute_reply":"2024-03-26T15:29:01.038259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ## no work (too slow..) \n# ## require dimensionality reduction first & features with high feature impor. \n# imputer = KNNImputer()\n# df_train = imputer.fit_transform(df_train)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T19:36:22.776867Z","iopub.execute_input":"2024-03-22T19:36:22.777705Z","iopub.status.idle":"2024-03-22T20:09:17.911874Z","shell.execute_reply.started":"2024-03-22T19:36:22.777676Z","shell.execute_reply":"2024-03-22T20:09:17.910143Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,  \n    \"learning_rate\": 0.05,\n    \"n_estimators\": 2000,  \n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    'num_leaves':64,\n    \"device\": \"gpu\", \n    \"verbose\": -1,\n}\n\nfitted_models = []\ncv_scores = []\n\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n    \n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set = [(X_valid, y_valid)],\n        callbacks = [lgb.log_evaluation(200), lgb.early_stopping(60)] )\n    fitted_models.append(model)\n    \n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n    \nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-03-28T13:29:56.879993Z","iopub.execute_input":"2024-03-28T13:29:56.880375Z","iopub.status.idle":"2024-03-28T13:31:37.228293Z","shell.execute_reply.started":"2024-03-28T13:29:56.880343Z","shell.execute_reply":"2024-03-28T13:31:37.226860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T13:18:26.502595Z","iopub.execute_input":"2024-03-27T13:18:26.503365Z","iopub.status.idle":"2024-03-27T13:18:26.510284Z","shell.execute_reply.started":"2024-03-27T13:18:26.503332Z","shell.execute_reply":"2024-03-27T13:18:26.509202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb.plot_importance(fitted_models[2], importance_type=\"split\", figsize=(10,50))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-27T13:18:30.345065Z","iopub.execute_input":"2024-03-27T13:18:30.345898Z","iopub.status.idle":"2024-03-27T13:18:34.509305Z","shell.execute_reply.started":"2024-03-27T13:18:30.345863Z","shell.execute_reply":"2024-03-27T13:18:34.508154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features = X_train.columns\nimportances = fitted_models[2].feature_importances_\nfeature_importance = pd.DataFrame({'importance':importances,'features':features}).sort_values('importance', ascending=False).reset_index(drop=True)\nfeature_importance","metadata":{"execution":{"iopub.status.busy":"2024-03-27T13:19:43.110642Z","iopub.execute_input":"2024-03-27T13:19:43.111427Z","iopub.status.idle":"2024-03-27T13:19:43.127048Z","shell.execute_reply.started":"2024-03-27T13:19:43.111392Z","shell.execute_reply":"2024-03-27T13:19:43.126135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"drop_list = []\nfor i, f in feature_importance.iterrows():\n    if f['importance']<80:\n        drop_list.append(f['features'])\nprint(f\"Number of features which are not important: {len(drop_list)} \")","metadata":{"execution":{"iopub.status.busy":"2024-03-27T13:19:47.882983Z","iopub.execute_input":"2024-03-27T13:19:47.883708Z","iopub.status.idle":"2024-03-27T13:19:47.907877Z","shell.execute_reply.started":"2024-03-27T13:19:47.883676Z","shell.execute_reply":"2024-03-27T13:19:47.906848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(drop_list)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T13:20:01.554419Z","iopub.execute_input":"2024-03-27T13:20:01.555439Z","iopub.status.idle":"2024-03-27T13:20:01.560170Z","shell.execute_reply.started":"2024-03-27T13:20:01.555401Z","shell.execute_reply":"2024-03-27T13:20:01.559243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submission","metadata":{}},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\n\nlgb_pred = pd.Series(model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-03-26T13:57:28.866316Z","iopub.execute_input":"2024-03-26T13:57:28.866935Z","iopub.status.idle":"2024-03-26T13:57:28.910452Z","shell.execute_reply.started":"2024-03-26T13:57:28.866900Z","shell.execute_reply":"2024-03-26T13:57:28.909589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = lgb_pred","metadata":{"execution":{"iopub.status.busy":"2024-03-26T13:57:30.048698Z","iopub.execute_input":"2024-03-26T13:57:30.049082Z","iopub.status.idle":"2024-03-26T13:57:30.061698Z","shell.execute_reply.started":"2024-03-26T13:57:30.049052Z","shell.execute_reply":"2024-03-26T13:57:30.060777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-26T13:57:31.193109Z","iopub.execute_input":"2024-03-26T13:57:31.193821Z","iopub.status.idle":"2024-03-26T13:57:31.203538Z","shell.execute_reply.started":"2024-03-26T13:57:31.193790Z","shell.execute_reply":"2024-03-26T13:57:31.202386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-19T21:33:29.240571Z","iopub.execute_input":"2024-03-19T21:33:29.241019Z","iopub.status.idle":"2024-03-19T21:33:29.249670Z","shell.execute_reply.started":"2024-03-19T21:33:29.240982Z","shell.execute_reply":"2024-03-19T21:33:29.248856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* handle nan value (both numeric & categorical)\n* preprocess the minority categorical value (drop / keep)\n* float to int after ordinal encode\n* oversampling (smote? (considering date feature)\n* high dimension (pca) \n* create new features based on high fea_imp features\n...\n...","metadata":{}},{"cell_type":"code","source":"# X_resampled, y_resampled = SMOTE().fit_resample(X, y)","metadata":{"execution":{"iopub.status.busy":"2024-03-21T16:40:34.781235Z","iopub.execute_input":"2024-03-21T16:40:34.781815Z","iopub.status.idle":"2024-03-21T16:40:36.101878Z","shell.execute_reply.started":"2024-03-21T16:40:34.781774Z","shell.execute_reply":"2024-03-21T16:40:36.099587Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}