{"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":30648,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Note: I'm looking for a job in Europe, if you like my work don't hesitate to reach =)\n\nimport os\nimport gc\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\nimport lightgbm as lgb\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-23T20:39:05.878323Z","iopub.execute_input":"2024-03-23T20:39:05.878900Z","iopub.status.idle":"2024-03-23T20:39:11.029351Z","shell.execute_reply.started":"2024-03-23T20:39:05.878870Z","shell.execute_reply":"2024-03-23T20:39:11.028530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pre-Fitted Voting Model","metadata":{}},{"cell_type":"code","source":"class VotingModel(BaseEstimator, ClassifierMixin):\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)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:39:11.030782Z","iopub.execute_input":"2024-03-23T20:39:11.031088Z","iopub.status.idle":"2024-03-23T20:39:11.038368Z","shell.execute_reply.started":"2024-03-23T20:39:11.031060Z","shell.execute_reply":"2024-03-23T20:39:11.037030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pipeline","metadata":{}},{"cell_type":"code","source":"integer_cols = [\n    \"actualdpdtolerance_344P\",\n    \"amtinstpaidbefduel24m_4187115A\",\n    \"annuity_780A\",\n    \"annuitynextmonth_57A\",\n    \"applicationcnt_361L\",\n    \"applications30d_658L\",\n    \"applicationscnt_1086L\",\n    \"applicationscnt_464L\",\n    \"applicationscnt_629L\",\n    \"applicationscnt_867L\",\n    \"avgdbddpdlast24m_3658932P\",\n    \"avgdbddpdlast3m_4187120P\",\n    \"avgdbdtollast24m_4525197P\",\n    \"avgdpdtolclosure24_3658938P\",\n    \"avginstallast24m_3658937A\",\n    \"avglnamtstart24m_4525187A\",\n    \"avgmaxdpdlast9m_3716943P\",\n    \"avgoutstandbalancel6m_4187114A\",\n    \"avgpmtlast12m_4525200A\",\n    \"clientscnt12m_3712952L\",\n    \"clientscnt3m_3712950L\",\n    \"clientscnt6m_3712949L\",\n    \"clientscnt_100L\",\n    \"clientscnt_1022L\",\n    \"clientscnt_1071L\",\n    \"clientscnt_1130L\",\n    \"clientscnt_136L\",\n    \"clientscnt_157L\",\n    \"clientscnt_257L\",\n    \"clientscnt_304L\",\n    \"clientscnt_360L\",\n    \"clientscnt_493L\",\n    \"clientscnt_533L\",\n    \"clientscnt_887L\",\n    \"clientscnt_946L\",\n    \"cntincpaycont9m_3716944L\",\n    \"cntpmts24_3658933L\",\n    \"commnoinclast6m_3546845L\",\n    \"credamount_770A\",\n    \"currdebt_22A\",\n    \"currdebtcredtyperange_828A\",\n    \"daysoverduetolerancedd_3976961L\",\n    \"deferredmnthsnum_166L\",\n    \"disbursedcredamount_1113A\",\n    \"downpmt_116A\",\n    \"homephncnt_628L\",\n    \"inittransactionamount_650A\",\n    \"interestrategrace_34L\",\n    \"isbidproduct_1095L\",\n    \"isbidproductrequest_292L\",\n    \"isdebitcard_729L\",\n    \"lastapprcredamount_781A\",\n    \"lastdependentsnum_448L\",\n    \"lastotherlnsexpense_631A\",\n    \"lastrejectcredamount_222A\",\n    \"maininc_215A\",\n    \"mastercontrelectronic_519L\",\n    \"mastercontrexist_109L\",\n    \"maxannuity_159A\",\n    \"maxannuity_4075009A\",\n    \"maxdbddpdlast1m_3658939P\",\n    \"maxdbddpdtollast12m_3658940P\",\n    \"maxdbddpdtollast6m_4187119P\",\n    \"maxdebt4_972A\",\n    \"maxdpdfrom6mto36m_3546853P\",\n    \"maxdpdinstlnum_3546846P\",\n    \"maxdpdlast12m_727P\",\n    \"maxdpdlast24m_143P\",\n    \"maxdpdlast3m_392P\",\n    \"maxdpdlast6m_474P\",\n    \"maxdpdlast9m_1059P\",\n    \"maxdpdtolerance_374P\",\n    \"maxinstallast24m_3658928A\",\n    \"maxlnamtstart6m_4525199A\",\n    \"maxoutstandbalancel12m_4187113A\",\n    \"maxpmtlast3m_4525190A\",\n    \"mindbddpdlast24m_3658935P\",\n    \"mindbdtollast24m_4525191P\",\n    \"mobilephncnt_593L\",\n    \"monthsannuity_845L\",\n    \"numactivecreds_622L\",\n    \"numactivecredschannel_414L\",\n    \"numactiverelcontr_750L\",\n    \"numcontrs3months_479L\",\n    \"numincomingpmts_3546848L\",\n    \"numinstlallpaidearly3d_817L\",\n    \"numinstls_657L\",\n    \"numinstlsallpaid_934L\",\n    \"numinstlswithdpd10_728L\",\n    \"numinstlswithdpd5_4187116L\",\n    \"numinstlswithoutdpd_562L\",\n    \"numinstmatpaidtearly2d_4499204L\",\n    \"numinstpaid_4499208L\",\n    \"numinstpaidearly3d_3546850L\",\n    \"numinstpaidearly3dest_4493216L\",\n    \"numinstpaidearly5d_1087L\",\n    \"numinstpaidearly5dest_4493211L\",\n    \"numinstpaidearly5dobd_4499205L\",\n    \"numinstpaidearly_338L\",\n    \"numinstpaidearlyest_4493214L\",\n    \"numinstpaidlastcontr_4325080L\",\n    \"numinstpaidlate1d_3546852L\",\n    \"numinstregularpaid_973L\",\n    \"numinstregularpaidest_4493210L\",\n    \"numinsttopaygr_769L\",\n    \"numinsttopaygrest_4493213L\",\n    \"numinstunpaidmax_3546851L\",\n    \"numinstunpaidmaxest_4493212L\",\n    \"numnotactivated_1143L\",\n    \"numpmtchanneldd_318L\",\n    \"numrejects9m_859L\",\n    \"opencred_647L\",\n    \"pmtnum_254L\",\n    \"posfpd10lastmonth_333P\",\n    \"posfpd30lastmonth_3976960P\",\n    \"posfstqpd30lastmonth_3976962P\",\n    \"price_1097A\",\n    \"sellerplacecnt_915L\",\n    \"sellerplacescnt_216L\",\n    \"sumoutstandtotal_3546847A\",\n    \"sumoutstandtotalest_4493215A\",\n    \"totaldebt_9A\",\n    \"totalsettled_863A\",\n    \"totinstallast1m_4525188A\",\n    \"contractssum_5085716L\",\n    \"days120_123L\",\n    \"days180_256L\",\n    \"days30_165L\",\n    \"days360_512L\",\n    \"days90_310L\",\n    \"firstquarter_103L\",\n    \"for3years_128L\",\n    \"for3years_504L\",\n    \"for3years_584L\",\n    \"formonth_118L\",\n    \"formonth_206L\",\n    \"formonth_535L\",\n    \"forquarter_1017L\",\n    \"forquarter_462L\",\n    \"forquarter_634L\",\n    \"fortoday_1092L\",\n    \"forweek_1077L\",\n    \"forweek_528L\",\n    \"forweek_601L\",\n    \"foryear_618L\",\n    \"foryear_818L\",\n    \"foryear_850L\",\n    \"fourthquarter_440L\",\n    \"numberofqueries_373L\",\n    \"pmtaverage_3A\",\n    \"pmtaverage_4527227A\",\n    \"pmtaverage_4955615A\",\n    \"pmtcount_4527229L\",\n    \"pmtcount_4955617L\",\n    \"pmtcount_693L\",\n    \"pmtscount_423L\",\n    \"pmtssum_45A\",\n    \"secondquarter_766L\",\n    \"thirdquarter_1082L\",\n]\n\nclass Pipeline:\n    @staticmethod\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.Int32))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col in integer_cols:\n                df = df.with_columns(pl.col(col).cast(pl.Int32))\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            \n        return df\n    \n    @staticmethod\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())\n                df = df.with_columns(pl.col(col).cast(pl.Float32))\n                \n        df = df.drop(\"date_decision\", \"MONTH\")\n\n        return df\n    \n    @staticmethod\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\n#                 if isnull > 0.99:\n                if isnull == 1.:\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\n                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n\n        return df","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:52:37.988153Z","iopub.execute_input":"2024-03-23T20:52:37.989032Z","iopub.status.idle":"2024-03-23T20:52:38.012480Z","shell.execute_reply.started":"2024-03-23T20:52:37.988988Z","shell.execute_reply":"2024-03-23T20:52:38.011460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Automatic Aggregation","metadata":{}},{"cell_type":"code","source":"not_num_types = [pl.String, pl.Boolean, pl.Null]\n\nclass Aggregator:\n    @staticmethod\n    def num_expr_max(df):\n        cols = [col for col in df.columns if (col[-1] in (\"P\", \"A\", \"T\", \"L\")) & (df[col].dtype not in not_num_types)]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\n\n    @staticmethod\n    def num_expr_avg(df):\n        cols = [col for col in df.columns if (col[-1] in (\"P\", \"A\", \"T\", \"L\")) & (df[col].dtype not in not_num_types)]\n        expr_max = [pl.mean(col).alias(f\"avg_{col}\") for col in cols]\n        return expr_max\n\n    @staticmethod\n    def num_expr_range(df):\n        cols = [col for col in df.columns if (col[-1] in (\"P\", \"A\", \"T\", \"L\")) & (df[col].dtype not in not_num_types)]\n        expr_max = [(pl.max(col)-pl.min(col)).alias(f\"range_{col}\") for col in cols]\n        return expr_max\n\n    @staticmethod\n    def num_expr_std(df):\n        cols = [col for col in df.columns if (col[-1] in (\"P\", \"A\", \"T\", \"L\")) & (df[col].dtype not in not_num_types)]\n        expr_max = [pl.std(col).alias(f\"std_{col}\") for col in cols]\n        return expr_max\n    \n    \n    @staticmethod\n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\",)]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\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    @staticmethod\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def get_exprs(df):\n#         exprs = Aggregator.num_expr(df) + \\\n#         exprs = Aggregator.num_expr_avg(df) + Aggregator.num_expr_std(df) + \\\n#                 Aggregator.num_expr_max(df) + Aggregator.num_expr_range(df) + \\\n        exprs = Aggregator.num_expr_avg(df) + Aggregator.num_expr_std(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.count_expr(df)\n#                 Aggregator.other_expr(df) + \\\n#                 Aggregator.count_expr(df)\n\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:01:59.055678Z","iopub.execute_input":"2024-03-23T21:01:59.056574Z","iopub.status.idle":"2024-03-23T21:01:59.073979Z","shell.execute_reply.started":"2024-03-23T21:01:59.056538Z","shell.execute_reply":"2024-03-23T21:01:59.072838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### File I/O","metadata":{}},{"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    \n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    \n    return df\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.set_table_dtypes)\n        \n        if depth in [1, 2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        \n        chunks.append(df)\n        \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:43:18.961753Z","iopub.execute_input":"2024-03-23T20:43:18.962124Z","iopub.status.idle":"2024-03-23T20:43:18.969740Z","shell.execute_reply.started":"2024-03-23T20:43:18.962095Z","shell.execute_reply":"2024-03-23T20:43:18.968797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Engineering","metadata":{}},{"cell_type":"code","source":"def reduce_memory_usage_pl(df):\n    \"\"\" Reduce memory usage by polars dataframe {df} with name {name} by changing its data types.\n        Original pandas version of this function: https://www.kaggle.com/code/arjanso/reducing-dataframe-memory-size-by-65 \"\"\"\n    print(f\"Memory usage of dataframe is {round(df.estimated_size('mb'), 2)} MB\")\n    Numeric_Int_types = [pl.Int8,pl.Int16,pl.Int32,pl.Int64]\n    Numeric_Float_types = [pl.Float32,pl.Float64]    \n    for col in df.columns:\n        if col == 'case_id': continue\n        try:\n            col_type = df[col].dtype\n            if col_type == pl.Categorical:\n                continue\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if col_type in Numeric_Int_types:\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df = df.with_columns(df[col].cast(pl.Int8))\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df = df.with_columns(df[col].cast(pl.Int16))\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df = df.with_columns(df[col].cast(pl.Int32))\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df = df.with_columns(df[col].cast(pl.Int64))\n            elif col_type in Numeric_Float_types:\n                if c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df = df.with_columns(df[col].cast(pl.Float32))\n                else:\n                    pass\n            # elif col_type == pl.Utf8:\n            #     df = df.with_columns(df[col].cast(pl.Categorical))\n            else:\n                pass\n        except:\n            pass\n    print(f\"Memory usage of dataframe became {round(df.estimated_size('mb'), 2)} MB\")\n    return df\n\n\ndef feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = reduce_memory_usage_pl(df_base)\n    depth_0 = [reduce_memory_usage_pl(df0) for df0 in depth_0]\n    depth_1 = [reduce_memory_usage_pl(df1) for df1 in depth_1]\n    depth_2 = [reduce_memory_usage_pl(df2) for df2 in depth_2]\n    \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        \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        \n    df_base = df_base.pipe(Pipeline.handle_dates)\n    \n    return df_base","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:47:46.106234Z","iopub.execute_input":"2024-03-23T20:47:46.106886Z","iopub.status.idle":"2024-03-23T20:47:46.121561Z","shell.execute_reply.started":"2024-03-23T20:47:46.106854Z","shell.execute_reply":"2024-03-23T20:47:46.120597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_pandas(df_data, cat_cols=None):\n    df_data = reduce_memory_usage_pl(df_data).to_pandas()\n    \n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    \n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    \n    return df_data, cat_cols","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:47:47.409280Z","iopub.execute_input":"2024-03-23T20:47:47.409674Z","iopub.status.idle":"2024-03-23T20:47:47.415888Z","shell.execute_reply.started":"2024-03-23T20:47:47.409643Z","shell.execute_reply":"2024-03-23T20:47:47.414951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Configuration","metadata":{}},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:47:48.403836Z","iopub.execute_input":"2024-03-23T20:47:48.404207Z","iopub.status.idle":"2024-03-23T20:47:48.408812Z","shell.execute_reply.started":"2024-03-23T20:47:48.404178Z","shell.execute_reply":"2024-03-23T20:47:48.407791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train Files Read & Feature Engineering","metadata":{}},{"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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:43:21.332647Z","iopub.execute_input":"2024-03-23T20:43:21.333008Z","iopub.status.idle":"2024-03-23T20:46:04.476336Z","shell.execute_reply.started":"2024-03-23T20:43:21.332975Z","shell.execute_reply":"2024-03-23T20:46:04.475424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\n\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T20:47:56.004906Z","iopub.execute_input":"2024-03-23T20:47:56.005547Z","iopub.status.idle":"2024-03-23T20:48:18.670561Z","shell.execute_reply.started":"2024-03-23T20:47:56.005516Z","shell.execute_reply":"2024-03-23T20:48:18.669487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Test Files Read & Feature Engineering","metadata":{}},{"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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:02:06.914386Z","iopub.execute_input":"2024-03-23T21:02:06.914819Z","iopub.status.idle":"2024-03-23T21:02:07.269695Z","shell.execute_reply.started":"2024-03-23T21:02:06.914783Z","shell.execute_reply":"2024-03-23T21:02:07.268780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\n\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:02:25.509846Z","iopub.execute_input":"2024-03-23T21:02:25.510241Z","iopub.status.idle":"2024-03-23T21:02:25.625137Z","shell.execute_reply.started":"2024-03-23T21:02:25.510200Z","shell.execute_reply":"2024-03-23T21:02:25.624223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Elimination","metadata":{}},{"cell_type":"code","source":"df_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-23T21:02:31.548588Z","iopub.execute_input":"2024-03-23T21:02:31.549241Z","iopub.status.idle":"2024-03-23T21:02:34.994934Z","shell.execute_reply.started":"2024-03-23T21:02:31.549210Z","shell.execute_reply":"2024-03-23T21:02:34.994013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pandas Conversion","metadata":{}},{"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-23T21:02:42.112086Z","iopub.execute_input":"2024-03-23T21:02:42.112792Z","iopub.status.idle":"2024-03-23T21:02:57.961953Z","shell.execute_reply.started":"2024-03-23T21:02:42.112754Z","shell.execute_reply":"2024-03-23T21:02:57.961061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Garbage Collection","metadata":{}},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:02:57.963500Z","iopub.execute_input":"2024-03-23T21:02:57.963780Z","iopub.status.idle":"2024-03-23T21:02:58.936962Z","shell.execute_reply.started":"2024-03-23T21:02:57.963756Z","shell.execute_reply":"2024-03-23T21:02:58.935868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### EDA","metadata":{}},{"cell_type":"code","source":"print(\"Train is duplicated:\\t\", df_train[\"case_id\"].duplicated().any())\nprint(\"Train Week Range:\\t\", (df_train[\"WEEK_NUM\"].min(), df_train[\"WEEK_NUM\"].max()))\n\nprint()\n\nprint(\"Test is duplicated:\\t\", df_test[\"case_id\"].duplicated().any())\nprint(\"Test Week Range:\\t\", (df_test[\"WEEK_NUM\"].min(), df_test[\"WEEK_NUM\"].max()))","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:02:58.938049Z","iopub.execute_input":"2024-03-23T21:02:58.938358Z","iopub.status.idle":"2024-03-23T21:02:58.968725Z","shell.execute_reply.started":"2024-03-23T21:02:58.938332Z","shell.execute_reply":"2024-03-23T21:02:58.967887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.lineplot(\n    data=df_train,\n    x=\"WEEK_NUM\",\n    y=\"target\",\n)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:02:58.971062Z","iopub.execute_input":"2024-03-23T21:02:58.971693Z","iopub.status.idle":"2024-03-23T21:03:15.443766Z","shell.execute_reply.started":"2024-03-23T21:02:58.971657Z","shell.execute_reply":"2024-03-23T21:03:15.442876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"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\": -1,\n    \"num_leaves\": 50,\n    \"learning_rate\": 0.005,\n    \"n_estimators\": 5000,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"n_jobs\": -1,\n    \"device\": \"gpu\",\n}\n\nfitted_models = []\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(100), lgb.early_stopping(100)]\n    )\n\n    fitted_models.append(model)\n\nmodel = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:03:15.444921Z","iopub.execute_input":"2024-03-23T21:03:15.445194Z","iopub.status.idle":"2024-03-23T21:19:43.552590Z","shell.execute_reply.started":"2024-03-23T21:03:15.445170Z","shell.execute_reply":"2024-03-23T21:19:43.551049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction","metadata":{}},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\n\ny_pred = pd.Series(model.predict_proba(X_test)[:, 1], index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:19:43.553599Z","iopub.status.idle":"2024-03-23T21:19:43.554181Z","shell.execute_reply.started":"2024-03-23T21:19:43.553826Z","shell.execute_reply":"2024-03-23T21:19:43.553847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submission","metadata":{}},{"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\"] = y_pred","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:19:43.555664Z","iopub.status.idle":"2024-03-23T21:19:43.555970Z","shell.execute_reply.started":"2024-03-23T21:19:43.555819Z","shell.execute_reply":"2024-03-23T21:19:43.555832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Check null: \", df_subm[\"score\"].isnull().any())\n\ndf_subm.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:19:43.557962Z","iopub.status.idle":"2024-03-23T21:19:43.558326Z","shell.execute_reply.started":"2024-03-23T21:19:43.558168Z","shell.execute_reply":"2024-03-23T21:19:43.558182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-23T21:19:43.559623Z","iopub.status.idle":"2024-03-23T21:19:43.560336Z","shell.execute_reply.started":"2024-03-23T21:19:43.560059Z","shell.execute_reply":"2024-03-23T21:19:43.560080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}