{"metadata":{"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30683,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"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"},"papermill":{"default_parameters":{},"duration":2159.116896,"end_time":"2024-04-07T10:19:38.712675","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-04-07T09:43:39.595779","version":"2.5.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport os\nimport gc\nimport datetime\nfrom glob import glob\nimport numpy as np\nimport pandas as pd\nimport polars as pl\n\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.metrics import roc_auc_score\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":2.185049,"end_time":"2024-04-07T09:43:44.599573","exception":false,"start_time":"2024-04-07T09:43:42.414524","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:24:20.471772Z","iopub.execute_input":"2024-04-17T15:24:20.472569Z","iopub.status.idle":"2024-04-17T15:24:22.672298Z","shell.execute_reply.started":"2024-04-17T15:24:20.472539Z","shell.execute_reply":"2024-04-17T15:24:22.671493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"start_time_utc = datetime.datetime.now()\nprint(f'Notebook Start Time (UTC): {start_time_utc}')\n\nstart_time_kst = start_time_utc + datetime.timedelta(hours=9)\nprint(f\"Notebook Start Time (KST): {start_time_kst}\")","metadata":{"execution":{"iopub.status.busy":"2024-04-17T15:24:22.673749Z","iopub.execute_input":"2024-04-17T15:24:22.674190Z","iopub.status.idle":"2024-04-17T15:24:22.679486Z","shell.execute_reply.started":"2024-04-17T15:24:22.674165Z","shell.execute_reply":"2024-04-17T15:24:22.678661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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        for col in df.columns:\n            if col not in [\"target\", \"case_id\", \"WEEK_NUM\"]:\n                isnull = df[col].is_null().mean()\n                if isnull > 0.7:\n                    df = df.drop(col)\n        \n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) & (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n        \n        return df\n\n\n\nclass Aggregator:\n    # Please add or subtract features yourself, be aware that too many features will take up too much space.\n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        expr_median = [pl.median(col).alias(f\"median_{col}\") for col in cols]\n        expr_var = [pl.var(col).alias(f\"var_{col}\") for col in cols]\n\n        return expr_max + expr_last + expr_mean \n\n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        expr_median = [pl.median(col).alias(f\"median_{col}\") for col in cols]\n\n        return expr_max + expr_last + expr_mean \n\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        # expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        return expr_max + expr_last  # +expr_count\n\n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return expr_max + expr_last\n\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return expr_max + expr_last\n\n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs","metadata":{"papermill":{"duration":0.025581,"end_time":"2024-04-07T09:43:48.930409","exception":false,"start_time":"2024-04-07T09:43:48.904828","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:24:26.913383Z","iopub.execute_input":"2024-04-17T15:24:26.914011Z","iopub.status.idle":"2024-04-17T15:24:26.937873Z","shell.execute_reply.started":"2024-04-17T15:24:26.913960Z","shell.execute_reply":"2024-04-17T15:24:26.936812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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\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","metadata":{"papermill":{"duration":0.020401,"end_time":"2024-04-07T09:43:48.998353","exception":false,"start_time":"2024-04-07T09:43:48.977952","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:24:29.840048Z","iopub.execute_input":"2024-04-17T15:24:29.840398Z","iopub.status.idle":"2024-04-17T15:24:29.847855Z","shell.execute_reply.started":"2024-04-17T15:24:29.840370Z","shell.execute_reply":"2024-04-17T15:24:29.846900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n    for i, df in enumerate(depth_0 + depth_1 + depth_2):\n        df_base = df_base.join(df, how=\"left\", on=\"case_id\", suffix=f\"_{i}\")\n    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base\n\n\ndef to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    return df_data, cat_cols","metadata":{"papermill":{"duration":0.019136,"end_time":"2024-04-07T09:43:49.028168","exception":false,"start_time":"2024-04-07T09:43:49.009032","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:24:34.919064Z","iopub.execute_input":"2024-04-17T15:24:34.919714Z","iopub.status.idle":"2024-04-17T15:24:34.926765Z","shell.execute_reply.started":"2024-04-17T15:24:34.919681Z","shell.execute_reply":"2024-04-17T15:24:34.925863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        if str(col_type)==\"category\":\n            continue\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            continue\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","metadata":{"papermill":{"duration":0.025318,"end_time":"2024-04-07T09:43:49.092539","exception":false,"start_time":"2024-04-07T09:43:49.067221","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:24:35.363907Z","iopub.execute_input":"2024-04-17T15:24:35.364395Z","iopub.status.idle":"2024-04-17T15:24:35.377425Z","shell.execute_reply.started":"2024-04-17T15:24:35.364359Z","shell.execute_reply":"2024-04-17T15:24:35.376374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nROOT            = Path(ROOT)\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\ndata_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{"papermill":{"duration":0.017335,"end_time":"2024-04-07T09:43:49.120502","exception":false,"start_time":"2024-04-07T09:43:49.103167","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:24:46.124757Z","iopub.execute_input":"2024-04-17T15:24:46.125142Z","iopub.status.idle":"2024-04-17T15:27:02.922035Z","shell.execute_reply.started":"2024-04-17T15:24:46.125111Z","shell.execute_reply":"2024-04-17T15:27:02.921018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ndf_train = df_train.pipe(Pipeline.filter_cols)\ngc.collect()","metadata":{"papermill":{"duration":22.182494,"end_time":"2024-04-07T09:46:28.617717","exception":false,"start_time":"2024-04-07T09:46:06.435223","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:27:02.923898Z","iopub.execute_input":"2024-04-17T15:27:02.924281Z","iopub.status.idle":"2024-04-17T15:27:25.098742Z","shell.execute_reply.started":"2024-04-17T15:27:02.924245Z","shell.execute_reply":"2024-04-17T15:27:25.097793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\nnums=df_train.select_dtypes(exclude='category').columns\nfrom itertools import combinations, permutations\n#df_train=df_train[nums]\nnans_df = df_train[nums].isna()\nnans_groups={}\nfor col in nums:\n    cur_group = nans_df[col].sum()\n    try:\n        nans_groups[cur_group].append(col)\n    except:\n        nans_groups[cur_group]=[col]\ndel nans_df; x=gc.collect()\n\ndef reduce_group(grps):\n    use = []\n    for g in grps:\n        mx = 0; vx = g[0]\n        for gg in g:\n            n = df_train[gg].nunique()\n            if n>mx:\n                mx = n\n                vx = gg\n            #print(str(gg)+'-'+str(n),', ',end='')\n        use.append(vx)\n        #print()\n    print('Use these',use)\n    return use\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    # 计算列之间的相关性\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\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    print('####### NAN count =',k)\nprint(uses)\nprint(len(uses))\nuses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train=df_train[uses]\n# df_train.drop(['requesttype_4525192L_cnt','max_empl_employedtotal_800L_cnt', 'max_empl_industry_691L_cnt'], axis=1, inplace=True)","metadata":{"papermill":{"duration":166.726205,"end_time":"2024-04-07T09:49:35.793659","exception":false,"start_time":"2024-04-07T09:46:49.067454","status":"completed"},"scrolled":true,"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:27:46.697025Z","iopub.execute_input":"2024-04-17T15:27:46.697945Z","iopub.status.idle":"2024-04-17T15:29:03.549990Z","shell.execute_reply.started":"2024-04-17T15:27:46.697911Z","shell.execute_reply":"2024-04-17T15:29:03.549128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"papermill":{"duration":1.183027,"end_time":"2024-04-07T09:49:38.596688","exception":false,"start_time":"2024-04-07T09:49:37.413661","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-17T15:29:19.094524Z","iopub.execute_input":"2024-04-17T15:29:19.095175Z","iopub.status.idle":"2024-04-17T15:29:20.285705Z","shell.execute_reply.started":"2024-04-17T15:29:19.095147Z","shell.execute_reply":"2024-04-17T15:29:20.284896Z"},"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-04-17T15:29:41.791150Z","iopub.execute_input":"2024-04-17T15:29:41.791518Z","iopub.status.idle":"2024-04-17T15:29:51.387936Z","shell.execute_reply.started":"2024-04-17T15:29:41.791490Z","shell.execute_reply":"2024-04-17T15:29:51.387168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from catboost import CatBoostClassifier, Pool\n\nparams = {\n    \"eval_metric\": \"AUC\",  # 相当于LightGBM中的metric参数\n    # \"depth\": 10,  # 相当于LightGBM中的max_depth参数\n    \"learning_rate\": 0.03,\n    \"iterations\":6000,  # 6000\n    # \"random_seed\": 3107,  # 相当于LightGBM中的random_state参数\n    # \"l2_leaf_reg\": 10,  # 相当于LightGBM中的reg_lambda参数\n    # \"border_count\": 254,  # 没有直接相当于LightGBM中的colsample_by*参数，但可以用来增加分箱数\n    \"verbose\": False,  # 控制输出信息\n    \"task_type\": \"GPU\",  # 使用GPU训练\n}\n\nn_splits = 5\nfitted_models = []\ncv_scores = []\n\ncv = StratifiedGroupKFold(n_splits=n_splits, shuffle=False)\n\nstep = 0\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#   Because it takes a long time to divide the data set, \n    step += 1\n    print(f'current step: {step}')\n    \n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# each time the data set is divided, two models are trained to each other twice, which saves time.\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n\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\n    model = CatBoostClassifier(**params)\n    model.fit(train_pool, eval_set=val_pool, verbose=1000)\n\n    \n    fitted_models.append(model)\n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n    \nprint(\"CV AUC scores: \", cv_scores)\nprint(\"AVG CV AUC score: \", np.mean(cv_scores))\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2024-04-17T15:30:13.446162Z","iopub.execute_input":"2024-04-17T15:30:13.446942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import joblib\n\njoblib.dump(fitted_models, 'cat_models.joblib')\n\nnotebook_info = {\n    'notebook_start_time': start_time_kst,\n    'description': 'first cat models',\n    'cols': df_train.columns.to_list(),\n    'cat_cols': cat_cols,\n}\njoblib.dump(notebook_info, 'notebook_info.joblib')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -al","metadata":{},"execution_count":null,"outputs":[]}]}