{"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":"markdown","source":"### Reference\n- {Notebook} [Home Credit Baseline](https://www.kaggle.com/code/greysky/home-credit-baseline)\n- {Notebook} [home-credit-lgb-train](https://www.kaggle.com/code/xiaoleilian/home-credit-lgb-train)\n- {Notebook} [Home Credit Baseline (1/2, Explained, KR)](https://www.kaggle.com/code/sunghoshim/home-credit-baseline-1-2-explained-kr): training 전까지의 코드 설명\n- {Notebook} [home-credit-ensemble-infer(lgb+cat) (Copy)](https://www.kaggle.com/code/sunghoshim/home-credit-ensemble-infer-lgb-cat-copy)","metadata":{}},{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\nfrom tqdm import tqdm_notebook\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nimport datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\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\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-16T09:13:59.080793Z","iopub.execute_input":"2024-04-16T09:13:59.081206Z","iopub.status.idle":"2024-04-16T09:14:05.765986Z","shell.execute_reply.started":"2024-04-16T09:13:59.081159Z","shell.execute_reply":"2024-04-16T09:14:05.764891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1. Prepare Meta Data","metadata":{}},{"cell_type":"code","source":"start_time_utc = datetime.datetime.now()\nprint(f'Notebook Start Time (UTC): {start_time_utc}')\n\nstart_time_kst = start_time_utc + datetime.timedelta(hours=9)\nprint(f\"Notebook Start Time (KST): {start_time_kst}\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Define custom columns\n\n- CUSTOM_AGG_DICT : depth1, depth2 테이블에 대해서, 특정 agg 함수들만 지정해서 쓸거임\n- EXCLUDE_COLS : agg 가기전에 빼버릴 column들","metadata":{}},{"cell_type":"code","source":"CUSTOM_AGG_DICT = {\n    # {discussion} Analysis of birthday: https://www.kaggle.com/competitions/home-credit-credit-risk-model-stability/discussion/476463\n    'birth_259D': {'first'},  # first, max, last 등을 명시\n    \n    # (1) importance 0 : from notebook version #6\n    'purposeofcred_426M': {'max'},  # \"M\" 으로 끝나는 feature 는 max랑 last 로 agg 했는데, last 가 importance 0 이라서 max 만 할 거임\n    'subjectrole_182M': {'max'},\n    'subjectrole_93M': {'max'},\n    'contaddr_matchlist_1032L': {'last'},\n    'collater_typofvalofguarant_298M': {'max'},\n    'collaterals_typeofguarante_359M': {'max'},\n    'collaterals_typeofguarante_669M': {'max'},\n    'subjectroles_name_541M': {'max'},\n    'subjectroles_name_838M': {'max'},\n    'empls_economicalst_849M': {'max'},\n}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EXCLUDE_COLS = {\n    'birthdate_574D',\n    'birthdate_87D',\n    'dateofbirth_337D',\n    'dateofbirth_342D',\n    \n    # (1) importance 0 : from notebook version #6\n    'applicationcnt_361L',\n    'clientscnt_257L',\n    'clientscnt_493L',\n    'deferredmnthsnum_166L',\n    'mastercontrexist_109L',\n    \n    'empladdr_district_926M',  # both last and max (둘 다 importance 0 이니까, 요 컬럼 자체를 빼버리자)\n    'empladdr_zipcode_114M',  # both last and max\n}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1. Prepare Utility Classes","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[-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        print('Pipeline.filter_cols(). Check isnull ratio')\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                    print(f'- drop {col} column. (isnull ratio: {isnull})')\n                    df = df.drop(col)\n        \n        print('\\n\\nPipeline.filter_cols(). Check n_unique count')\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                    print(f'- drop {col} column. (n_unique: {freq})')\n                    df = df.drop(col)\n        \n        return df","metadata":{"execution":{"iopub.status.busy":"2024-04-16T09:14:05.768652Z","iopub.execute_input":"2024-04-16T09:14:05.769347Z","iopub.status.idle":"2024-04-16T09:14:05.779138Z","shell.execute_reply.started":"2024-04-16T09:14:05.769311Z","shell.execute_reply":"2024-04-16T09:14:05.777854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 같은 컴럼에서 나온 feature 들이 뭉쳐 있어야 보기 좋을 것 같기도 해서, 함수 하나로 합침\nclass Aggregator:\n    def get_exprs(df):\n        exprs = []\n        for col in df.columns:\n            # custom aggregations\n            custom_aggs = CUSTOM_AGG_DICT.get(col)\n            if custom_aggs:\n                for custom_agg in custom_aggs:\n                    if custom_agg == 'first':\n                        exprs.append(pl.first(col).alias(f'first_{col}'))\n                    elif custom_agg == 'max':\n                        exprs.append(pl.max(col).alias(f'max_{col}'))\n                    elif custom_agg == 'last':\n                        exprs.append(pl.last(col).alias(f'last_{col}'))\n                    elif custom_agg == 'mean':\n                        exprs.append(pl.mean(col).alias(f'mean_{col}'))\n                    elif custom_agg == 'mode':\n                        exprs.append(pl.mode(col).alias(f'mode_{col}'))\n                    else:\n                        print(f'Unknown custom_agg \"{custom_type}\" for \"{col}\" column')\n                \n            # num_expr\n            elif col[-1] in (\"P\", \"A\"):\n                exprs.append(pl.max(col).alias(f'max_{col}'))\n                exprs.append(pl.last(col).alias(f'last_{col}'))\n                exprs.append(pl.mean(col).alias(f'mean_{col}'))\n                # exprs.append(pl.median(col).alias(f'median_{col}'))\n                # exprs.append(pl.var(col).alias(f'var_{col}'))\n            # date_expr\n            elif col[-1] in (\"D\"):\n                exprs.append(pl.max(col).alias(f'max_{col}'))\n                exprs.append(pl.last(col).alias(f'last_{col}'))\n                exprs.append(pl.mean(col).alias(f'mean_{col}'))\n                # exprs.append(pl.median(col).alias(f'median_{col}'))\n            # str_expr\n            elif col[-1] in (\"M\"):\n                exprs.append(pl.max(col).alias(f'max_{col}'))\n                exprs.append(pl.last(col).alias(f'last_{col}'))\n            # other_expr\n            elif col[-1] in (\"T\", \"L\"):\n                exprs.append(pl.max(col).alias(f'max_{col}'))\n                exprs.append(pl.last(col).alias(f'last_{col}'))\n            # count_expr\n            elif \"num_group\" in col:\n                exprs.append(pl.max(col).alias(f'max_{col}'))\n                exprs.append(pl.last(col).alias(f'last_{col}'))\n            elif col == \"case_id\":\n                continue\n            else:\n                print(f'Unknown colum type!! \"{col}\"')\n                \n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-04-16T09:14:05.781305Z","iopub.execute_input":"2024-04-16T09:14:05.781887Z","iopub.status.idle":"2024-04-16T09:14:05.811582Z","shell.execute_reply.started":"2024-04-16T09:14:05.781843Z","shell.execute_reply":"2024-04-16T09:14:05.810150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_file(path, depth=None):\n    print(f\"- read_file(). {str(path).split('/')[-1]}\")\n    lf = pl.scan_parquet(path)\n    lf = lf.pipe(Pipeline.set_table_dtypes)\n    lf = lf.drop(EXCLUDE_COLS)\n    df = lf.collect()  # agg 하고 난 다음 까지 lazy_frame 으로 들고가면, 메모리가 넘쳐버림\n    if depth in [1,2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df)) \n    return df\n\n\ndef read_files(regex_path, depth=None):\n    print(f\"- read_files(). {str(regex_path).split('/')[-1]}\")\n    chunks = []\n    \n    for path in glob(str(regex_path)):\n        lf = pl.scan_parquet(path)\n        lf = lf.pipe(Pipeline.set_table_dtypes)\n        lf = lf.drop(EXCLUDE_COLS)\n        df = lf.collect()\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","metadata":{},"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    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}\")  # 이름 겹치면 뒤에 suffix\n    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base\n\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","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        if str(col_type)==\"category\":\n            continue\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            continue\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Prepare Datasets","metadata":{}},{"cell_type":"code","source":"%%time\n\nROOT            = Path(ROOT)\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}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = df_train.pipe(Pipeline.filter_cols)\ngc.collect()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.shape","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"len(cat_cols): \", len(cat_cols))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nums=df_train.select_dtypes(exclude='category').columns\nlen(nums)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\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()\nlen(nans_groups)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from itertools import combinations\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    # 计算列之间的相关性\n    correlation_matrix = matrix.corr()\n\n    # 分组列\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    \n    return groups","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"uses=[]\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]\n# df_train.drop(['requesttype_4525192L_cnt','max_empl_employedtotal_800L_cnt', 'max_empl_industry_691L_cnt'], axis=1, inplace=True)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. Train","metadata":{}},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_split = 5\ncv = StratifiedGroupKFold(n_splits=n_split, shuffle=False)\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    \"sample_weight\":'balanced',\n    \"device\": \"gpu\", \n    \"gpu_use_dp\": True,  # https://www.kaggle.com/competitions/home-credit-credit-risk-model-stability/discussion/494257\n    \"verbose\": -1,\n}\n\nfitted_models = []\ncv_scores = []\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#   Because it takes a long time to divide the data set, \n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# each time the data set is divided, two models are trained to each other twice, which saves time.\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\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    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(\"AVG CV AUC score: \", np.mean(cv_scores))\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 4. Check Importance","metadata":{}},{"cell_type":"code","source":"best_idx = np.argmax(cv_scores)\nbest_model = fitted_models[best_idx]\nbest_idx","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model.importance_type = 'gain'\nser = pd.Series(best_model.feature_importances_, index= best_model.feature_name_)\nser_gain_sorted = ser.sort_values(ascending=False).astype(int)\n\ndisplay(ser_gain_sorted.head(20))\n# display(ser_gain_sorted.tail(20))\ngain_zero_cols = ser_gain_sorted[ser_gain_sorted == 0].index\nprint('- gain_zero_cols: ', len(gain_zero_cols))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model.importance_type = 'split'\nser = pd.Series(best_model.feature_importances_, index= best_model.feature_name_)\nser_split_sorted = ser.sort_values(ascending=False).astype(int)\n\ndisplay(ser_split_sorted.head(20))\n# display(ser_split_sorted.tail(20))\nsplit_zero_cols = ser_split_sorted[ser_split_sorted == 0].index\nprint('- split_zero_cols: ', len(split_zero_cols))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"importance_zero_features = set(gain_zero_cols) & set(split_zero_cols)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for col in best_model.feature_name_:\n    if col in importance_zero_features:\n        print(col)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 5. Save Models","metadata":{}},{"cell_type":"code","source":"import joblib\n\njoblib.dump(fitted_models, 'lgb_models.joblib')\n\nnotebook_info = {\n    'notebook_start_time': start_time_kst,\n    'notebook_version': 8,  # Save 누르면 될 버전\n    'description': 'Example notebook',\n    'cols': df_train.columns.to_list(),\n    'cat_cols': cat_cols,\n    'CUSTOM_AGG_DICT': CUSTOM_AGG_DICT,\n    'EXCLUDE_COLS': EXCLUDE_COLS,\n}\njoblib.dump(notebook_info, 'notebook_info.joblib')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -al","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"CV AUC scores: \", cv_scores)\nprint(\"AVG CV AUC score: \", np.mean(cv_scores))\nprint(\"Maximum CV AUC score: \", max(cv_scores))\nprint(f\"avg / max : {round(np.mean(cv_scores), 4)} / {round(max(cv_scores), 4)}\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\n\n여기서 부터는 다른 노트북이라고 가정","metadata":{}},{"cell_type":"markdown","source":"## 10. Load Models","metadata":{}},{"cell_type":"code","source":"lgb_notebook_info = joblib.load('notebook_info.joblib')\nprint(f\"- [lgb] notebook_start_time: {lgb_notebook_info['notebook_start_time']}\")\nprint(f\"- [lgb] description: {lgb_notebook_info['description']}\")\n\ncols = lgb_notebook_info['cols']\ncat_cols = lgb_notebook_info['cat_cols']\nprint(f\"- [lgb] len(cols): {len(cols)}\")\nprint(f\"- [lgb] len(cat_cols): {len(cat_cols)}\")\n\nlgb_models = joblib.load('lgb_models.joblib')\nlgb_models","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CUSTOM_AGG_DICT = lgb_notebook_info['CUSTOM_AGG_DICT']\nCUSTOM_AGG_DICT","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EXCLUDE_COLS = lgb_notebook_info['EXCLUDE_COLS']\nEXCLUDE_COLS","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat_models = []\ncat_models","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 11. Prepare test dataset","metadata":{}},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\ndata_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2)\n    ]\n}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()\n\ndf_test = df_test.select(['case_id'] + cols)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\ndf_test = df_test.set_index('case_id')\nprint(\"test data shape:\\t\", df_test.shape)\n\ngc.collect()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 12. Voting Model","metadata":{}},{"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        MODEL_WEIGHTS = np.array([\n            1, 1, 1, 1, 1, # lgb\n            # 1, 1, 1, 1, 1, # cat\n        ])\n                \n        # lgb\n        X[cat_cols] = X[cat_cols].astype('category')\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]\n        \n        # cat        \n        # X[cat_cols] = X[cat_cols].astype(str)\n        # y_preds += [estimator.predict_proba(X) for estimator in self.estimators[-5:]]\n        \n        return np.average(y_preds, axis=0, weights=MODEL_WEIGHTS)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = VotingModel(lgb_models + cat_models)\nlen(model.estimators)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(model.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{},"execution_count":null,"outputs":[]}]}