{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30664,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"%load_ext autoreload\n%autoreload 2","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:05:51.509440Z","iopub.execute_input":"2024-03-17T15:05:51.509784Z","iopub.status.idle":"2024-03-17T15:05:51.539671Z","shell.execute_reply.started":"2024-03-17T15:05:51.509755Z","shell.execute_reply":"2024-03-17T15:05:51.538919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport os\nimport gc\nfrom datetime import datetime\n\nfrom glob import glob\nfrom pathlib import Path\nimport polars as pl\n\nfrom tqdm.notebook import tqdm","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:05:51.541430Z","iopub.execute_input":"2024-03-17T15:05:51.541763Z","iopub.status.idle":"2024-03-17T15:05:52.186904Z","shell.execute_reply.started":"2024-03-17T15:05:51.541733Z","shell.execute_reply":"2024-03-17T15:05:52.186079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Dataset aggregation","metadata":{}},{"cell_type":"code","source":"class 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[-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.95:\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-17T15:05:52.187919Z","iopub.execute_input":"2024-03-17T15:05:52.188290Z","iopub.status.idle":"2024-03-17T15:05:52.219020Z","shell.execute_reply.started":"2024-03-17T15:05:52.188265Z","shell.execute_reply":"2024-03-17T15:05:52.218178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Aggregator:\n    @staticmethod\n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\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 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        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\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                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:05:52.220983Z","iopub.execute_input":"2024-03-17T15:05:52.221277Z","iopub.status.idle":"2024-03-17T15:05:52.249339Z","shell.execute_reply.started":"2024-03-17T15:05:52.221255Z","shell.execute_reply":"2024-03-17T15:05:52.248515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    \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-17T15:05:52.250490Z","iopub.execute_input":"2024-03-17T15:05:52.250717Z","iopub.status.idle":"2024-03-17T15:05:52.275924Z","shell.execute_reply.started":"2024-03-17T15:05:52.250698Z","shell.execute_reply":"2024-03-17T15:05:52.275084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n        \n    for i, df in tqdm(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-17T15:05:52.277088Z","iopub.execute_input":"2024-03-17T15:05:52.277410Z","iopub.status.idle":"2024-03-17T15:05:52.299650Z","shell.execute_reply.started":"2024-03-17T15:05:52.277388Z","shell.execute_reply":"2024-03-17T15:05:52.298857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    \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-17T15:05:52.300595Z","iopub.execute_input":"2024-03-17T15:05:52.300837Z","iopub.status.idle":"2024-03-17T15:05:52.322301Z","shell.execute_reply.started":"2024-03-17T15:05:52.300815Z","shell.execute_reply":"2024-03-17T15:05:52.321576Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-17T15:05:52.323446Z","iopub.execute_input":"2024-03-17T15:05:52.324080Z","iopub.status.idle":"2024-03-17T15:05:52.344548Z","shell.execute_reply.started":"2024-03-17T15:05:52.324027Z","shell.execute_reply":"2024-03-17T15:05:52.343840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train_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-17T15:05:52.345583Z","iopub.execute_input":"2024-03-17T15:05:52.345887Z","iopub.status.idle":"2024-03-17T15:07:58.969435Z","shell.execute_reply.started":"2024-03-17T15:05:52.345858Z","shell.execute_reply":"2024-03-17T15:07:58.968612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_train_store)\n\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:07:58.973911Z","iopub.execute_input":"2024-03-17T15:07:58.974261Z","iopub.status.idle":"2024-03-17T15:08:08.544675Z","shell.execute_reply.started":"2024-03-17T15:07:58.974236Z","shell.execute_reply":"2024-03-17T15:08:08.543774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.sample(10)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:08.545739Z","iopub.execute_input":"2024-03-17T15:08:08.545999Z","iopub.status.idle":"2024-03-17T15:08:08.597337Z","shell.execute_reply.started":"2024-03-17T15:08:08.545975Z","shell.execute_reply":"2024-03-17T15:08:08.596450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_test_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-17T15:08:08.598345Z","iopub.execute_input":"2024-03-17T15:08:08.598607Z","iopub.status.idle":"2024-03-17T15:08:08.956720Z","shell.execute_reply.started":"2024-03-17T15:08:08.598582Z","shell.execute_reply":"2024-03-17T15:08:08.955786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_test_store)\n\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:08.957911Z","iopub.execute_input":"2024-03-17T15:08:08.958217Z","iopub.status.idle":"2024-03-17T15:08:09.035491Z","shell.execute_reply.started":"2024-03-17T15:08:08.958192Z","shell.execute_reply":"2024-03-17T15:08:09.034606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-17T15:08:09.036553Z","iopub.execute_input":"2024-03-17T15:08:09.036813Z","iopub.status.idle":"2024-03-17T15:08:11.888028Z","shell.execute_reply.started":"2024-03-17T15:08:09.036790Z","shell.execute_reply":"2024-03-17T15:08:11.887106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:11.889137Z","iopub.execute_input":"2024-03-17T15:08:11.889430Z","iopub.status.idle":"2024-03-17T15:08:32.685651Z","shell.execute_reply.started":"2024-03-17T15:08:11.889406Z","shell.execute_reply":"2024-03-17T15:08:32.684830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_train_store\ndel data_test_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:32.686804Z","iopub.execute_input":"2024-03-17T15:08:32.687096Z","iopub.status.idle":"2024-03-17T15:08:33.085787Z","shell.execute_reply.started":"2024-03-17T15:08:32.687067Z","shell.execute_reply":"2024-03-17T15:08:33.084827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Dataset aggregation above is taken from https://www.kaggle.com/code/greysky/home-credit-baseline","metadata":{}},{"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-17T15:08:33.086727Z","iopub.execute_input":"2024-03-17T15:08:33.087010Z","iopub.status.idle":"2024-03-17T15:08:33.131277Z","shell.execute_reply.started":"2024-03-17T15:08:33.086988Z","shell.execute_reply":"2024-03-17T15:08:33.130378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features = pd.read_csv(ROOT / 'feature_definitions.csv')","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:33.132324Z","iopub.execute_input":"2024-03-17T15:08:33.132594Z","iopub.status.idle":"2024-03-17T15:08:33.163646Z","shell.execute_reply.started":"2024-03-17T15:08:33.132571Z","shell.execute_reply":"2024-03-17T15:08:33.162644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nan_values = pd.DataFrame(df_train.isna().sum()[df_train.isna().sum() != 0]).reset_index().rename(columns={'index': 'Variable', 0: 'NaNs'})\nnan_values","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:33.164799Z","iopub.execute_input":"2024-03-17T15:08:33.165154Z","iopub.status.idle":"2024-03-17T15:08:34.635624Z","shell.execute_reply.started":"2024-03-17T15:08:33.165122Z","shell.execute_reply":"2024-03-17T15:08:34.634761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"A lot of NaNs above.","metadata":{}},{"cell_type":"code","source":"features_nans = pd.merge(features, nan_values, on=['Variable'])\nfeatures_nans.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:34.636833Z","iopub.execute_input":"2024-03-17T15:08:34.637204Z","iopub.status.idle":"2024-03-17T15:08:34.674818Z","shell.execute_reply.started":"2024-03-17T15:08:34.637172Z","shell.execute_reply":"2024-03-17T15:08:34.673753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# I've done a lot of research for different features and below refine function is defined,\n# where some feature transformations implemented. I've deleted parts where i research lots\n# features, because notebook becomes a little bit too messy\n\n# Also have to say, that these transformations improved model's overall quality to 56.6\n\ndef refine(df):\n    df['clientscnt'] = df[df.columns[df.columns.str.startswith('clientscnt_')]].sum(1)\n    df.drop(columns=list(df.columns[df.columns.str.startswith('clientscnt_')]))\n    \n    df.drop(columns=list(df.columns[df.columns.str.startswith('assignmentdate_')]))\n    df.drop(columns=['education_1103M'])\n    df.drop(columns=['maritalst_893M'])\n    df.drop(columns=['responsedate_4527233D'])\n    df.drop(columns=['responsedate_1012D'])\n    df.drop(columns=['assignmentdate_4527235D'], inplace=True, errors='ignore')\n    \n    df['pmtaverage'] = df[df.columns[df.columns.str.startswith('pmtaverage_')]].mean(1)\n    df.drop(columns=list(df.columns[df.columns.str.startswith('pmtaverage_')]))\n    \n    df['pmtcount'] = df[df.columns[df.columns.str.startswith('pmtcount_')]].mean(1)\n    df.drop(columns=list(df.columns[df.columns.str.startswith('pmtcount_')]))\n    \n    df['clientscnt'] = df[df.columns[df.columns.str.startswith('clientscnt_')]].sum(1)\n    df.drop(columns=list(df.columns[df.columns.str.startswith('clientscnt_')]))\n\n#     df.loc[df['equalitydataagreement_891L'].isna(), 'equalitydataagreement_891L'] = False\n\ndef remove_low_valuable_features(df):\n    low_valuable_features = [\n        'applicationcnt_361L',\n         'clientscnt_100L',\n         'commnoinclast6m_3546845L',\n         'deferredmnthsnum_166L',\n         'education_88M',\n         'equalitydataagreement_891L',\n         'isdebitcard_729L',\n         'lastrejectcommodtypec_5251769M',\n         'maritalst_893M',\n         'mastercontrelectronic_519L',\n         'mastercontrexist_109L',\n         'max_collater_typofvalofguarant_298M',\n         'max_collater_typofvalofguarant_407M',\n         'max_collaterals_typeofguarante_359M',\n         'max_collaterals_typeofguarante_669M',\n         'max_contaddr_matchlist_1032L',\n         'max_contractst_545M',\n         'max_credacc_status_367L',\n         'max_credtype_587L',\n         'max_education_927M',\n         'max_empladdr_district_926M',\n         'max_empladdr_zipcode_114M',\n         'max_housetype_905L',\n         'max_num_group1_10',\n         'max_num_group1_11',\n         'max_outstandingamount_354A',\n         'max_overdueamount_31A',\n         'max_personindex_1023L',\n         'max_persontype_1072L',\n         'max_persontype_792L',\n         'max_pmts_month_158T',\n         'max_pmts_month_706T',\n         'max_purposeofcred_426M',\n         'max_purposeofcred_874M',\n         'max_rejectreasonclient_4145042M',\n         'max_remitter_829L',\n         'max_residualamount_488A',\n         'max_role_1084L',\n         'max_safeguarantyflag_411L',\n         'max_subjectrole_182M',\n         'max_subjectrole_93M',\n         'max_subjectroles_name_541M',\n         'max_subjectroles_name_838M',\n         'max_totaloutstanddebtvalue_668A',\n         'max_type_25L',\n         'numactivecreds_622L',\n         'numactivecredschannel_414L',\n         'numactiverelcontr_750L',\n         'numnotactivated_1143L',\n         'numpmtchanneldd_318L',\n         'opencred_647L',\n         'paytype1st_925L',\n         'paytype_783L',\n         'pmtcount_4527229L',\n         'sellerplacecnt_915L'\n    ]\n    df.drop(columns=low_valuable_features, inplace=True, errors='ignore')","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:42:01.427420Z","iopub.execute_input":"2024-03-17T15:42:01.428342Z","iopub.status.idle":"2024-03-17T15:42:01.479621Z","shell.execute_reply.started":"2024-03-17T15:42:01.428310Z","shell.execute_reply":"2024-03-17T15:42:01.478724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"refine(df_train)\nrefine(df_test)\n\n# I've tried to do feature removal, it makes quality significantly worse\n# remove_low_valuable_features(df_train)\n# remove_low_valuable_features(df_test)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:42:01.914536Z","iopub.execute_input":"2024-03-17T15:42:01.914884Z","iopub.status.idle":"2024-03-17T15:42:16.219521Z","shell.execute_reply.started":"2024-03-17T15:42:01.914859Z","shell.execute_reply":"2024-03-17T15:42:16.218695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features_nans.sort_values('NaNs', ascending=False).head(20)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:17:06.939713Z","iopub.execute_input":"2024-03-17T15:17:06.940397Z","iopub.status.idle":"2024-03-17T15:17:06.972015Z","shell.execute_reply.started":"2024-03-17T15:17:06.940365Z","shell.execute_reply":"2024-03-17T15:17:06.971065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features_nans[features_nans['NaNs'] < 10000]","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:17:07.118848Z","iopub.execute_input":"2024-03-17T15:17:07.119174Z","iopub.status.idle":"2024-03-17T15:17:07.147236Z","shell.execute_reply.started":"2024-03-17T15:17:07.119148Z","shell.execute_reply":"2024-03-17T15:17:07.146312Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.loc[df_train['annuitynextmonth_57A'].isna(), ['annuitynextmonth_57A', 'annuity_780A']]","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:17:07.277178Z","iopub.execute_input":"2024-03-17T15:17:07.277706Z","iopub.status.idle":"2024-03-17T15:17:07.314942Z","shell.execute_reply.started":"2024-03-17T15:17:07.277676Z","shell.execute_reply":"2024-03-17T15:17:07.314045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[['annuitynextmonth_57A', 'annuity_780A']].sample(20)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:17:07.454541Z","iopub.execute_input":"2024-03-17T15:17:07.454798Z","iopub.status.idle":"2024-03-17T15:17:07.527639Z","shell.execute_reply.started":"2024-03-17T15:17:07.454777Z","shell.execute_reply":"2024-03-17T15:17:07.526723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, ClassifierMixin","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:17:08.072813Z","iopub.execute_input":"2024-03-17T15:17:08.073475Z","iopub.status.idle":"2024-03-17T15:17:08.750829Z","shell.execute_reply.started":"2024-03-17T15:17:08.073441Z","shell.execute_reply":"2024-03-17T15:17:08.749861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-17T15:17:08.754610Z","iopub.execute_input":"2024-03-17T15:17:08.755375Z","iopub.status.idle":"2024-03-17T15:17:08.785568Z","shell.execute_reply.started":"2024-03-17T15:17:08.755349Z","shell.execute_reply":"2024-03-17T15:17:08.784656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"cell_type":"code","source":"import lightgbm as lgb","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:17:09.097301Z","iopub.execute_input":"2024-03-17T15:17:09.097608Z","iopub.status.idle":"2024-03-17T15:17:12.889267Z","shell.execute_reply.started":"2024-03-17T15:17:09.097585Z","shell.execute_reply":"2024-03-17T15:17:12.888488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\ndef objective(trial, data=X, target=y):\n    params = {\n        \"boosting_type\": \"gbdt\",\n        \"objective\": \"binary\",\n        \"metric\": \"auc\",\n        \"max_depth\": trial.suggest_int('max_depth', 2, 12), # 8,\n        \"learning_rate\": trial.suggest_float('learning_rate', 1e-3, 10.0), #0.05,\n        \"reg_alpha\": trial.suggest_float('reg_alpha', 1e-3, 10.0),\n        \"reg_lambda\": trial.suggest_float('reg_lambda', 1e-3, 10.0),\n        \"n_estimators\": trial.suggest_int('n_estimators', 500, 1500),# 1000,\n        \"colsample_bytree\": trial.suggest_categorical('colsample_bytree', [0.6,0.7,0.75,0.8,0.85, 0.9, 1.0]), #0.8, \n        \"colsample_bynode\": trial.suggest_categorical('colsample_bynode', [0.6,0.7,0.75,0.8,0.85, 0.9, 1.0]), # 0.8,\n        \"verbose\": -1,\n        \"random_state\": 42,\n        \"device\": \"gpu\",\n    }\n    \n    rmse = 0\n\n    for idx_train, idx_valid in cv.split(data, target, groups=weeks):\n        X_train, y_train = data.iloc[idx_train], target.iloc[idx_train]\n        X_valid, y_valid = data.iloc[idx_valid], target.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        preds = model.predict(X_valid)\n        rmse += mean_squared_error(y_valid, preds,squared=False)\n    \n    return rmse","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### DO NOT RUN! WAS USED TO HYPERPARAM OPTIMIZING (EXTREMELY SLOW)\n\n# study = optuna.create_study(direction='minimize')\n# study.optimize(objective, n_trials=10)\n# print('Number of finished trials:', len(study.trials))\n# print('Best trial:', study.best_trial.params)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.05,\n    \"n_estimators\": 1000,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\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-17T15:17:12.890864Z","iopub.execute_input":"2024-03-17T15:17:12.891160Z","iopub.status.idle":"2024-03-17T15:34:36.493058Z","shell.execute_reply.started":"2024-03-17T15:17:12.891135Z","shell.execute_reply":"2024-03-17T15:34:36.492000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's have a look at features importance:","metadata":{}},{"cell_type":"markdown","source":"### Submition","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-17T15:08:48.322576Z","iopub.status.idle":"2024-03-17T15:08:48.322911Z","shell.execute_reply.started":"2024-03-17T15:08:48.322758Z","shell.execute_reply":"2024-03-17T15:08:48.322771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:48.323867Z","iopub.status.idle":"2024-03-17T15:08:48.324200Z","shell.execute_reply.started":"2024-03-17T15:08:48.324012Z","shell.execute_reply":"2024-03-17T15:08:48.324025Z"},"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-17T15:08:48.324973Z","iopub.status.idle":"2024-03-17T15:08:48.325318Z","shell.execute_reply.started":"2024-03-17T15:08:48.325162Z","shell.execute_reply":"2024-03-17T15:08:48.325176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-17T15:08:48.327338Z","iopub.status.idle":"2024-03-17T15:08:48.327673Z","shell.execute_reply.started":"2024-03-17T15:08:48.327509Z","shell.execute_reply":"2024-03-17T15:08:48.327523Z"},"trusted":true},"execution_count":null,"outputs":[]}]}