{"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":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\n\nclass 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\n\nROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\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}\n\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ngc.collect()\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\nnums=df_train.select_dtypes(exclude='category').columns\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    # Compute the correlation between columns\n    correlation_matrix = matrix.corr()\n\n    # Group columns\n    groups = []\n    remaining_cols = list(matrix.columns)\n    while remaining_cols:\n        col = remaining_cols.pop(0)\n        group = [col]\n        for remaining_col in remaining_cols[:]:\n            if abs(correlation_matrix[col][remaining_col]) > threshold:\n                group.append(remaining_col)\n                remaining_cols.remove(remaining_col)\n        groups.append(group)\n\n    return groups\n\ndef select_columns_by_group_correlation(groups, threshold=0.8):\n    selected_cols = []\n    for group in groups:\n        selected_cols.append(group[0])\n\n    return selected_cols\n\ncorrelation_groups = group_columns_by_correlation(df_train[nums])\nprint('correlation_groups',len(correlation_groups))\nfor group in correlation_groups:\n    print(group)\n    \nuse = reduce_group(correlation_groups)\nprint('Select these',use)\ngc.collect()\n\nimport scipy.stats as ss\ndef normalize(df, cols):\n    for col in cols:\n        df[col] = ss.rankdata(df[col])/df[col].shape[0]\n    return df\n#df_train = normalize(df_train, use)\n\nprint('correlation_groups',len(correlation_groups))\nfor group in correlation_groups:\n    print(group)\n    \n\ndef lightgbm_weeks(train, target, test, cat_cols, num_cols, params, folds, num_rounds=2000, verbose_eval=500):\n    oof_preds = np.zeros(train.shape[0])\n    sub_preds = np.zeros(test.shape[0])\n    \n    feature_importance_df = pd.DataFrame()\n    \n    for n_fold, (trn_idx, val_idx) in enumerate(folds.split(train, target)):\n        trn_x, trn_y = train.iloc[trn_idx], target.iloc[trn_idx]\n        val_x, val_y = train.iloc[val_idx], target.iloc[val_idx]\n        \n        trn_data = lgb.Dataset(trn_x, label=trn_y, categorical_feature=cat_cols, feature_name=num_cols)\n        val_data = lgb.Dataset(val_x, label=val_y, categorical_feature=cat_cols, feature_name=num_cols)\n        \n        clf = lgb.train(params, trn_data, num_rounds, valid_sets=[trn_data, val_data], verbose_eval=verbose_eval, early_stopping_rounds=200)\n        \n        oof_preds[val_idx] = clf.predict(val_x, num_iteration=clf.best_iteration)\n        sub_preds += clf.predict(test, num_iteration=clf.best_iteration) / folds.n_splits\n        \n        fold_importance_df = pd.DataFrame()\n        fold_importance_df[\"Feature\"] = num_cols\n        fold_importance_df[\"importance\"] = clf.feature_importance(importance_type=\"gain\")\n        fold_importance_df[\"fold\"] = n_fold + 1\n        feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n        \n        print('Fold %2d AUC : %.6f' % (n_fold + 1, roc_auc_score(val_y, oof_preds[val_idx])))\n        del trn_x, trn_y, val_x, val_y, trn_data, val_data\n        gc.collect()\n        \n    print('Full AUC score %.6f' % roc_auc_score(target, oof_preds))\n    \n    return oof_preds, sub_preds, feature_importance_df\n\ndef lightgbm_feature_importance(train, target, cat_cols, num_cols, params, folds, num_rounds=2000, verbose_eval=500):\n    oof_preds = np.zeros(train.shape[0])\n    feature_importance_df = pd.DataFrame()\n    \n    for n_fold, (trn_idx, val_idx) in enumerate(folds.split(train, target)):\n        trn_x, trn_y = train.iloc[trn_idx], target.iloc[trn_idx]\n        val_x, val_y = train.iloc[val_idx], target.iloc[val_idx]\n        \n        trn_data = lgb.Dataset(trn_x, label=trn_y, categorical_feature=cat_cols, feature_name=num_cols)\n        val_data = lgb.Dataset(val_x, label=val_y, categorical_feature=cat_cols, feature_name=num_cols)\n        \n        clf = lgb.train(params, trn_data, num_rounds, valid_sets=[trn_data, val_data], verbose_eval=verbose_eval, early_stopping_rounds=200)\n        \n        oof_preds[val_idx] = clf.predict(val_x, num_iteration=clf.best_iteration)\n        \n        fold_importance_df = pd.DataFrame()\n        fold_importance_df[\"Feature\"] = num_cols\n        fold_importance_df[\"importance\"] = clf.feature_importance(importance_type=\"gain\")\n        fold_importance_df[\"fold\"] = n_fold + 1\n        feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n        \n        print('Fold %2d AUC : %.6f' % (n_fold + 1, roc_auc_score(val_y, oof_preds[val_idx])))\n        del trn_x, trn_y, val_x, val_y, trn_data, val_data\n        gc.collect()\n        \n    print('Full AUC score %.6f' % roc_auc_score(target, oof_preds))\n    \n    return feature_importance_df\n\n# Aggregates columns from different sources\n# Parameters\n# ----------\n# df: DataFrame\n#     The dataframe from which to aggregate columns\n# source_mapping: dict\n#     A dictionary that maps the target column to a list of source columns\n# postfix: str, optional (default='')\n#     The postfix to append to the target column\n# drop_source: bool, optional (default=False)\n#     Whether to drop the source columns or not\n# Returns\n# -------\n# DataFrame\n#     A DataFrame containing the aggregated columns\ndef aggregate_columns(df, source_mapping, postfix='', drop_source=False):\n    aggr_df = pd.DataFrame()\n    \n    for target, sources in source_mapping.items():\n        target_col = df[sources[0]].copy() # To preserve index\n        \n        for src in sources[1:]:\n            target_col = target_col.combine_first(df[src])\n        \n        target_col.name = target + postfix\n        aggr_df = pd.concat([aggr_df, target_col], axis=1)\n        \n        if drop_source:\n            df = df.drop(columns=sources)\n        \n    return aggr_df\n\ndef create_agg_cols(df, depth):\n    # Column mappings\n    source_mapping = {\n        'max_AMT_CREDIT_SUM': [\n            'max_credit_bureau_{}_{}'.format(x, depth) for x in ['A', 'B']\n        ],\n        'max_AMT_CREDIT_SUM_DEBT': [\n            'max_credit_bureau_{}_{}'.format(x, depth) for x in ['A', 'B']\n        ],\n        'max_AMT_ANNUITY': [\n            'max_applprev_{}'.format(depth)\n        ],\n        'last_NUM_INSTALMENT_VERSION': [\n            'last_applprev_{}'.format(depth)\n        ]\n    }\n    \n    # Aggregate columns\n    agg_df = aggregate_columns(df, source_mapping, postfix='_agg', drop_source=True)\n    return agg_df\n\ndef preprocess_data(df):\n    df = df.copy()\n    df = create_agg_cols(df, '2')\n    \n    # Handle missing values\n    for col in df.columns:\n        if df[col].dtype.name == 'category':\n            df[col] = df[col].fillna(df[col].mode().values[0])\n        else:\n            df[col] = df[col].fillna(df[col].median())\n    \n    return df\n\ndef merge_embeddings(df, emb_df):\n    merged_df = df.merge(emb_df, how='left', left_on='case_id', right_on='case_id_emb')\n    merged_df = merged_df.drop(columns=['case_id_emb'])\n    \n    return merged_df\n\nclass Model(BaseEstimator, RegressorMixin):\n    def __init__(self, lgb_params):\n        self.lgb_params = lgb_params\n        self.estimators_ = []\n        \n    def fit(self, X, y, num_rounds=2000, verbose_eval=500, folds=None):\n        self.feature_importance_ = pd.DataFrame()\n        \n        oof_preds = np.zeros(X.shape[0])\n        sub_preds = np.zeros(test_df.shape[0])\n        \n        if folds is None:\n            folds = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)\n        \n        for n_fold, (trn_idx, val_idx) in enumerate(folds.split(X, y, groups=X['WEEK_NUM'])):\n            trn_x, trn_y = X.iloc[trn_idx], y.iloc[trn_idx]\n            val_x, val_y = X.iloc[val_idx], y.iloc[val_idx]\n\n            trn_data = lgb.Dataset(trn_x, label=trn_y, categorical_feature=cat_cols)\n            val_data = lgb.Dataset(val_x, label=val_y, categorical_feature=cat_cols)\n            \n            clf = lgb.train(self.lgb_params, trn_data, num_rounds, valid_sets=[trn_data, val_data], verbose_eval=verbose_eval, early_stopping_rounds=200)\n\n            oof_preds[val_idx] = clf.predict(val_x, num_iteration=clf.best_iteration)\n            sub_preds += clf.predict(test_df, num_iteration=clf.best_iteration) / folds.n_splits\n\n            fold_importance_df = pd.DataFrame()\n            fold_importance_df[\"Feature\"] = clf.feature_name()\n            fold_importance_df[\"importance\"] = clf.feature_importance(importance_type=\"gain\")\n            fold_importance_df[\"fold\"] = n_fold + 1\n            self.feature_importance_ = pd.concat([self.feature_importance_, fold_importance_df], axis=0)\n            \n            self.estimators_.append(clf)\n            \n            print('Fold %2d AUC : %.6f' % (n_fold + 1, roc_auc_score(val_y, oof_preds[val_idx])))\n            \n        print('Full AUC score %.6f' % roc_auc_score(y, oof_preds))\n        \n        return self\n\n    def predict(self, X):\n        predictions = np.zeros(X.shape[0])\n        \n        for estimator in self.estimators_:\n            predictions += estimator.predict(X) / len(self.estimators_)\n        \n        return predictions\n\ndef train_lgbm(train_df, target_df, test_df, lgb_params, folds, cat_cols, num_rounds=2000, verbose_eval=500):\n    feature_importance_df = pd.DataFrame()\n    oof_preds = np.zeros(train_df.shape[0])\n    sub_preds = np.zeros(test_df.shape[0])\n    \n    for n_fold, (trn_idx, val_idx) in enumerate(folds.split(train_df, target_df)):\n        trn_x, trn_y = train_df.iloc[trn_idx], target_df.iloc[trn_idx]\n        val_x, val_y = train_df.iloc[val_idx], target_df.iloc[val_idx]\n        \n        trn_data = lgb.Dataset(trn_x, label=trn_y, categorical_feature=cat_cols)\n        val_data = lgb.Dataset(val_x, label=val_y, categorical_feature=cat_cols)\n        \n        clf = lgb.train(lgb_params, trn_data, num_rounds, valid_sets=[trn_data, val_data], verbose_eval=verbose_eval, early_stopping_rounds=200)\n        \n        oof_preds[val_idx] = clf.predict(val_x, num_iteration=clf.best_iteration)\n        sub_preds += clf.predict(test_df, num_iteration=clf.best_iteration) / folds.n_splits\n        \n        fold_importance_df = pd.DataFrame()\n        fold_importance_df[\"Feature\"] = train_df.columns\n        fold_importance_df[\"importance\"] = clf.feature_importance(importance_type=\"gain\")\n        fold_importance_df[\"fold\"] = n_fold + 1\n        feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n        \n        print('Fold %2d AUC : %.6f' % (n_fold + 1, roc_auc_score(val_y, oof_preds[val_idx])))\n        \n    print('Full AUC score %.6f' % roc_auc_score(target_df, oof_preds))\n    \n    return sub_preds, feature_importance_df\n\n# Optimized LGBM parameters\nlgb_params = {\n    'boosting_type': 'gbdt',\n    'objective': 'binary',\n    'metric': 'auc',\n    'n_estimators': 5000,\n    'learning_rate': 0.01,\n    'subsample': 0.7,\n    'subsample_freq': 1,\n    'colsample_bytree': 0.6,\n    'reg_alpha': 1,\n    'reg_lambda': 1,\n    'min_split_gain': 0.01,\n    'min_child_weight': 10,\n    'random_state': 42,\n    'verbose': -1,\n    'n_jobs': -1,\n    'early_stopping_rounds': 200\n}\n\nfolds = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)\n\ntrain_df = df_train.copy()\ntarget_df = train_df.pop('target')\n\noof_preds, sub_preds, feature_importance_df = train_lgbm(train_df, target_df, test_df, lgb_params, folds, cat_cols)\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:25:10.378698Z","iopub.execute_input":"2024-05-03T13:25:10.379147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}