{"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":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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 StratifiedKFold, 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\"\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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-22T15:10:24.804134Z","iopub.execute_input":"2024-05-22T15:10:24.804555Z","iopub.status.idle":"2024-05-22T15:10:30.272240Z","shell.execute_reply.started":"2024-05-22T15:10:24.804522Z","shell.execute_reply":"2024-05-22T15:10:30.271305Z"},"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-22T15:10:30.274407Z","iopub.execute_input":"2024-05-22T15:10:30.275033Z","iopub.status.idle":"2024-05-22T15:10:30.298008Z","shell.execute_reply.started":"2024-05-22T15:10:30.275003Z","shell.execute_reply":"2024-05-22T15:10:30.296745Z"},"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-22T15:10:30.300263Z","iopub.execute_input":"2024-05-22T15:10:30.300651Z","iopub.status.idle":"2024-05-22T15:10:30.321990Z","shell.execute_reply.started":"2024-05-22T15:10:30.300609Z","shell.execute_reply":"2024-05-22T15:10:30.320968Z"},"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-22T15:10:30.323634Z","iopub.execute_input":"2024-05-22T15:10:30.324250Z","iopub.status.idle":"2024-05-22T15:10:30.350693Z","shell.execute_reply.started":"2024-05-22T15:10:30.324214Z","shell.execute_reply":"2024-05-22T15:10:30.349850Z"},"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        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":{"iopub.status.busy":"2024-05-22T15:10:30.353754Z","iopub.execute_input":"2024-05-22T15:10:30.354255Z","iopub.status.idle":"2024-05-22T15:13:53.541967Z","shell.execute_reply.started":"2024-05-22T15:10:30.354213Z","shell.execute_reply":"2024-05-22T15:13:53.540880Z"},"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-22T15:13:53.543132Z","iopub.execute_input":"2024-05-22T15:13:53.543413Z","iopub.status.idle":"2024-05-22T15:15:02.145757Z","shell.execute_reply.started":"2024-05-22T15:13:53.543388Z","shell.execute_reply":"2024-05-22T15:15:02.144623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 保存cat🎑\npd.DataFrame({'cat':cat_cols}).to_csv('cat.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:15:02.147378Z","iopub.execute_input":"2024-05-22T15:15:02.147827Z","iopub.status.idle":"2024-05-22T15:15:02.158730Z","shell.execute_reply.started":"2024-05-22T15:15:02.147786Z","shell.execute_reply":"2024-05-22T15:15:02.157642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 筛选","metadata":{}},{"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-22T15:15:02.160144Z","iopub.execute_input":"2024-05-22T15:15:02.160759Z","iopub.status.idle":"2024-05-22T15:15:02.170641Z","shell.execute_reply.started":"2024-05-22T15:15:02.160727Z","shell.execute_reply":"2024-05-22T15:15:02.169622Z"},"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]","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:15:02.171968Z","iopub.execute_input":"2024-05-22T15:15:02.172282Z","iopub.status.idle":"2024-05-22T15:18:03.761245Z","shell.execute_reply.started":"2024-05-22T15:15:02.172255Z","shell.execute_reply":"2024-05-22T15:18:03.760120Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 保存use🎄\npd.DataFrame({'use':uses}).to_csv('use.csv',index=False)\n\n#df_train = df_train.iloc[:6000]##################","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:18:03.762868Z","iopub.execute_input":"2024-05-22T15:18:03.763154Z","iopub.status.idle":"2024-05-22T15:18:03.769921Z","shell.execute_reply.started":"2024-05-22T15:18:03.763129Z","shell.execute_reply":"2024-05-22T15:18:03.768939Z"},"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\"])\ncv = StratifiedGroupKFold(n_splits=4, shuffle=False)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:18:03.771310Z","iopub.execute_input":"2024-05-22T15:18:03.772015Z","iopub.status.idle":"2024-05-22T15:18:05.445764Z","shell.execute_reply.started":"2024-05-22T15:18:03.771978Z","shell.execute_reply":"2024-05-22T15:18:05.444781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:18:05.447106Z","iopub.execute_input":"2024-05-22T15:18:05.447436Z","iopub.status.idle":"2024-05-22T15:18:40.803372Z","shell.execute_reply.started":"2024-05-22T15:18:05.447407Z","shell.execute_reply":"2024-05-22T15:18:40.802298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\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    \"random_state\": 42,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    #'categorical_feature ': 'auto', ##\n    'num_leaves':64,\n    \"device\": 'gpu', \n    \"verbose\": -1,\n    'max_bin':250\n}\n\nxgb_params = {\n    \"booster\": \"gbtree\",\n    \"objective\": \"binary:logistic\",\n    \"eval_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    \"alpha\": 0.1,  \n    \"lambda\": 10,  \n    \"tree_method\": 'gpu_hist' ,\n    \"random_state\": 42,\n    \"verbosity\": 0,\n    \"enable_categorical\":True,\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:18:40.805174Z","iopub.execute_input":"2024-05-22T15:18:40.805606Z","iopub.status.idle":"2024-05-22T15:18:40.812544Z","shell.execute_reply.started":"2024-05-22T15:18:40.805576Z","shell.execute_reply":"2024-05-22T15:18:40.811462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfitted_models_cat = []\nfitted_models_lgb = []\nfitted_models_xgb = []\n\ncv_scores_cat = []\ncv_scores_lgb = []\ncv_scores_xgb = []\n\nroll = 0\n\n# 存储第一层模型的预测结果\nmeta_features = pd.DataFrame(index=df_train.index,\n                             columns=['CatBoost', 'LightGBM', 'XGBoost'])\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n    print('------------ start roll ',roll,' ------------')\n    i = roll\n    roll = roll + 1\n    ################# CAT\n    '''\n    train_pool = Pool(X_train, y_train, cat_features=cat_cols)\n    val_pool = Pool(X_valid, y_valid, cat_features=cat_cols)\n    cat_model = CatBoostClassifier(\n                    eval_metric='AUC',\n                    task_type='GPU',\n                    learning_rate=0.03,\n                    iterations=6000,\n                    early_stopping_rounds=100)\n    random_seed=3107\n    cat_model.fit(train_pool, eval_set=val_pool, verbose=500)\n#    fitted_models_cat.append(cat_model)\n    y_pred_valid = cat_model.predict_proba(val_pool,\n                            ntree_end=cat_model.get_best_iteration())[:, 1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_cat.append(auc_score)\n    meta_features.loc[X_valid.index, 'CatBoost'] = y_pred_valid\n    cat_model.save_model(f'cat_{i}.cbm', format=\"cbm\")\n    del cat_model\n    '''\n    ################# LGBM\n    \n    X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n    X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\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(50), lgb.early_stopping(100)] )    \n#    fitted_models_lgb.append(model)\n    y_pred_valid = model.predict_proba(X_valid,\n                            num_iteration=model.booster_.best_iteration)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_lgb.append(auc_score)\n    meta_features.loc[X_valid.index, 'LightGBM'] = y_pred_valid\n    model.booster_.save_model(f'lgb_{i}.txt')\n    del model\n    \n    ################# XGB\n    '''\n    X_train[cat_cols] = X_train[cat_cols].astype('category')\n    X_valid[cat_cols] = X_valid[cat_cols].astype('category')\n    X_train.replace([np.inf,-np.inf],np.nan,inplace=True)\n    X_valid.replace([np.inf,-np.inf],np.nan,inplace=True)\n    xgb_model = xgb.XGBClassifier(**xgb_params)\n    xgb_model.fit(X_train, y_train, eval_set=[(X_valid, y_valid)],\n              early_stopping_rounds=100, verbose=50)\n#    fitted_models_xgb.append(xgb_model)\n    y_pred_valid = xgb_model.predict_proba(X_valid,\n                   iteration_range=(0,xgb_model.best_iteration))[:, 1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_xgb.append(auc_score)\n    meta_features.loc[X_valid.index, 'XGBoost'] = y_pred_valid\n    xgb_model.save_model(f'xgb_{i}.json')\n    del xgb_model\n    '''\n    \n    meta_features.to_csv('meta_features.csv')\n    gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:18:40.816188Z","iopub.execute_input":"2024-05-22T15:18:40.816564Z","iopub.status.idle":"2024-05-22T15:52:53.284779Z","shell.execute_reply.started":"2024-05-22T15:18:40.816539Z","shell.execute_reply":"2024-05-22T15:52:53.283671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nprint(\"CV AUC scores: \", cv_scores_cat)\nprint(\"Maximum CV AUC score: \", max(cv_scores_cat))\n'''\n'''\nprint(\"CV AUC scores: \", cv_scores_lgb)\nprint(\"Maximum CV AUC score: \", max(cv_scores_lgb))\n'''\n'''\nprint(\"CV AUC scores: \", cv_scores_xgb)\nprint(\"Maximum CV AUC score: \", max(cv_scores_xgb))\n'''\n'''\nprint(\"CV AUC scores: \", cv_scores_rfc)\nprint(\"Maximum CV AUC score: \", max(cv_scores_rfc))\n'''","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:52:53.286572Z","iopub.execute_input":"2024-05-22T15:52:53.287510Z","iopub.status.idle":"2024-05-22T15:52:53.296291Z","shell.execute_reply.started":"2024-05-22T15:52:53.287466Z","shell.execute_reply":"2024-05-22T15:52:53.295101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 保存为二进制格式，更加高效\n'''\nfor i in range(K):\n'''\n    ################# CAT\n    '''\n    cat_model = fitted_models_cat[i]\n    cat_model.save_model(f'cat_{i}.cbm', format=\"cbm\")\n    '''\n    ################# LGBM\n    '''\n    model = fitted_models_lgb[i]\n    model.booster_.save_model(f'lgb_{i}.txt')\n    '''\n    ################# XGB\n    '''\n    xgb_model = fitted_models_xgb[i]\n    xgb_model.save_model(f'xgb_{i}.json')\n    '''\n    ################# Random Forest\n    '''\n    rfc_model = fitted_models_rfc[i]\n    joblib.dump(rfc_model, f'rfc_{i}.pkl')\n    '''","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:52:53.297598Z","iopub.execute_input":"2024-05-22T15:52:53.297967Z","iopub.status.idle":"2024-05-22T15:52:53.310378Z","shell.execute_reply.started":"2024-05-22T15:52:53.297926Z","shell.execute_reply":"2024-05-22T15:52:53.308993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nmeta_features.to_csv('meta_features.csv')\nprint('done!')\n'''","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:52:53.311254Z","iopub.status.idle":"2024-05-22T15:52:53.311676Z","shell.execute_reply.started":"2024-05-22T15:52:53.311464Z","shell.execute_reply":"2024-05-22T15:52:53.311484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}