{"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-26T10:11:03.733789Z","iopub.execute_input":"2024-05-26T10:11:03.734144Z","iopub.status.idle":"2024-05-26T10:11:05.662350Z","shell.execute_reply.started":"2024-05-26T10:11:03.734115Z","shell.execute_reply":"2024-05-26T10:11:05.661353Z"},"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-26T10:11:05.664179Z","iopub.execute_input":"2024-05-26T10:11:05.664620Z","iopub.status.idle":"2024-05-26T10:11:05.684068Z","shell.execute_reply.started":"2024-05-26T10:11:05.664593Z","shell.execute_reply":"2024-05-26T10:11:05.683130Z"},"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-26T10:11:05.685665Z","iopub.execute_input":"2024-05-26T10:11:05.686014Z","iopub.status.idle":"2024-05-26T10:11:05.701466Z","shell.execute_reply.started":"2024-05-26T10:11:05.685965Z","shell.execute_reply":"2024-05-26T10:11:05.700548Z"},"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-26T10:11:05.702302Z","iopub.execute_input":"2024-05-26T10:11:05.702587Z","iopub.status.idle":"2024-05-26T10:11:05.723812Z","shell.execute_reply.started":"2024-05-26T10:11:05.702565Z","shell.execute_reply":"2024-05-26T10:11:05.723244Z"},"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-26T10:11:05.725883Z","iopub.execute_input":"2024-05-26T10:11:05.726368Z","iopub.status.idle":"2024-05-26T10:11:05.967478Z","shell.execute_reply.started":"2024-05-26T10:11:05.726333Z","shell.execute_reply":"2024-05-26T10:11:05.966687Z"},"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-26T10:11:05.968849Z","iopub.execute_input":"2024-05-26T10:11:05.969217Z","iopub.status.idle":"2024-05-26T10:11:06.147199Z","shell.execute_reply.started":"2024-05-26T10:11:05.969182Z","shell.execute_reply":"2024-05-26T10:11:06.146271Z"},"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-26T10:11:06.148404Z","iopub.execute_input":"2024-05-26T10:11:06.148746Z","iopub.status.idle":"2024-05-26T10:11:06.458726Z","shell.execute_reply.started":"2024-05-26T10:11:06.148713Z","shell.execute_reply":"2024-05-26T10:11:06.457812Z"},"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        #print(y_preds)\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        #print(y_preds)\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        #                             validate_features=False)\\\n        #           for estimator in self.estimators]\n        #y_preds = [estimator.predict(xgb.DMatrix(X,enable_categorical=True),\n        #                     validate_features=False,\\\n        #                     iteration_range=(0,estimator.best_iteration))\\\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        #print(y_preds)\n        return np.mean(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:11:06.460044Z","iopub.execute_input":"2024-05-26T10:11:06.460482Z","iopub.status.idle":"2024-05-26T10:11:06.470623Z","shell.execute_reply.started":"2024-05-26T10:11:06.460456Z","shell.execute_reply":"2024-05-26T10:11:06.469632Z"},"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-26T10:11:06.471672Z","iopub.execute_input":"2024-05-26T10:11:06.471946Z","iopub.status.idle":"2024-05-26T10:11:11.494069Z","shell.execute_reply.started":"2024-05-26T10:11:06.471923Z","shell.execute_reply":"2024-05-26T10:11:11.493272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Stacking","metadata":{}},{"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)\nprint(test_meta_features.head(10))\n\ndel cat_model\ndel model\ndel xgb_model\ndel fitted_models_cat, fitted_models_lgb, fitted_models_xgb\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:11:11.495122Z","iopub.execute_input":"2024-05-26T10:11:11.495424Z","iopub.status.idle":"2024-05-26T10:11:12.642734Z","shell.execute_reply.started":"2024-05-26T10:11:11.495400Z","shell.execute_reply":"2024-05-26T10:11:12.642040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import joblib\nmeta_model = joblib.load(INPUT+'/meta.pkl')","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:11:12.643751Z","iopub.execute_input":"2024-05-26T10:11:12.644052Z","iopub.status.idle":"2024-05-26T10:11:12.659629Z","shell.execute_reply.started":"2024-05-26T10:11:12.644024Z","shell.execute_reply":"2024-05-26T10:11:12.658740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_meta_features['meta'] = meta_model.predict_proba(test_meta_features)[:, 1]\n\nprint(test_meta_features.head(10))\n\ndel meta_model,df_test\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:11:12.660695Z","iopub.execute_input":"2024-05-26T10:11:12.661473Z","iopub.status.idle":"2024-05-26T10:11:12.745270Z","shell.execute_reply.started":"2024-05-26T10:11:12.661447Z","shell.execute_reply":"2024-05-26T10:11:12.744366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 新","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        \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        return expr_max\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        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        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        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        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    \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    '''\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n    '''\n    for i, df in 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    \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    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:11:12.746834Z","iopub.execute_input":"2024-05-26T10:11:12.747109Z","iopub.status.idle":"2024-05-26T10:11:12.778857Z","shell.execute_reply.started":"2024-05-26T10:11:12.747088Z","shell.execute_reply":"2024-05-26T10:11:12.777943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 选择","metadata":{}},{"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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:11:12.783822Z","iopub.execute_input":"2024-05-26T10:11:12.784079Z","iopub.status.idle":"2024-05-26T10:12:40.787831Z","shell.execute_reply.started":"2024-05-26T10:11:12.784058Z","shell.execute_reply":"2024-05-26T10:12:40.786310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ngc.collect()\n\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)","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:12:40.790177Z","iopub.execute_input":"2024-05-26T10:12:40.790566Z","iopub.status.idle":"2024-05-26T10:13:22.857008Z","shell.execute_reply.started":"2024-05-26T10:12:40.790532Z","shell.execute_reply":"2024-05-26T10:13:22.856072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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":{"iopub.status.busy":"2024-05-26T10:13:22.858840Z","iopub.execute_input":"2024-05-26T10:13:22.859225Z","iopub.status.idle":"2024-05-26T10:13:22.868343Z","shell.execute_reply.started":"2024-05-26T10:13:22.859188Z","shell.execute_reply":"2024-05-26T10:13:22.867385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nnums=df_train.select_dtypes(exclude='category').columns\n\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\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\n\nprint(len(uses))\nuses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\n\ndf_train=df_train[uses]\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:13:22.869583Z","iopub.execute_input":"2024-05-26T10:13:22.869911Z","iopub.status.idle":"2024-05-26T10:13:51.048256Z","shell.execute_reply.started":"2024-05-26T10:13:22.869880Z","shell.execute_reply":"2024-05-26T10:13:51.047389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:13:51.049725Z","iopub.execute_input":"2024-05-26T10:13:51.050242Z","iopub.status.idle":"2024-05-26T10:13:51.183693Z","shell.execute_reply.started":"2024-05-26T10:13:51.050205Z","shell.execute_reply":"2024-05-26T10:13:51.182927Z"},"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-26T10:13:51.185079Z","iopub.execute_input":"2024-05-26T10:13:51.185531Z","iopub.status.idle":"2024-05-26T10:13:51.325378Z","shell.execute_reply.started":"2024-05-26T10:13:51.185493Z","shell.execute_reply":"2024-05-26T10:13:51.324660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.select([col for col in df_train.columns if col != \"target\"])\nprint(\"test data shape:\\t\", df_test.shape)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:13:51.326570Z","iopub.execute_input":"2024-05-26T10:13:51.326814Z","iopub.status.idle":"2024-05-26T10:13:51.618348Z","shell.execute_reply.started":"2024-05-26T10:13:51.326793Z","shell.execute_reply":"2024-05-26T10:13:51.617407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 🎄🎋🎍🧶🎑⛳🥉🧩🔫🔋📗\n#df_train['target'] = 0\ndf_test['target'] = 2\ndf_test = df_test[uses]","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:13:51.619717Z","iopub.execute_input":"2024-05-26T10:13:51.619981Z","iopub.status.idle":"2024-05-26T10:13:51.638043Z","shell.execute_reply.started":"2024-05-26T10:13:51.619959Z","shell.execute_reply":"2024-05-26T10:13:51.637138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train=pd.concat([df_train,df_test])\nprint(\"test data shape:\\t\", df_train.shape)\nprint(set(df_train['target']))\ndf_train=reduce_mem_usage(df_train)","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:13:51.639534Z","iopub.execute_input":"2024-05-26T10:13:51.639881Z","iopub.status.idle":"2024-05-26T10:14:02.151355Z","shell.execute_reply.started":"2024-05-26T10:13:51.639849Z","shell.execute_reply":"2024-05-26T10:14:02.150445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 玄幻","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":{"iopub.status.busy":"2024-05-26T10:14:02.152745Z","iopub.execute_input":"2024-05-26T10:14:02.153041Z","iopub.status.idle":"2024-05-26T10:14:04.900670Z","shell.execute_reply.started":"2024-05-26T10:14:02.153016Z","shell.execute_reply":"2024-05-26T10:14:04.899867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(\"category\")\n\nif len(df_test)<100: \n    n = 2 ; n2 = 1\nelse: \n    n = 100 ; n2 = 25\n\nps = {  \"boosting_type\": \"gbdt\",\n        \"objective\": 'multiclass',\n        'num_class':3,\n        \"metric\": \"auc_mu\",\n        \"max_depth\": 16,\n        \"num_leaves\": 32,\n        \"min_child_samples\":100,\n        \"learning_rate\": 0.03,\n        \"feature_fraction\": 0.9,\n        \"bagging_fraction\": 0.8,\n        \"bagging_freq\": 5,\n        \"n_estimators\": n,\n        \"verbose\": 1,#-1,\n        \"device\": \"cpu\",\n        #\"max_bin\":225,\n        \"force_col_wise\":True}\n\nmodel = lgb.LGBMClassifier(**ps)#objective='multiclass',num_class=3)\nmodel.fit(df_train,y,\n          eval_set=[(df_train, y)],\n          callbacks = [lgb.log_evaluation(n2), lgb.early_stopping(50)])   \ndel df_train,y\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:14:04.902165Z","iopub.execute_input":"2024-05-26T10:14:04.902438Z","iopub.status.idle":"2024-05-26T10:15:11.859488Z","shell.execute_reply.started":"2024-05-26T10:14:04.902416Z","shell.execute_reply":"2024-05-26T10:15:11.858475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\",'target'])\ndf_test = df_test.set_index(\"case_id\")\ngc.collect()\n\ndf_test[cat_cols] = df_test[cat_cols].astype(\"category\")\ntest_meta_features['p'] = model.predict(df_test)\ntest_meta_features['p0'] = model.predict_proba(df_test)[:,0]\ntest_meta_features['p1'] = model.predict_proba(df_test)[:,1]\ntest_meta_features['p2'] = model.predict_proba(df_test)[:,2]\n\ndel df_test,model\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:15:11.861267Z","iopub.execute_input":"2024-05-26T10:15:11.861588Z","iopub.status.idle":"2024-05-26T10:15:12.298488Z","shell.execute_reply.started":"2024-05-26T10:15:11.861564Z","shell.execute_reply":"2024-05-26T10:15:12.297539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\ntest_meta_features['score'] = (test_meta_features['p1'] + \\\n                              test_meta_features['p2'] * test_meta_features['meta']).clip(0,1)\n'''\ntest_meta_features['score'] = test_meta_features['LightGBM']*0.5 + \\\n                              test_meta_features['CatBoost']*0.5\n\ncondition = test_meta_features['p']==1\ntest_meta_features.loc[condition, 'score'] = \\\n    (test_meta_features.loc[condition, 'score'] + 0.083).clip(0,1)\n\ncondition = test_meta_features['p']==0\ntest_meta_features.loc[condition, 'score'] = \\\n    (test_meta_features.loc[condition, 'score'] - 0.083).clip(0,1)\n\nprint(test_meta_features.head(10))","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:15:12.299923Z","iopub.execute_input":"2024-05-26T10:15:12.300204Z","iopub.status.idle":"2024-05-26T10:15:12.318888Z","shell.execute_reply.started":"2024-05-26T10:15:12.300181Z","shell.execute_reply":"2024-05-26T10:15:12.318015Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 提交","metadata":{}},{"cell_type":"code","source":"#submission[\"score\"] = meta_model.predict_proba(test_meta_features)[:, 1] \n#submission[\"score\"] = test_meta_features['CatBoost']\n#submission[\"score\"] = np.mean(test_meta_features, axis=1)\n\nsubmission[\"score\"] = test_meta_features['score']\n\nsubmission.to_csv(\"./submission.csv\")\nprint(submission.head(10))\nprint('🎉✨🎊done!')","metadata":{"execution":{"iopub.status.busy":"2024-05-26T10:15:12.320082Z","iopub.execute_input":"2024-05-26T10:15:12.320549Z","iopub.status.idle":"2024-05-26T10:15:12.333678Z","shell.execute_reply.started":"2024-05-26T10:15:12.320524Z","shell.execute_reply":"2024-05-26T10:15:12.332851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}