{"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":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Reference \n(LGB + Cat ensemble) +Stacking https://www.kaggle.com/code/harrychan123/lgb-cat-ensemble-stacking","metadata":{}},{"cell_type":"markdown","source":"# Let's get to work!","metadata":{}},{"cell_type":"markdown","source":"## Imports ","metadata":{}},{"cell_type":"code","source":"import gc \ndef report_gpu(): \n    print(torch.cuda.list_gpu_processes()) \n    gc.collect() \n    torch.cuda.empty_cache()","metadata":{"execution":{"iopub.status.busy":"2024-04-27T16:33:42.452559Z","iopub.execute_input":"2024-04-27T16:33:42.453675Z","iopub.status.idle":"2024-04-27T16:33:42.461406Z","shell.execute_reply.started":"2024-04-27T16:33:42.453630Z","shell.execute_reply":"2024-04-27T16:33:42.460366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"report_gpu","metadata":{"execution":{"iopub.status.busy":"2024-04-27T16:34:05.700537Z","iopub.execute_input":"2024-04-27T16:34:05.701156Z","iopub.status.idle":"2024-04-27T16:34:05.707604Z","shell.execute_reply.started":"2024-04-27T16:34:05.701126Z","shell.execute_reply":"2024-04-27T16:34:05.706598Z"},"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\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\n\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import KNNImputer\nfrom sklearn.preprocessing import OrdinalEncoder","metadata":{"_uuid":"6d51fb38-3f61-48b9-a8be-f4928616260c","_cell_guid":"3ed5829e-7666-462e-abcc-a5492ae4fcec","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:27.207502Z","iopub.execute_input":"2024-04-27T10:56:27.209072Z","iopub.status.idle":"2024-04-27T10:56:32.448456Z","shell.execute_reply.started":"2024-04-27T10:56:27.209013Z","shell.execute_reply":"2024-04-27T10:56:32.447251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"## Processing functions","metadata":{}},{"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.endswith(\"D\"):\n                    # Calculate the difference in days between each date column and date_decision\n                    df = df.with_columns(\n                        (pl.col(\"date_decision\") - pl.col(col)).dt.total_days().alias(col)\n                    )\n                    df = df.with_columns(pl.col(col).fill_null(np.nan)) \n        # Drop date_decision column\n        df = df.drop(\"date_decision\")\n\n        return df\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\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_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n\n        return 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        \n        return expr_max \n\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        # expr_min = [pl.min(col).alias(f\"min_{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\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        return expr_max\n\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return expr_max \n    \n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs\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    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    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.set_table_dtypes)\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        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                try:\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                except:\n                    continue\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":{"_uuid":"d341d4b9-d40b-4520-b1d2-e00e21e1e7a0","_cell_guid":"f918ffff-f322-4e08-9468-2f841260c4d4","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:32.451051Z","iopub.execute_input":"2024-04-27T10:56:32.452108Z","iopub.status.idle":"2024-04-27T10:56:32.506184Z","shell.execute_reply.started":"2024-04-27T10:56:32.452065Z","shell.execute_reply":"2024-04-27T10:56:32.505153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Little Testing","metadata":{}},{"cell_type":"markdown","source":"## Train data","metadata":{}},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"_uuid":"dffa0116-9b3c-4aa5-bfda-c6de1d75fcf1","_cell_guid":"dd049f8a-eff3-4308-a5ed-6bf1630dc9d1","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:32.507826Z","iopub.execute_input":"2024-04-27T10:56:32.508620Z","iopub.status.idle":"2024-04-27T10:56:32.529634Z","shell.execute_reply.started":"2024-04-27T10:56:32.508580Z","shell.execute_reply":"2024-04-27T10:56:32.528485Z"},"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":{"_uuid":"329b6c89-aef4-4e8b-b4ce-eca792d4c22a","_cell_guid":"dbeaee46-7f54-4be9-9249-05a9c5b98ff7","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:32.532650Z","iopub.execute_input":"2024-04-27T10:56:32.532983Z","iopub.status.idle":"2024-04-27T10:56:56.532376Z","shell.execute_reply.started":"2024-04-27T10:56:32.532956Z","shell.execute_reply":"2024-04-27T10:56:56.528451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Processing data","metadata":{}},{"cell_type":"code","source":"\ndf_train = feature_eng(**data_store) # import train data \nprint(\"train data shape:\\t\", df_train.shape)\n# gc.collect()\n# spamming gc.collect praying for memory to not full\ngc.collect()\ndf_train = df_train.pipe(Pipeline.filter_cols) # fillter column\ngc.collect()\ndf_train, cat_cols = to_pandas(df_train) # tranform to pandas dataframe, easier to work with\ngc.collect()\ndf_train = reduce_mem_usage(df_train) # as the name said\ngc.collect()\nprint(\"train data shape:\\t\", df_train.shape)\nnums=df_train.select_dtypes(exclude='category').columns\n# IDK what is going on for now\nfrom itertools import combinations, permutations\n#df_train=df_train[nums]\nnans_df = df_train[nums].isna()\nnans_groups={}\nfor 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]\ndel nans_df; x=gc.collect()\n\ndef 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\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    correlation_matrix = matrix.corr()\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    return groups\n\nuses=[]\nfor 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)\nprint(uses)\nprint(len(uses))\nuses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train=df_train[uses]","metadata":{"_uuid":"d6d05875-9880-41f6-9c96-6d0a6d4fb3dc","_cell_guid":"72ab5d13-1bd8-4422-a0c8-aeddb6f24d37","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.533615Z","iopub.status.idle":"2024-04-27T10:56:56.534061Z","shell.execute_reply.started":"2024-04-27T10:56:56.533851Z","shell.execute_reply":"2024-04-27T10:56:56.533868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Feature Selection","metadata":{"_uuid":"f8086977-546a-4fa9-86dc-8ea3c4dc394b","_cell_guid":"3152a026-8de2-4579-b700-ca9eb55dc1d7","trusted":true}},{"cell_type":"code","source":"df_train","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.535121Z","iopub.status.idle":"2024-04-27T10:56:56.535523Z","shell.execute_reply.started":"2024-04-27T10:56:56.535330Z","shell.execute_reply":"2024-04-27T10:56:56.535347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)","metadata":{"_uuid":"cb387be5-14c2-42be-bb37-002eafca6bb4","_cell_guid":"59206b02-5b58-4d76-a7af-7df80da2b4dc","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.537296Z","iopub.status.idle":"2024-04-27T10:56:56.537672Z","shell.execute_reply.started":"2024-04-27T10:56:56.537487Z","shell.execute_reply":"2024-04-27T10:56:56.537503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Applying OrdinalEncoder to handle catagory columns","metadata":{}},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)\nimport polars as pl\nfrom sklearn.preprocessing import OrdinalEncoder\n\n\n# Fit Ordinal Encoder on Training Data\nencoder = OrdinalEncoder(handle_unknown=\"use_encoded_value\", unknown_value=np.nan)\nencoder.fit(df_train[cat_cols])\n\n# Transform Training Data\ndf_train[cat_cols] = encoder.transform(df_train[cat_cols])\ndf_train[cat_cols] = df_train[cat_cols].fillna(-1)\ndf_train[cat_cols] = df_train[cat_cols].astype(int)\n","metadata":{"_uuid":"f807b9d4-4071-40e4-a043-6a4928333812","_cell_guid":"5fce529d-7cf0-4925-9e43-7bd858705094","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.539310Z","iopub.status.idle":"2024-04-27T10:56:56.540270Z","shell.execute_reply.started":"2024-04-27T10:56:56.540046Z","shell.execute_reply":"2024-04-27T10:56:56.540065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Setting up parameters","metadata":{}},{"cell_type":"code","source":"\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,  \n    \"learning_rate\": 0.05,\n    \"n_estimators\": 2000,  \n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    'num_leaves':64,\n    \"device\": \"gpu\", \n    \"verbose\": -1,\n}\n\n\n# rf_params = {\n#     \"n_estimators\": 100,  # Number of trees in the forest\n#     \"criterion\": \"gini\",  # Criteria for splitting: either \"gini\" or \"entropy\"\n#     \"max_depth\": None,  # Maximum depth of the tree. None means unlimited depth.\n#     \"min_samples_split\": 2,  # Minimum number of samples required to split an internal node\n#     \"min_samples_leaf\": 1,  # Minimum number of samples required to be at a leaf node\n#     \"max_features\": \"auto\",  # Number of features to consider when looking for the best split\n#     \"bootstrap\": True,  # Whether bootstrap samples are used when building trees\n#     \"random_state\": 42,  # Seed for random number generator\n#     \"n_jobs\": -1,  # Number of jobs to run in parallel (-1 means using all processors)\n#     \"verbose\": 0,  # Controls the verbosity when fitting and predicting\n# }","metadata":{"_uuid":"6904e6de-80d6-47cf-baf3-78dce2c7c672","_cell_guid":"33472c64-261e-40c7-9275-b266fec0005e","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.541473Z","iopub.status.idle":"2024-04-27T10:56:56.542136Z","shell.execute_reply.started":"2024-04-27T10:56:56.541938Z","shell.execute_reply":"2024-04-27T10:56:56.541956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_train.to_csv('df_train.csv')","metadata":{"_uuid":"5c56ee3f-5e38-4cfa-bb60-a9a6b674c7b2","_cell_guid":"359aa0f4-9070-4fb3-9e67-4ffd79d72940","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.543376Z","iopub.status.idle":"2024-04-27T10:56:56.544029Z","shell.execute_reply.started":"2024-04-27T10:56:56.543814Z","shell.execute_reply":"2024-04-27T10:56:56.543832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fitted_models = []\ncv_scores = []\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    \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    fitted_models.append(model)\n    \n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n    \nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"_uuid":"13c97864-af48-48f5-b86d-823b812e715b","_cell_guid":"8fb6d171-ef22-4758-a922-1d245dd868e3","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.548937Z","iopub.status.idle":"2024-04-27T10:56:56.549492Z","shell.execute_reply.started":"2024-04-27T10:56:56.549309Z","shell.execute_reply":"2024-04-27T10:56:56.549325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.model_selection import StratifiedGroupKFold\nimport numpy as np\n\n# Initialize confusion matrix and classification report variables\nconf_matrix = None\nclass_report = None\n\n# Predict labels for validation data\ny_pred_labels = model.predict(X_valid)\n\n# Compute confusion matrix\nconf_matrix = confusion_matrix(y_valid, y_pred_labels)\n\n# Compute classification report\nclass_report = classification_report(y_valid, y_pred_labels)\n\n# Print confusion matrix and classification report\nprint(\"Confusion Matrix:\")\nprint(conf_matrix)\nprint(\"\\nClassification Report:\")\nprint(class_report)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.550342Z","iopub.status.idle":"2024-04-27T10:56:56.551092Z","shell.execute_reply.started":"2024-04-27T10:56:56.550895Z","shell.execute_reply":"2024-04-27T10:56:56.550913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models)","metadata":{"_uuid":"d925f610-48b8-4881-a9bc-31175330236b","_cell_guid":"3d29ac20-ddc5-4fde-8d3f-397e084a7128","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.552220Z","iopub.status.idle":"2024-04-27T10:56:56.553072Z","shell.execute_reply.started":"2024-04-27T10:56:56.552767Z","shell.execute_reply":"2024-04-27T10:56:56.552794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb.plot_importance(fitted_models[2], importance_type=\"split\", figsize=(10,50))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.554559Z","iopub.status.idle":"2024-04-27T10:56:56.555084Z","shell.execute_reply.started":"2024-04-27T10:56:56.554813Z","shell.execute_reply":"2024-04-27T10:56:56.554835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features = X_train.columns\nimportances = fitted_models[2].feature_importances_\nfeature_importance = pd.DataFrame({'importance':importances,'features':features}).sort_values('importance', ascending=False).reset_index(drop=True)\nfeature_importance","metadata":{"_uuid":"ceaf47bc-beea-4afc-95d7-926597207afa","_cell_guid":"4ffb439d-fec1-4fa8-8e78-78e5410b9820","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.556594Z","iopub.status.idle":"2024-04-27T10:56:56.556991Z","shell.execute_reply.started":"2024-04-27T10:56:56.556769Z","shell.execute_reply":"2024-04-27T10:56:56.556785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"drop_list = []\nfor i, f in feature_importance.iterrows():\n    if f['importance']<80:\n        drop_list.append(f['features'])\nprint(f\"Number of features which are not important: {len(drop_list)} \")","metadata":{"_uuid":"28653c29-b897-49f9-be65-2316b290a375","_cell_guid":"18c3e571-f69c-425f-b38f-175f8eeed92f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.558476Z","iopub.status.idle":"2024-04-27T10:56:56.558841Z","shell.execute_reply.started":"2024-04-27T10:56:56.558663Z","shell.execute_reply":"2024-04-27T10:56:56.558678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(drop_list)","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.560892Z","iopub.status.idle":"2024-04-27T10:56:56.561872Z","shell.execute_reply.started":"2024-04-27T10:56:56.561560Z","shell.execute_reply":"2024-04-27T10:56:56.561584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submision","metadata":{"_uuid":"6b20c95b-3c8e-4e4d-ac39-83c906ddb800","_cell_guid":"51de17d9-9a23-4b29-82a2-a371f4de5c29","trusted":true}},{"cell_type":"code","source":"data_store_test = {\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-04-27T10:56:56.563088Z","iopub.status.idle":"2024-04-27T10:56:56.563455Z","shell.execute_reply.started":"2024-04-27T10:56:56.563280Z","shell.execute_reply":"2024-04-27T10:56:56.563295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store_test)\nprint(\"test data shape:\\t\", df_test.shape)\nprint(df_test[\"case_id\"])\ngc.collect()\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"] + ['case_id'])\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = df_test.set_index(\"case_id\")\ndf_test = reduce_mem_usage(df_test)\ndf_test[cat_cols] = df_test[cat_cols].astype(str)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.565417Z","iopub.status.idle":"2024-04-27T10:56:56.565769Z","shell.execute_reply.started":"2024-04-27T10:56:56.565596Z","shell.execute_reply":"2024-04-27T10:56:56.565611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.567300Z","iopub.status.idle":"2024-04-27T10:56:56.567650Z","shell.execute_reply.started":"2024-04-27T10:56:56.567479Z","shell.execute_reply":"2024-04-27T10:56:56.567493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Transform Test Data using the same encoder instance to ensure consistency\ndf_test[cat_cols] = encoder.transform(df_test[cat_cols])\ndf_test[cat_cols] = df_test[cat_cols].fillna(-1)\ndf_test[cat_cols] = df_test[cat_cols].astype(int)","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.568747Z","iopub.status.idle":"2024-04-27T10:56:56.569146Z","shell.execute_reply.started":"2024-04-27T10:56:56.568963Z","shell.execute_reply":"2024-04-27T10:56:56.568979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nlgb_pred = pd.Series(model.predict_proba(df_test)[:, 1],index=df_test.index)","metadata":{"_uuid":"aae72955-bc1d-4996-ad1a-d460e704b62a","_cell_guid":"d640ca44-5285-4c49-b88c-4134dd299c73","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-27T10:56:56.570428Z","iopub.status.idle":"2024-04-27T10:56:56.570793Z","shell.execute_reply.started":"2024-04-27T10:56:56.570602Z","shell.execute_reply":"2024-04-27T10:56:56.570616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb_pred ","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.573131Z","iopub.status.idle":"2024-04-27T10:56:56.573675Z","shell.execute_reply.started":"2024-04-27T10:56:56.573408Z","shell.execute_reply":"2024-04-27T10:56:56.573430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = lgb_pred","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.575015Z","iopub.status.idle":"2024-04-27T10:56:56.575561Z","shell.execute_reply.started":"2024-04-27T10:56:56.575292Z","shell.execute_reply":"2024-04-27T10:56:56.575314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv('submission.csv')\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-04-27T10:56:56.577074Z","iopub.status.idle":"2024-04-27T10:56:56.577659Z","shell.execute_reply.started":"2024-04-27T10:56:56.577351Z","shell.execute_reply":"2024-04-27T10:56:56.577374Z"},"trusted":true},"execution_count":null,"outputs":[]}]}