{"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"},{"sourceId":8467057,"sourceType":"datasetVersion","datasetId":5048143}],"dockerImageVersionId":30698,"isInternetEnabled":false,"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\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\nfrom itertools import combinations, permutations\n\nfrom catboost import CatBoostClassifier, Pool\nimport xgboost as xgb\n\n#ROOT = '/kaggle/input/home-credit-credit-risk-model-stability'\nROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\nINPUT           = '/kaggle/input/20240426g'\n\nDELETE_LIST = ['dpdmaxdatemonth_442T', 'dpdmaxdatemonth_89T', \\\n    'dpdmaxdateyear_596T', 'dpdmaxdateyear_896T', 'financialinstitution_382M', \\\n    'financialinstitution_591M', 'overdueamountmaxdatemonth_284T', \\\n    'overdueamountmaxdatemonth_365T', 'overdueamountmaxdateyear_2T', \\\n    'overdueamountmaxdateyear_994T', 'credor_3940957M', 'dpdmaxdatemonth_804T',\\\n    'dpdmaxdateyear_742T', 'overdueamountmaxdatemonth_494T', \\\n    'overdueamountmaxdateyear_432T', 'empladdr_zipcode_114M', \\\n    'registaddr_zipcode_184M', 'name_4527232M', 'name_4917606M', \\\n    'employername_160M', 'pmts_month_158T', 'pmts_month_706T',\\\n    'pmts_year_1139T', 'subjectroles_name_541M', 'subjectroles_name_838M',\\\n    'addres_zip_823M', 'empls_employer_name_740M','pmts_year_507T',\\\n    'firstquarter_103L','secondquarter_766L',\\\n    'thirdquarter_1082L','fourthquarter_440L']\n#DELETE_LIST = []\nLT_TO_M = ['bankacctype_710L', 'cardtype_51L', 'credtype_322L', \\\n    'disbursementtype_67L', 'equalitydataagreement_891L', 'equalityempfrom_62L',\\\n    'inittransactioncode_186L', 'isbidproduct_1095L', 'isbidproductrequest_292L',\\\n    'isdebitcard_729L', 'lastst_736L', 'mastercontrelectronic_519L', \\\n    'mastercontrexist_109L', 'paytype_783L', 'paytype1st_925L', \\\n    'twobodfilling_608L', 'typesuite_864L', 'requesttype_4525192L', \\\n    'credacc_status_367L', 'credtype_587L', 'familystate_726L', \\\n    'inittransactioncode_279L', 'isbidproduct_390L', 'isdebitcard_527L', \\\n    'status_219L', 'contaddr_matchlist_1032L', 'contaddr_smempladdr_334L', \\\n    'empl_industry_691L', 'familystate_447L', 'gender_992L', 'housetype_905L', \\\n    'housingtype_772L', 'incometype_1044T', 'isreference_387L', 'maritalst_703L',\\\n    'personindex_1023L', 'persontype_1072L', 'persontype_792L', \\\n    'relationshiptoclient_415T', 'relationshiptoclient_642T', 'remitter_829L',\\\n    'role_1084L', 'role_993L', 'safeguarantyflag_411L', 'sex_738L', 'type_25L',\\\n    'conts_type_509L', 'credacc_cards_status_52L', 'addres_role_871L',\\\n    'relatedpersons_role_762T','riskassesment_302T','periodicityofpmts_997L',\\\n    'empl_employedtotal_800L']","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:22.601120Z","iopub.execute_input":"2024-05-20T13:18:22.601727Z","iopub.status.idle":"2024-05-20T13:18:25.010946Z","shell.execute_reply.started":"2024-05-20T13:18:22.601676Z","shell.execute_reply":"2024-05-20T13:18:25.009729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 预处理","metadata":{}},{"cell_type":"code","source":"class Pipeline:\n    \n    def set_table_dtypes(df,path,depth):\n        # 额外加上去掉某些列\n        for col in df.columns:\n            if col in DELETE_LIST:\n                df = df.drop(col)\n        # 修改某些列的后缀 [ T L ]\n        for col in df.columns:\n            if col in LT_TO_M:\n                if col=='periodicityofpmts_997L':\n                    df = df.rename({col: 'periodicityofpmts_998M'})\n                elif col[-1]=='L':df = df.rename({col: col.replace('L','M')})\n                else:df = df.rename({col: col.replace('T','M')})\n        # 自定义某几列\n        if 'applprev_1' in str(path):\n            df = df.with_columns(\n                (pl.col('currdebt_94A')/pl.col('mainoccupationinc_437A'))\\\n                   .alias('crdbt_94_mnocpt_437A'),\n                (pl.col('downpmt_134A')/pl.col('mainoccupationinc_437A'))\\\n                   .alias('dnpmt_134_mnocpt_437A'),\n                (pl.col('outstandingdebt_522A')/pl.col('mainoccupationinc_437A'))\\\n                   .alias('otstnddbt_522_mnocpt_437A')\n            )\n        if 'other_1' in str(path):\n            df = df.with_columns(\n    (pl.col('amtdebitincoming_4809443A')-pl.col('amtdebitoutgoing_4809440A'))\\\n       .alias('amtdbtin_4809443_amtdbtout_4809440A'),\n    (pl.col('amtdepositincoming_4809444A')-pl.col('amtdepositoutgoing_4809442A'))\\\n       .alias('amtdpstin_4809444_amtdpstout_4809442A')\n            )\n        # 数据类型调整\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\", \"L\", \"T\"):\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())\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.95:\n                    df = df.drop(col)\n                    #print('isnull>0.7:',col)\n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) \\\n               & (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n                    #print('freq=1or>50:',col)\n        # 缺失值处理 🎃\n        num_cols = df.select(\"^*A$\").columns\n        for col in num_cols:\n            df = df.with_columns(pl.col(col).fill_null(0))\n        encoding_cols = df.select(\\\n            pl.selectors.by_dtype([pl.String, pl.Boolean, pl.Categorical])).columns\n        for col in encoding_cols:\n            df = df.with_columns(pl.col(col).fill_null('Missing'))\n        return df","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:25.013050Z","iopub.execute_input":"2024-05-20T13:18:25.013654Z","iopub.status.idle":"2024-05-20T13:18:25.039182Z","shell.execute_reply.started":"2024-05-20T13:18:25.013617Z","shell.execute_reply":"2024-05-20T13:18:25.037793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 聚合","metadata":{}},{"cell_type":"code","source":"class Aggregator:\n    def num_expr(df,path,depth):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\", \"L\", \"T\")]\n        expr_max = [pl.max(col).alias(f\"max_{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        expr_var = [pl.var(col).alias(f\"var_{col}\") for col in cols]\n        return expr_max + expr_last + expr_mean + expr_var\n    \n    def date_expr(df,path,depth):\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_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,path,depth):\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_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,path,depth):\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_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        return  expr_max + expr_count\n    \n    def get_exprs(df,path,depth):\n        exprs = Aggregator.num_expr(df,path,depth) + \\\n                Aggregator.date_expr(df,path,depth) + \\\n                Aggregator.str_expr(df,path,depth) + \\\n                Aggregator.count_expr(df,path,depth)\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:25.041086Z","iopub.execute_input":"2024-05-20T13:18:25.041442Z","iopub.status.idle":"2024-05-20T13:18:25.060201Z","shell.execute_reply.started":"2024-05-20T13:18:25.041414Z","shell.execute_reply":"2024-05-20T13:18:25.058879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 其他预处理","metadata":{}},{"cell_type":"code","source":"def read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes,path=path,depth=depth)\n    if depth == 1:\n        df = df.sort(['case_id','num_group1'], descending=[False,False]) \n    elif depth == 2:\n        df = df.sort(['case_id','num_group1','num_group2'], descending=[False,False,False]) \n    \n    if depth in [1,2]:\n        if 'person_1' in str(path):\n            df = df.filter(pl.col('num_group1')==0)\n        else:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df,path,depth))\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,path=path,depth=depth)\n        if depth == 1:\n            df = df.sort(['case_id','num_group1'], descending=[False,False]) \n        elif depth == 2:\n            df = df.sort(['case_id','num_group1','num_group2'], descending=[False,False,False]) \n        \n        if depth in [1,2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df,path,depth))\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.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                    #+ ['month_decision', 'weekday_decision'] #❗❗❗\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","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:25.063098Z","iopub.execute_input":"2024-05-20T13:18:25.063448Z","iopub.status.idle":"2024-05-20T13:18:25.091009Z","shell.execute_reply.started":"2024-05-20T13:18:25.063420Z","shell.execute_reply":"2024-05-20T13:18:25.090012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 读数据","metadata":{}},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        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-05-20T13:18:25.092325Z","iopub.execute_input":"2024-05-20T13:18:25.092870Z","iopub.status.idle":"2024-05-20T13:18:25.404120Z","shell.execute_reply.started":"2024-05-20T13:18:25.092840Z","shell.execute_reply":"2024-05-20T13:18:25.402778Z"},"trusted":true},"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()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:25.405621Z","iopub.execute_input":"2024-05-20T13:18:25.406009Z","iopub.status.idle":"2024-05-20T13:18:25.629201Z","shell.execute_reply.started":"2024-05-20T13:18:25.405972Z","shell.execute_reply":"2024-05-20T13:18:25.628012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"uses = pd.read_csv(INPUT+'/'+'use.csv')['use'].tolist()\ncat_cols = pd.read_csv(INPUT+'/'+'cat.csv')['cat'].tolist()\n\ndf_test = df_test.select([col for col in uses if col != \"target\"])\nprint(\"test data shape:\\t\", df_test.shape)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\n#cat_cols = cat_cols + ['month_decision', 'weekday_decision']\ndf_test = reduce_mem_usage(df_test)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:25.631010Z","iopub.execute_input":"2024-05-20T13:18:25.631720Z","iopub.status.idle":"2024-05-20T13:18:26.040169Z","shell.execute_reply.started":"2024-05-20T13:18:25.631678Z","shell.execute_reply":"2024-05-20T13:18:26.038796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 预测","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_cb(self, X):\n        X[cat_cols] = X[cat_cols].astype(str)\n        X = Pool(X, cat_features=cat_cols)\n        #y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        y_preds = [estimator.predict_proba(X,\n                        ntree_end=estimator.get_best_iteration())\\\n                   for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)[:,1]\n    \n    def predict_lgb(self, X):\n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        #y_preds = [estimator.predict(X) for estimator in self.estimators]\n        y_preds = [estimator.predict(X,num_iteration=estimator.best_iteration)\\\n                   for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_xgb(self, X):\n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        X.replace([np.inf, -np.inf], np.nan, inplace=True)\n        #y_preds = [estimator.predict(xgb.DMatrix(X,enable_categorical=True))\\\n        #           for estimator in self.estimators]\n        y_preds = [estimator.predict(xgb.DMatrix(X,enable_categorical=True),\n                             iteration_range=(0,estimator.best_iteration))\\\n                   for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:26.042601Z","iopub.execute_input":"2024-05-20T13:18:26.043438Z","iopub.status.idle":"2024-05-20T13:18:26.058207Z","shell.execute_reply.started":"2024-05-20T13:18:26.043393Z","shell.execute_reply":"2024-05-20T13:18:26.056573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fitted_models_cat = []\nfitted_models_lgb = []\nfitted_models_xgb = []\n\nfor i in range(5):\n    cat_model = CatBoostClassifier().load_model(INPUT+f'/cat_{i}.cbm','cbm')\n    fitted_models_cat.append(cat_model)\n    del cat_model\n    model = lgb.Booster(model_file=INPUT+f'/lgb_{i}.txt')\n    fitted_models_lgb.append(model)\n    del model\n    xgb_model = xgb.Booster(model_file=INPUT+f'/xgb_{i}.json')\n    fitted_models_xgb.append(xgb_model)\n    del xgb_model\n    \ncat_model = VotingModel(fitted_models_cat)\nmodel = VotingModel(fitted_models_lgb)\nxgb_model = VotingModel(fitted_models_xgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:26.060219Z","iopub.execute_input":"2024-05-20T13:18:26.060811Z","iopub.status.idle":"2024-05-20T13:18:30.753663Z","shell.execute_reply.started":"2024-05-20T13:18:26.060757Z","shell.execute_reply":"2024-05-20T13:18:30.752574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# restore","metadata":{}},{"cell_type":"code","source":"testing = pd.read_parquet(\n    \"/kaggle/input/home-credit-credit-risk-model-stability/parquet_files/test/test_base.parquet\")\\\n            .set_index(\"case_id\")\n\ntesting[\"WEEK_NUM\"] = (pd.to_datetime(testing['date_decision'])-pd.to_datetime('2018-12-30'))\\\n                      .map(lambda x:int(x.days/7) if not pd.isnull(x) else None)\n\n_min = testing[\"WEEK_NUM\"].min()\n_max = testing[\"WEEK_NUM\"].max()\nprint(_min,_max)\ntesting['coef'] = testing.apply(\n    lambda x: (x.WEEK_NUM-_min)/(_max-_min) if not pd.isnull(x.WEEK_NUM) else None,axis=1)\n\nprint(testing.head(10))","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:30.757411Z","iopub.execute_input":"2024-05-20T13:18:30.757798Z","iopub.status.idle":"2024-05-20T13:18:30.788860Z","shell.execute_reply.started":"2024-05-20T13:18:30.757767Z","shell.execute_reply":"2024-05-20T13:18:30.787710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Stacking","metadata":{}},{"cell_type":"code","source":"import joblib\nmeta_model = joblib.load(INPUT+'/meta.pkl')","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:30.790511Z","iopub.execute_input":"2024-05-20T13:18:30.790841Z","iopub.status.idle":"2024-05-20T13:18:30.800663Z","shell.execute_reply.started":"2024-05-20T13:18:30.790813Z","shell.execute_reply":"2024-05-20T13:18:30.799258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\"])\n\nsubmission = pd.DataFrame({\n    \"case_id\": df_test[\"case_id\"].to_numpy()\n}).set_index('case_id')\n\n\ndf_test = df_test.set_index(\"case_id\")\n\ntest_meta_features = pd.DataFrame(index=df_test.index, \n                                  columns=['LightGBM', 'XGBoost', 'CatBoost'])\ntest_meta_features['LightGBM'] = model.predict_lgb(df_test)\ntest_meta_features['XGBoost'] = xgb_model.predict_xgb(df_test)\ntest_meta_features['CatBoost'] = cat_model.predict_cb(df_test)\ntest_meta_features[\"meta\"] = meta_model.predict_proba(test_meta_features)[:, 1] \ntest_meta_features['coef'] = testing['coef']\n#test_meta_features['score'] = \\\n#    test_meta_features['LightGBM']*test_meta_features['coef'] +\\\n#    test_meta_features['CatBoost']*(1-test_meta_features['coef'])\n\ndef f(x):\n    if x.coef>2/3: \n        y = x.meta-0.073\n        if y>1:return 1\n        elif y<0:return 0\n        else:return y\n    else:\n        return x.meta\n\ntest_meta_features['score'] = \\\n    test_meta_features.apply(\n        lambda x: f(x),axis=1)\n\nprint(test_meta_features.head(10))\ndel cat_model\ndel model\ndel xgb_model\ndel meta_model\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:30.802380Z","iopub.execute_input":"2024-05-20T13:18:30.802769Z","iopub.status.idle":"2024-05-20T13:18:32.146161Z","shell.execute_reply.started":"2024-05-20T13:18:30.802737Z","shell.execute_reply":"2024-05-20T13:18:32.145135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission[\"score\"] = test_meta_features[\"score\"] \n#submission[\"score\"] = test_meta_features['CatBoost']\n#submission[\"score\"] = np.mean(test_meta_features, axis=1)\nsubmission.to_csv(\"./submission.csv\")\nprint(submission.head(10))\nprint('🎉✨🎊done!')","metadata":{"execution":{"iopub.status.busy":"2024-05-20T13:18:32.147507Z","iopub.execute_input":"2024-05-20T13:18:32.148125Z","iopub.status.idle":"2024-05-20T13:18:32.159010Z","shell.execute_reply.started":"2024-05-20T13:18:32.148093Z","shell.execute_reply":"2024-05-20T13:18:32.157485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}