{"metadata":{"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"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"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# https://www.kaggle.com/code/jeffersusus/home-credit-lgb-cat-ensemble","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:36:37.210765Z","iopub.execute_input":"2024-05-03T13:36:37.211135Z","iopub.status.idle":"2024-05-03T13:36:37.216299Z","shell.execute_reply.started":"2024-05-03T13:36:37.211101Z","shell.execute_reply":"2024-05-03T13:36:37.215369Z"},"trusted":true},"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\n\nfrom 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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2024-05-03T13:36:37.218257Z","iopub.execute_input":"2024-05-03T13:36:37.219107Z","iopub.status.idle":"2024-05-03T13:36:41.822751Z","shell.execute_reply.started":"2024-05-03T13:36:37.219073Z","shell.execute_reply":"2024-05-03T13:36:41.822006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n# ROOT = Path(\"../home-credit-credit-risk-model-stability\")\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:36:41.823796Z","iopub.execute_input":"2024-05-03T13:36:41.824318Z","iopub.status.idle":"2024-05-03T13:36:41.830565Z","shell.execute_reply.started":"2024-05-03T13:36:41.824293Z","shell.execute_reply":"2024-05-03T13:36:41.829816Z"},"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.9:\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\n\n\nclass Aggregator:\n    #Please add or subtract features yourself, be aware that too many features will take up too much space.\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        \n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return expr_max +expr_last+expr_mean\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        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return  expr_max +expr_last+expr_mean\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        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        #expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        return  expr_max +expr_last#+expr_count\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        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return  expr_max +expr_last\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] \n        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return  expr_max +expr_last\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\n\ndef read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    cols = [col for col in df.columns if col[-1] in (\"M\",)]\n    for col in cols:\n        df = df.with_columns(\n            pl.when(df[col].str.contains(\"a55475b1\"))\n            .then(None)\n            .otherwise(df[col])\n            .alias(col)\n        )    \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\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        for col in cols:\n            df = df.with_columns(\n                pl.when(df[col].str.contains(\"a55475b1\"))\n                .then(None)\n                .otherwise(df[col])\n                .alias(col)\n            )           \n            \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\n\ndef 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\n\ndef 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\n\ndef 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","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:36:41.833504Z","iopub.execute_input":"2024-05-03T13:36:41.833858Z","iopub.status.idle":"2024-05-03T13:36:41.875831Z","shell.execute_reply.started":"2024-05-03T13:36:41.833828Z","shell.execute_reply":"2024-05-03T13:36:41.874924Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndata_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-05-03T13:36:41.876844Z","iopub.execute_input":"2024-05-03T13:36:41.877166Z","iopub.status.idle":"2024-05-03T13:39:34.130617Z","shell.execute_reply.started":"2024-05-03T13:36:41.877143Z","shell.execute_reply":"2024-05-03T13:39:34.129646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ngc.collect()\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:39:34.131859Z","iopub.execute_input":"2024-05-03T13:39:34.132174Z","iopub.status.idle":"2024-05-03T13:40:29.630994Z","shell.execute_reply.started":"2024-05-03T13:39:34.132147Z","shell.execute_reply":"2024-05-03T13:40:29.629907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # 相关性去重\n# nums=df_train.select_dtypes(exclude='category').columns\n# from itertools import combinations, permutations\n# #df_train=df_train[nums]\n# nans_df = df_train[nums].isna()\n# nans_groups={}\n# for col in nums:\n#     cur_group = nans_df[col].sum()\n#     try:\n#         nans_groups[cur_group].append(col)\n#     except:\n#         nans_groups[cur_group]=[col]\n# del nans_df; x=gc.collect()\n\n# def reduce_group(grps):\n#     use = []\n#     for g in grps:\n#         mx = 0; vx = g[0]\n#         for gg in g:\n#             n = df_train[gg].nunique()\n#             if n>mx:\n#                 mx = n\n#                 vx = gg\n#             #print(str(gg)+'-'+str(n),', ',end='')\n#         use.append(vx)\n#         #print()\n#     print('Use these',use)\n#     return use\n\n# def group_columns_by_correlation(matrix, threshold=0.8):\n#     # 计算列之间的相关性\n#     correlation_matrix = matrix.corr()\n\n#     # 分组列\n#     groups = []\n#     remaining_cols = list(matrix.columns)\n#     while remaining_cols:\n#         col = remaining_cols.pop(0)\n#         group = [col]\n#         correlated_cols = [col]\n#         for c in remaining_cols:\n#             if correlation_matrix.loc[col, c] >= threshold:\n#                 group.append(c)\n#                 correlated_cols.append(c)\n#         groups.append(group)\n#         remaining_cols = [c for c in remaining_cols if c not in correlated_cols]\n    \n#     return groups\n\n# uses=[]\n# for k,v in nans_groups.items():\n#     if len(v)>1:\n#             Vs = nans_groups[k]\n#             #cross_features=list(combinations(Vs, 2))\n#             #make_corr(Vs)\n#             grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n#             use=reduce_group(grps)\n#             uses=uses+use\n#             #make_corr(use)\n#     else:\n#         uses=uses+v\n#     print('####### NAN count =',k)\n# print(uses)\n# print(len(uses))\n# uses=uses+list(df_train.select_dtypes(include='category').columns)\n# print(len(uses))\n# df_train=df_train[uses]","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2024-05-03T13:40:29.633134Z","iopub.execute_input":"2024-05-03T13:40:29.633566Z","iopub.status.idle":"2024-05-03T13:40:29.640842Z","shell.execute_reply.started":"2024-05-03T13:40:29.633526Z","shell.execute_reply":"2024-05-03T13:40:29.639570Z"},"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"uses = ['case_id', 'WEEK_NUM', 'target', 'month_decision', 'weekday_decision', 'credamount_770A', 'applicationcnt_361L', 'applications30d_658L', 'applicationscnt_1086L', 'applicationscnt_464L', 'applicationscnt_867L', 'clientscnt_1022L', 'clientscnt_100L', 'clientscnt_1071L', 'clientscnt_1130L', 'clientscnt_157L', 'clientscnt_257L', 'clientscnt_304L', 'clientscnt_360L', 'clientscnt_493L', 'clientscnt_533L', 'clientscnt_887L', 'clientscnt_946L', 'deferredmnthsnum_166L', 'disbursedcredamount_1113A', 'downpmt_116A', 'homephncnt_628L', 'isbidproduct_1095L', 'mobilephncnt_593L', 'numactivecreds_622L', 'numactivecredschannel_414L', 'numactiverelcontr_750L', 'numcontrs3months_479L', 'numnotactivated_1143L', 'numpmtchanneldd_318L', 'numrejects9m_859L', 'sellerplacecnt_915L', 'max_mainoccupationinc_384A', 'max_birth_259D', 'max_num_group1_9', 'birthdate_574D', 'contractssum_5085716L', 'dateofbirth_337D', 'days180_256L', 'days30_165L', 'days360_512L', 'firstquarter_103L', 'fourthquarter_440L', 'secondquarter_766L', 'thirdquarter_1082L', 'max_debtoutstand_525A', 'max_debtoverdue_47A', 'max_refreshdate_3813885D', 'mean_refreshdate_3813885D', 'pmtscount_423L', 'pmtssum_45A', 'responsedate_1012D', 'responsedate_4527233D', 'responsedate_4917613D', 'actualdpdtolerance_344P', 'amtinstpaidbefduel24m_4187115A', 'numinstlswithdpd5_4187116L', 'annuitynextmonth_57A', 'currdebt_22A', 'currdebtcredtyperange_828A', 'numinstls_657L', 'totalsettled_863A', 'mindbddpdlast24m_3658935P', 'avgdbddpdlast3m_4187120P', 'mindbdtollast24m_4525191P', 'avgdpdtolclosure24_3658938P', 'avginstallast24m_3658937A', 'maxinstallast24m_3658928A', 'avglnamtstart24m_4525187A', 'avgmaxdpdlast9m_3716943P', 'avgoutstandbalancel6m_4187114A', 'avgpmtlast12m_4525200A', 'cntincpaycont9m_3716944L', 'cntpmts24_3658933L', 'commnoinclast6m_3546845L', 'maxdpdfrom6mto36m_3546853P', 'datefirstoffer_1144D', 'datelastunpaid_3546854D', 'daysoverduetolerancedd_3976961L', 'numinsttopaygr_769L', 'dtlastpmtallstes_4499206D', 'eir_270L', 'firstclxcampaign_1125D', 'firstdatedue_489D', 'inittransactionamount_650A', 'lastactivateddate_801D', 'lastapplicationdate_877D', 'mean_creationdate_885D', 'max_num_group1', 'last_num_group1', 'max_num_group2_14', 'last_num_group2_14', 'lastapprcredamount_781A', 'lastapprdate_640D', 'lastdelinqdate_224D', 'lastrejectcredamount_222A', 'lastrejectdate_50D', 'maininc_215A', 'mastercontrelectronic_519L', 'mastercontrexist_109L', 'maxannuity_159A', 'maxdebt4_972A', 'maxdpdlast24m_143P', 'maxdpdlast3m_392P', 'maxdpdtolerance_374P', 'maxdbddpdlast1m_3658939P', 'maxdbddpdtollast12m_3658940P', 'maxdbddpdtollast6m_4187119P', 'maxdpdinstldate_3546855D', 'maxdpdinstlnum_3546846P', 'maxlnamtstart6m_4525199A', 'maxoutstandbalancel12m_4187113A', 'maxpmtlast3m_4525190A', 'numinstpaidearly_338L', 'numinstpaidearly5d_1087L', 'numinstpaidlate1d_3546852L', 'numincomingpmts_3546848L', 'numinstlsallpaid_934L', 'numinstlswithdpd10_728L', 'numinstlswithoutdpd_562L', 'numinstpaid_4499208L', 'numinstpaidearly3d_3546850L', 'numinstregularpaidest_4493210L', 'numinstpaidearly5dest_4493211L', 'sumoutstandtotalest_4493215A', 'numinstpaidlastcontr_4325080L', 'numinstregularpaid_973L', 'pctinstlsallpaidearl3d_427L', 'pctinstlsallpaidlate1d_3546856L', 'pctinstlsallpaidlat10d_839L', 'pctinstlsallpaidlate4d_3546849L', 'pctinstlsallpaidlate6d_3546844L', 'pmtnum_254L', 'posfpd10lastmonth_333P', 'posfpd30lastmonth_3976960P', 'posfstqpd30lastmonth_3976962P', 'price_1097A', 'sumoutstandtotal_3546847A', 'totaldebt_9A', 'totinstallast1m_4525188A', 'mean_actualdpd_943P', 'max_annuity_853A', 'mean_annuity_853A', 'mean_credacc_actualbalance_314A', 'mean_credacc_maxhisbal_375A', 'mean_credacc_minhisbal_90A', 'max_credacc_transactions_402L', 'max_credacc_credlmt_575A', 'max_credamount_590A', 'max_downpmt_134A', 'mean_credacc_credlmt_575A', 'mean_credamount_590A', 'mean_downpmt_134A', 'max_currdebt_94A', 'mean_currdebt_94A', 'max_mainoccupationinc_437A', 'mean_mainoccupationinc_437A', 'mean_maxdpdtolerance_577P', 'max_outstandingdebt_522A', 'mean_outstandingdebt_522A', 'mean_revolvingaccount_394A', 'last_actualdpd_943P', 'last_annuity_853A', 'last_credacc_credlmt_575A', 'last_credamount_590A', 'last_downpmt_134A', 'last_currdebt_94A', 'last_mainoccupationinc_437A', 'last_maxdpdtolerance_577P', 'last_outstandingdebt_522A', 'max_approvaldate_319D', 'mean_approvaldate_319D', 'max_dateactivated_425D', 'mean_dateactivated_425D', 'max_dtlastpmt_581D', 'mean_dtlastpmt_581D', 'max_dtlastpmtallstes_3545839D', 'mean_dtlastpmtallstes_3545839D', 'max_employedfrom_700D', 'max_firstnonzeroinstldate_307D', 'mean_firstnonzeroinstldate_307D', 'last_approvaldate_319D', 'last_creationdate_885D', 'last_dateactivated_425D', 'last_dtlastpmt_581D', 'last_dtlastpmtallstes_3545839D', 'last_employedfrom_700D', 'last_firstnonzeroinstldate_307D', 'max_byoccupationinc_3656910L', 'max_childnum_21L', 'max_pmtnum_8L', 'last_byoccupationinc_3656910L', 'last_childnum_21L', 'last_pmtnum_8L', 'max_amount_4527230A', 'max_recorddate_4527225D', 'max_num_group1_3', 'last_num_group1_3', 'max_pmtamount_36A', 'last_pmtamount_36A', 'max_processingdate_168D', 'last_processingdate_168D', 'max_num_group1_5', 'mean_credlmt_230A', 'mean_credlmt_935A', 'mean_pmts_dpd_1073P', 'max_dpdmaxdatemonth_89T', 'max_dpdmaxdateyear_596T', 'max_pmts_dpd_303P', 'mean_dpdmax_757P', 'max_dpdmaxdatemonth_442T', 'max_dpdmaxdateyear_896T', 'mean_pmts_dpd_303P', 'mean_instlamount_768A', 'mean_instlamount_852A', 'mean_monthlyinstlamount_332A', 'max_monthlyinstlamount_674A', 'mean_monthlyinstlamount_674A', 'mean_outstandingamount_354A', 'mean_outstandingamount_362A', 'mean_overdueamount_31A', 'mean_overdueamount_659A', 'max_numberofoverdueinstls_725L', 'mean_overdueamountmax2_14A', 'mean_totaloutstanddebtvalue_39A', 'mean_dateofcredend_289D', 'mean_dateofcredstart_739D', 'max_lastupdate_1112D', 'mean_lastupdate_1112D', 'max_numberofcontrsvalue_258L', 'max_numberofoverdueinstlmax_1039L', 'max_overdueamountmaxdatemonth_365T', 'max_overdueamountmaxdateyear_2T', 'mean_pmts_overdue_1140A', 'max_pmts_month_158T', 'max_pmts_year_1139T', 'mean_overdueamountmax2_398A', 'max_dateofcredend_353D', 'max_dateofcredstart_181D', 'mean_dateofcredend_353D', 'max_numberofoverdueinstlmax_1151L', 'mean_overdueamountmax_35A', 'max_overdueamountmaxdatemonth_284T', 'max_overdueamountmaxdateyear_994T', 'mean_pmts_overdue_1152A', 'max_residualamount_488A', 'mean_residualamount_856A', 'max_totalamount_6A', 'mean_totalamount_6A', 'mean_totalamount_996A', 'mean_totaldebtoverduevalue_718A', 'mean_totaloutstanddebtvalue_668A', 'max_numberofcontrsvalue_358L', 'max_dateofrealrepmt_138D', 'mean_dateofrealrepmt_138D', 'max_lastupdate_388D', 'mean_lastupdate_388D', 'max_numberofoverdueinstlmaxdat_148D', 'mean_numberofoverdueinstlmaxdat_641D', 'mean_overdueamountmax2date_1002D', 'max_overdueamountmax2date_1142D', 'last_refreshdate_3813885D', 'max_annualeffectiverate_199L', 'max_annualeffectiverate_63L', 'max_nominalrate_281L', 'max_nominalrate_498L', 'max_numberofinstls_229L', 'max_numberofinstls_320L', 'max_numberofoutstandinstls_520L', 'max_numberofoutstandinstls_59L', 'max_numberofoverdueinstls_834L', 'max_periodicityofpmts_1102L', 'max_periodicityofpmts_837L', 'last_num_group1_6', 'last_mainoccupationinc_384A', 'last_birth_259D', 'max_empl_employedfrom_271D', 'last_personindex_1023L', 'last_persontype_1072L', 'max_collater_valueofguarantee_1124L', 'max_collater_valueofguarantee_876L', 'max_pmts_month_706T', 'max_pmts_year_507T', 'last_pmts_month_158T', 'last_pmts_year_1139T', 'last_pmts_month_706T', 'last_pmts_year_507T', 'max_num_group1_13', 'max_num_group2_13', 'last_num_group2_13', 'max_num_group1_15', 'max_num_group2_15', 'description_5085714M', 'education_1103M', 'maritalst_385M', 'requesttype_4525192L', 'bankacctype_710L', 'cardtype_51L', 'credtype_322L', 'disbursementtype_67L', 'inittransactioncode_186L', 'isdebitcard_729L', 'lastapprcommoditycat_1041M', 'lastcancelreason_561M', 'lastrejectcommoditycat_161M', 'lastrejectreason_759M', 'lastrejectreasonclient_4145040M', 'lastst_736L', 'opencred_647L', 'paytype1st_925L', 'paytype_783L', 'twobodfilling_608L', 'typesuite_864L', 'max_cancelreason_3545846M', 'max_education_1138M', 'max_postype_4733339M', 'max_rejectreason_755M', 'max_rejectreasonclient_4145042M', 'last_cancelreason_3545846M', 'last_education_1138M', 'last_postype_4733339M', 'last_rejectreason_755M', 'last_rejectreasonclient_4145042M', 'max_credacc_status_367L', 'max_credtype_587L', 'max_familystate_726L', 'max_inittransactioncode_279L', 'max_isbidproduct_390L', 'max_isdebitcard_527L', 'max_status_219L', 'last_credtype_587L', 'last_familystate_726L', 'last_inittransactioncode_279L', 'last_isbidproduct_390L', 'last_status_219L', 'max_classificationofcontr_13M', 'max_contractst_545M', 'max_financialinstitution_591M', 'max_purposeofcred_426M', 'max_purposeofcred_874M', 'max_subjectrole_182M', 'max_subjectrole_93M', 'max_education_927M', 'max_language1_981M', 'last_language1_981M', 'max_contaddr_matchlist_1032L', 'max_contaddr_smempladdr_334L', 'max_empl_employedtotal_800L', 'max_empl_industry_691L', 'max_familystate_447L', 'max_incometype_1044T', 'max_relationshiptoclient_415T', 'max_relationshiptoclient_642T', 'max_remitter_829L', 'max_role_1084L', 'max_safeguarantyflag_411L', 'max_sex_738L', 'max_type_25L', 'last_contaddr_matchlist_1032L', 'last_contaddr_smempladdr_334L', 'last_incometype_1044T', 'last_relationshiptoclient_415T', 'last_relationshiptoclient_642T', 'last_remitter_829L', 'last_role_1084L', 'last_safeguarantyflag_411L', 'last_sex_738L', 'last_type_25L', 'max_collater_typofvalofguarant_298M', 'max_collater_typofvalofguarant_407M', 'max_collaterals_typeofguarante_359M', 'max_collaterals_typeofguarante_669M', 'max_subjectroles_name_541M', 'max_subjectroles_name_838M', 'max_conts_type_509L', 'max_credacc_cards_status_52L', 'last_conts_type_509L']\ndf_train=df_train[uses]\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:40:29.642649Z","iopub.execute_input":"2024-05-03T13:40:29.643094Z","iopub.status.idle":"2024-05-03T13:40:32.217204Z","shell.execute_reply.started":"2024-05-03T13:40:29.643054Z","shell.execute_reply":"2024-05-03T13:40:32.216177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# sample = pd.read_csv(\"/kaggle/input/home-credit-credit-risk-model-stability/sample_submission.csv\")\ndevice='gpu'\n# #n_samples=200000\nn_est=6000\n# DRY_RUN = True if sample.shape[0] == 10 else False   \n# if DRY_RUN:\n#     device='cpu'\n#     df_train = df_train.iloc[:50000]\n#     #n_samples=10000\n#     n_est=600\n# print(device)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:40:32.220337Z","iopub.execute_input":"2024-05-03T13:40:32.221005Z","iopub.status.idle":"2024-05-03T13:40:32.225833Z","shell.execute_reply.started":"2024-05-03T13:40:32.220977Z","shell.execute_reply":"2024-05-03T13:40:32.224927Z"},"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-05-03T13:40:32.227054Z","iopub.execute_input":"2024-05-03T13:40:32.227358Z","iopub.status.idle":"2024-05-03T13:40:32.653251Z","shell.execute_reply.started":"2024-05-03T13:40:32.227321Z","shell.execute_reply":"2024-05-03T13:40:32.652285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:40:32.654381Z","iopub.execute_input":"2024-05-03T13:40:32.654666Z","iopub.status.idle":"2024-05-03T13:40:33.186112Z","shell.execute_reply.started":"2024-05-03T13:40:32.654641Z","shell.execute_reply":"2024-05-03T13:40:33.185111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### LGBM+Cat\n","metadata":{}},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:40:33.187414Z","iopub.execute_input":"2024-05-03T13:40:33.187789Z","iopub.status.idle":"2024-05-03T13:40:34.595702Z","shell.execute_reply.started":"2024-05-03T13:40:33.187755Z","shell.execute_reply":"2024-05-03T13:40:34.594922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)\ndf_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:40:34.596788Z","iopub.execute_input":"2024-05-03T13:40:34.597114Z","iopub.status.idle":"2024-05-03T13:40:38.796752Z","shell.execute_reply.started":"2024-05-03T13:40:34.597088Z","shell.execute_reply":"2024-05-03T13:40:38.795919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\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\": device, \n    \"verbose\": -1,\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:40:38.797837Z","iopub.execute_input":"2024-05-03T13:40:38.798134Z","iopub.status.idle":"2024-05-03T13:40:38.804376Z","shell.execute_reply.started":"2024-05-03T13:40:38.798108Z","shell.execute_reply":"2024-05-03T13:40:38.803209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom catboost import CatBoostClassifier, Pool\n\nfitted_models_cat = []\nfitted_models_lgb = []\n\ncv_scores_cat = []\ncv_scores_lgb = []\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# \n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n    train_pool = Pool(X_train, y_train,cat_features=cat_cols)\n    val_pool = Pool(X_valid, y_valid,cat_features=cat_cols)\n    clf = CatBoostClassifier(\n    eval_metric='AUC',\n    task_type='GPU',\n    learning_rate=0.03,\n    iterations=n_est,\n#     early_stopping_rounds=100,\n    )\n    random_seed=3107\n    clf.fit(train_pool, eval_set=val_pool,verbose=300)\n    fitted_models_cat.append(clf)\n    y_pred_valid = clf.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_cat.append(auc_score)\n    \n    \n    X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n    X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\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(100)] )\n    \n    fitted_models_lgb.append(model)\n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_lgb.append(auc_score)\n    \n    \nprint(\"CV AUC scores: \", cv_scores_cat)\nprint(\"Maximum CV AUC score: \", max(cv_scores_cat))\n\n\nprint(\"CV AUC scores: \", cv_scores_lgb)\nprint(\"Maximum CV AUC score: \", max(cv_scores_lgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:40:38.805475Z","iopub.execute_input":"2024-05-03T13:40:38.805715Z","iopub.status.idle":"2024-05-03T14:43:32.286726Z","shell.execute_reply.started":"2024-05-03T13:40:38.805694Z","shell.execute_reply":"2024-05-03T14:43:32.285731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pickle","metadata":{"execution":{"iopub.status.busy":"2024-05-03T14:43:46.864336Z","iopub.execute_input":"2024-05-03T14:43:46.865220Z","iopub.status.idle":"2024-05-03T14:43:46.870310Z","shell.execute_reply.started":"2024-05-03T14:43:46.865178Z","shell.execute_reply":"2024-05-03T14:43:46.869250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open('fitted_models_cat_fitted_models_lgb.pkl', 'wb') as f:\n    pickle.dump((fitted_models_cat,fitted_models_lgb),f)   ","metadata":{"execution":{"iopub.status.busy":"2024-05-03T14:43:47.941532Z","iopub.execute_input":"2024-05-03T14:43:47.941912Z","iopub.status.idle":"2024-05-03T14:43:48.313111Z","shell.execute_reply.started":"2024-05-03T14:43:47.941860Z","shell.execute_reply":"2024-05-03T14:43:48.311960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# TabNet","metadata":{}}]}