{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":11502521,"sourceType":"datasetVersion","datasetId":7012378}],"dockerImageVersionId":31011,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"papermill":{"default_parameters":{},"duration":33985.66718,"end_time":"2025-04-20T10:04:52.222503","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2025-04-20T00:38:26.555323","version":"2.5.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Project was created by Bikbulatov Daniil, Bykova Maria, Nemtsev Daniil and Vostrenkova Ekaterina and scientific adviser Petrosian Ovanes from Saint Petersburg State University, Russia. ","metadata":{}},{"cell_type":"markdown","source":"https://www.kaggle.com/bikbulatovdi\n\nhttps://www.kaggle.com/mashabykova\n\nhttps://www.kaggle.com/daniilnemcew\n\nhttps://www.kaggle.com/ekaterinamv\n\nhttps://www.kaggle.com/ovanespetrosian","metadata":{}},{"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'\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\nfrom catboost import CatBoostClassifier, Pool\nfrom lightgbm import LGBMClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import VotingClassifier","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":13.580607,"end_time":"2025-04-20T00:38:44.352986","exception":false,"start_time":"2025-04-20T00:38:30.772379","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:33.771748Z","iopub.execute_input":"2025-04-22T19:00:33.772277Z","iopub.status.idle":"2025-04-22T19:00:33.777554Z","shell.execute_reply.started":"2025-04-22T19:00:33.772256Z","shell.execute_reply":"2025-04-22T19:00:33.776811Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Set a seed for various non-deterministic processes for reproducibility\nimport random\ndef seed_it_all(seed=7):\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    random.seed(seed)\n    np.random.seed(seed)\n\nSEED = 0\n\n# set the seed for this run\nseed_it_all(SEED)","metadata":{"papermill":{"duration":0.010808,"end_time":"2025-04-20T00:38:44.368001","exception":false,"start_time":"2025-04-20T00:38:44.357193","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:33.778671Z","iopub.execute_input":"2025-04-22T19:00:33.778950Z","iopub.status.idle":"2025-04-22T19:00:33.793057Z","shell.execute_reply.started":"2025-04-22T19:00:33.778933Z","shell.execute_reply":"2025-04-22T19:00:33.792546Z"}},"outputs":[],"execution_count":null},{"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\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    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\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":{"papermill":{"duration":0.032056,"end_time":"2025-04-20T00:38:44.403892","exception":false,"start_time":"2025-04-20T00:38:44.371836","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.124040Z","iopub.execute_input":"2025-04-22T19:00:34.124790Z","iopub.status.idle":"2025-04-22T19:00:34.161058Z","shell.execute_reply.started":"2025-04-22T19:00:34.124763Z","shell.execute_reply":"2025-04-22T19:00:34.160267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"papermill":{"duration":0.009945,"end_time":"2025-04-20T00:38:44.417614","exception":false,"start_time":"2025-04-20T00:38:44.407669","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.162439Z","iopub.execute_input":"2025-04-22T19:00:34.162904Z","iopub.status.idle":"2025-04-22T19:00:34.186595Z","shell.execute_reply.started":"2025-04-22T19:00:34.162886Z","shell.execute_reply":"2025-04-22T19:00:34.185875Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_columns = ['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', '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', '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', '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', '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', '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', 'mean_actualdpd_943P', 'max_annuity_853A', 'mean_annuity_853A', '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', '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_dtlastpmtallstes_3545839D', 'last_employedfrom_700D', 'last_firstnonzeroinstldate_307D', 'max_byoccupationinc_3656910L', 'max_childnum_21L', 'max_pmtnum_8L', 'last_pmtnum_8L', '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_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_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', 'education_88M', 'maritalst_385M', 'maritalst_893M', 'requesttype_4525192L', 'credtype_322L', 'disbursementtype_67L', 'inittransactioncode_186L', 'lastapprcommoditycat_1041M', 'lastcancelreason_561M', 'lastrejectcommoditycat_161M', 'lastrejectcommodtypec_5251769M', 'lastrejectreason_759M', 'lastrejectreasonclient_4145040M', 'lastst_736L', 'opencred_647L', 'paytype1st_925L', 'paytype_783L', 'twobodfilling_608L', '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_credtype_587L', 'max_familystate_726L', 'max_inittransactioncode_279L', 'max_isbidproduct_390L', 'max_status_219L', 'last_credtype_587L', 'last_familystate_726L', 'last_inittransactioncode_279L', 'last_isbidproduct_390L', 'last_status_219L', 'max_classificationofcontr_13M', 'max_classificationofcontr_400M', 'max_contractst_545M', 'max_contractst_964M', 'max_description_351M', 'max_financialinstitution_382M', 'max_financialinstitution_591M', 'max_purposeofcred_426M', 'max_purposeofcred_874M', 'max_subjectrole_182M', 'max_subjectrole_93M', 'last_classificationofcontr_13M', 'last_classificationofcontr_400M', 'last_contractst_545M', 'last_contractst_964M', 'last_description_351M', 'last_financialinstitution_382M', 'last_financialinstitution_591M', 'last_purposeofcred_426M', 'last_purposeofcred_874M', 'last_subjectrole_182M', 'last_subjectrole_93M', 'max_education_927M', 'max_empladdr_district_926M', 'max_empladdr_zipcode_114M', 'max_language1_981M', 'last_education_927M', 'last_empladdr_district_926M', 'last_empladdr_zipcode_114M', '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_642T', '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', 'last_collater_typofvalofguarant_298M', 'last_collater_typofvalofguarant_407M', 'last_collaterals_typeofguarante_359M', 'last_collaterals_typeofguarante_669M', 'last_subjectroles_name_541M', 'last_subjectroles_name_838M', 'max_cacccardblochreas_147M', 'last_cacccardblochreas_147M', 'max_conts_type_509L', 'last_conts_type_509L', 'max_conts_role_79M', 'max_empls_economicalst_849M', 'max_empls_employer_name_740M', 'last_conts_role_79M', 'last_empls_economicalst_849M', 'last_empls_employer_name_740M']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.227097Z","iopub.execute_input":"2025-04-22T19:00:34.227343Z","iopub.status.idle":"2025-04-22T19:00:34.240575Z","shell.execute_reply.started":"2025-04-22T19:00:34.227323Z","shell.execute_reply":"2025-04-22T19:00:34.239899Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pickle\nwith open('/kaggle/input/models/cat_cols.pkl', 'rb') as f:\n    cat_cols = pickle.load(f)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.241725Z","iopub.execute_input":"2025-04-22T19:00:34.241944Z","iopub.status.idle":"2025-04-22T19:00:34.267320Z","shell.execute_reply.started":"2025-04-22T19:00:34.241929Z","shell.execute_reply":"2025-04-22T19:00:34.266691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample = pd.read_csv(\"/kaggle/input/home-credit-credit-risk-model-stability/sample_submission.csv\")\ndevice='gpu'\n","metadata":{"papermill":{"duration":0.029023,"end_time":"2025-04-20T00:42:50.642401","exception":false,"start_time":"2025-04-20T00:42:50.613378","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.268136Z","iopub.execute_input":"2025-04-22T19:00:34.268393Z","iopub.status.idle":"2025-04-22T19:00:34.277978Z","shell.execute_reply.started":"2025-04-22T19:00:34.268355Z","shell.execute_reply":"2025-04-22T19:00:34.277528Z"}},"outputs":[],"execution_count":null},{"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":{"papermill":{"duration":0.525453,"end_time":"2025-04-20T00:42:51.173997","exception":false,"start_time":"2025-04-20T00:42:50.648544","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.279462Z","iopub.execute_input":"2025-04-22T19:00:34.279628Z","iopub.status.idle":"2025-04-22T19:00:34.504423Z","shell.execute_reply.started":"2025-04-22T19:00:34.279615Z","shell.execute_reply":"2025-04-22T19:00:34.503735Z"}},"outputs":[],"execution_count":null},{"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 final_columns if col != \"target\"])\nprint(\"columns:\\t\", len(final_columns))\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":{"papermill":{"duration":0.526967,"end_time":"2025-04-20T00:42:51.705801","exception":false,"start_time":"2025-04-20T00:42:51.178834","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.505022Z","iopub.execute_input":"2025-04-22T19:00:34.505207Z","iopub.status.idle":"2025-04-22T19:00:34.957904Z","shell.execute_reply.started":"2025-04-22T19:00:34.505193Z","shell.execute_reply":"2025-04-22T19:00:34.957188Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{"papermill":{"duration":10.777152,"end_time":"2025-04-20T00:43:03.901518","exception":false,"start_time":"2025-04-20T00:42:53.124366","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.958796Z","iopub.execute_input":"2025-04-22T19:00:34.959064Z","iopub.status.idle":"2025-04-22T19:00:34.980262Z","shell.execute_reply.started":"2025-04-22T19:00:34.959040Z","shell.execute_reply":"2025-04-22T19:00:34.979722Z"}},"outputs":[],"execution_count":null},{"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[:5]]\n        \n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        y_preds += [estimator.predict_proba(X) for estimator in self.estimators[5:]]\n        \n        return np.mean(y_preds, axis=0)\n","metadata":{"papermill":{"duration":0.027734,"end_time":"2025-04-20T10:04:36.718873","exception":false,"start_time":"2025-04-20T10:04:36.691139","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.980811Z","iopub.execute_input":"2025-04-22T19:00:34.980985Z","iopub.status.idle":"2025-04-22T19:00:34.986636Z","shell.execute_reply.started":"2025-04-22T19:00:34.980971Z","shell.execute_reply":"2025-04-22T19:00:34.985932Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import joblib\n\nmodel = joblib.load('/kaggle/input/models/ensemble_model.pkl')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:34.987429Z","iopub.execute_input":"2025-04-22T19:00:34.987693Z","iopub.status.idle":"2025-04-22T19:00:37.289730Z","shell.execute_reply.started":"2025-04-22T19:00:34.987667Z","shell.execute_reply":"2025-04-22T19:00:37.289166Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.estimators[0].feature_names_[289]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:37.293972Z","iopub.execute_input":"2025-04-22T19:00:37.294180Z","iopub.status.idle":"2025-04-22T19:00:37.302637Z","shell.execute_reply.started":"2025-04-22T19:00:37.294164Z","shell.execute_reply":"2025-04-22T19:00:37.301918Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission","metadata":{"papermill":{"duration":0.015781,"end_time":"2025-04-20T10:04:36.751070","exception":false,"start_time":"2025-04-20T10:04:36.735289","status":"completed"},"tags":[]}},{"cell_type":"code","source":"df_test","metadata":{"papermill":{"duration":0.055215,"end_time":"2025-04-20T10:04:36.822365","exception":false,"start_time":"2025-04-20T10:04:36.767150","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:37.304399Z","iopub.execute_input":"2025-04-22T19:00:37.304781Z","iopub.status.idle":"2025-04-22T19:00:37.334557Z","shell.execute_reply.started":"2025-04-22T19:00:37.304765Z","shell.execute_reply":"2025-04-22T19:00:37.333854Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# set(df_test['max_pmts_year_1139T'])\ndf_test[df_test[\"max_pmts_year_1139T\"] == 2020]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:37.335451Z","iopub.execute_input":"2025-04-22T19:00:37.335655Z","iopub.status.idle":"2025-04-22T19:00:37.360274Z","shell.execute_reply.started":"2025-04-22T19:00:37.335640Z","shell.execute_reply":"2025-04-22T19:00:37.359584Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# df_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")\n\ndf_test['score'] = pd.Series(model.predict_proba(df_test.loc[:, df_test.columns != \"WEEK_NUM\"])[:, 1], index=df_test.index)\n\nmask = df_test[\"max_pmts_year_1139T\"] == 2020\ndf_test.loc[mask, 'score'] = (df_test.loc[mask, 'score'] - 0.07).clip(0)\n\nmask = df_test[\"max_pmts_year_1139T\"] == 2021\ndf_test.loc[mask, 'score'] = (df_test.loc[mask, 'score'] - 0.06).clip(0)\n\nmask = df_test[\"max_pmts_year_1139T\"] == 2022\ndf_test.loc[mask, 'score'] = (df_test.loc[mask, 'score'] - 0.02).clip(0)\n\n\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = df_test['score']\n\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"papermill":{"duration":1.104284,"end_time":"2025-04-20T10:04:37.942328","exception":false,"start_time":"2025-04-20T10:04:36.838044","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-04-22T19:00:37.360982Z","iopub.execute_input":"2025-04-22T19:00:37.361254Z","iopub.status.idle":"2025-04-22T19:00:38.044513Z","shell.execute_reply.started":"2025-04-22T19:00:37.361237Z","shell.execute_reply":"2025-04-22T19:00:38.043757Z"}},"outputs":[],"execution_count":null}]}