{"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"}],"dockerImageVersionId":30665,"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\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'\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\nfrom sklearn.base import BaseEstimator, ClassifierMixin","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-27T10:49:34.733381Z","iopub.execute_input":"2024-03-27T10:49:34.733838Z","iopub.status.idle":"2024-03-27T10:49:39.770367Z","shell.execute_reply.started":"2024-03-27T10:49:34.733806Z","shell.execute_reply":"2024-03-27T10:49:39.769330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***This notebook is to remove features based on relevance***","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        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.75:\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\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        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        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\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    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    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-03-27T10:49:39.772553Z","iopub.execute_input":"2024-03-27T10:49:39.773253Z","iopub.status.idle":"2024-03-27T10:49:39.823965Z","shell.execute_reply.started":"2024-03-27T10:49:39.773206Z","shell.execute_reply":"2024-03-27T10:49:39.822466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:49:39.826071Z","iopub.execute_input":"2024-03-27T10:49:39.826533Z","iopub.status.idle":"2024-03-27T10:49:39.849668Z","shell.execute_reply.started":"2024-03-27T10:49:39.826493Z","shell.execute_reply":"2024-03-27T10:49:39.848687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:49:39.852435Z","iopub.execute_input":"2024-03-27T10:49:39.852870Z","iopub.status.idle":"2024-03-27T10:53:08.028032Z","shell.execute_reply.started":"2024-03-27T10:49:39.852837Z","shell.execute_reply":"2024-03-27T10:53:08.025045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ngc.collect()\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)\n","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:53:08.031662Z","iopub.execute_input":"2024-03-27T10:53:08.032692Z","iopub.status.idle":"2024-03-27T10:54:28.661801Z","shell.execute_reply.started":"2024-03-27T10:53:08.032621Z","shell.execute_reply":"2024-03-27T10:54:28.660936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nums=df_train.select_dtypes(exclude='category').columns","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:54:28.663225Z","iopub.execute_input":"2024-03-27T10:54:28.663818Z","iopub.status.idle":"2024-03-27T10:54:31.273941Z","shell.execute_reply.started":"2024-03-27T10:54:28.663787Z","shell.execute_reply":"2024-03-27T10:54:31.272922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\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","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:54:31.275570Z","iopub.execute_input":"2024-03-27T10:54:31.276066Z","iopub.status.idle":"2024-03-27T10:54:37.340092Z","shell.execute_reply.started":"2024-03-27T10:54:31.276025Z","shell.execute_reply":"2024-03-27T10:54:37.338705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_plots(Vs):\n    col = 4\n    row = len(Vs)//4+1\n    plt.figure(figsize=(20,row*5))\n    idx = df_train[~df_train[Vs[0]].isna()].index\n    for i,v in enumerate(Vs):\n        plt.subplot(row,col,i+1)\n        n = df_train[v].nunique()\n        x = np.sum(df_train.loc[idx,v]!=df_train.loc[idx,v].astype(int))\n        y = np.round(100*np.sum(df_train[v].isna())/len(df_train),2)\n        t = 'int'\n        if x!=0: t = 'float'\n        plt.title(v+' has '+str(n)+' '+t+' and '+str(y)+'% nan')\n        plt.yticks([])\n        h = plt.hist(df_train.loc[idx,v],bins=100)\n        if len(h[0])>1: plt.ylim((0,np.sort(h[0])[-2]))\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:54:37.341588Z","iopub.execute_input":"2024-03-27T10:54:37.341955Z","iopub.status.idle":"2024-03-27T10:54:37.353710Z","shell.execute_reply.started":"2024-03-27T10:54:37.341926Z","shell.execute_reply":"2024-03-27T10:54:37.352631Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Here is the code to determine whether the missing value distribution is the same. If you need to determine, run it yourself.","metadata":{}},{"cell_type":"code","source":"def check_nan(cross_features,nan_number):\n    for item in cross_features:\n        tp=(df_train[item[0]]+df_train[item[1]]).isnull().sum()-nan_number\n        print(\"check \"+item[0]+' and '+item[1]+': '+str(tp))\n'''        \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            check_nan(cross_features,k) \n            make_plots(Vs)\n    print('####### NAN count =',k)\n    print(v)'''","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:54:37.355346Z","iopub.execute_input":"2024-03-27T10:54:37.355823Z","iopub.status.idle":"2024-03-27T10:54:37.376527Z","shell.execute_reply.started":"2024-03-27T10:54:37.355785Z","shell.execute_reply":"2024-03-27T10:54:37.375226Z"},"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\ndef make_corr(Vs,Vtitle=''):\n    cols =  Vs\n    plt.figure(figsize=(15,15))\n    sns.heatmap(df_train[cols].corr(), cmap='RdBu_r', annot=True, center=0.0)\n    if Vtitle!='': plt.title(Vtitle,fontsize=14)\n    else: plt.title(Vs[0]+' - '+Vs[-1],fontsize=14)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:54:37.382658Z","iopub.execute_input":"2024-03-27T10:54:37.383051Z","iopub.status.idle":"2024-03-27T10:54:37.393424Z","shell.execute_reply.started":"2024-03-27T10:54:37.383013Z","shell.execute_reply":"2024-03-27T10:54:37.392154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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-03-27T10:54:37.395015Z","iopub.execute_input":"2024-03-27T10:54:37.395343Z","iopub.status.idle":"2024-03-27T10:54:37.405762Z","shell.execute_reply.started":"2024-03-27T10:54:37.395315Z","shell.execute_reply":"2024-03-27T10:54:37.404428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# The graph is drawn here to compare the difference in correlation before and after deleting some features","metadata":{}},{"cell_type":"code","source":"for 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.85)\n            use=reduce_group(grps)\n            make_corr(use)\n    print('####### NAN count =',k)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:54:37.407585Z","iopub.execute_input":"2024-03-27T10:54:37.408041Z","iopub.status.idle":"2024-03-27T10:57:17.917683Z","shell.execute_reply.started":"2024-03-27T10:54:37.407996Z","shell.execute_reply":"2024-03-27T10:57:17.916651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"uses=[]\nfor k,v in nans_groups.items():\n    if len(v)>1:\n            Vs = nans_groups[k]\n            #cross_features=list(combinations(Vs, 2))\n            #make_corr(Vs)\n            grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use=reduce_group(grps)\n            uses=uses+use\n            #make_corr(use)\n    else:\n        uses=uses+v\n    print('####### NAN count =',k)\nprint(uses)\nprint(len(uses))","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:57:17.919071Z","iopub.execute_input":"2024-03-27T10:57:17.919407Z","iopub.status.idle":"2024-03-27T10:57:56.779237Z","shell.execute_reply.started":"2024-03-27T10:57:17.919378Z","shell.execute_reply":"2024-03-27T10:57:56.777704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"uses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train=df_train[uses]","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:57:56.781007Z","iopub.execute_input":"2024-03-27T10:57:56.781487Z","iopub.status.idle":"2024-03-27T10:57:59.268729Z","shell.execute_reply.started":"2024-03-27T10:57:56.781436Z","shell.execute_reply":"2024-03-27T10:57:59.267465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# The goal here is to quickly debug code in the cloud space without consuming too much GPU time","metadata":{}},{"cell_type":"code","source":"sample = pd.read_csv(\"/kaggle/input/home-credit-credit-risk-model-stability/sample_submission.csv\")\ndevice='gpu'\nn_samples=200000\nDRY_RUN = True if sample.shape[0] == 10 else False   \nif DRY_RUN:\n    device='cpu'\n    df_train = df_train.iloc[:50000]\n    n_samples=10000\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:57:59.270464Z","iopub.execute_input":"2024-03-27T10:57:59.270805Z","iopub.status.idle":"2024-03-27T10:57:59.300702Z","shell.execute_reply.started":"2024-03-27T10:57:59.270776Z","shell.execute_reply":"2024-03-27T10:57:59.299593Z"},"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        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:57:59.302297Z","iopub.execute_input":"2024-03-27T10:57:59.302735Z","iopub.status.idle":"2024-03-27T10:57:59.711064Z","shell.execute_reply.started":"2024-03-27T10:57:59.302696Z","shell.execute_reply":"2024-03-27T10:57:59.709924Z"},"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()\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\nprint(\"train data shape:\\t\", df_train.shape)\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-03-27T10:57:59.713273Z","iopub.execute_input":"2024-03-27T10:57:59.714056Z","iopub.status.idle":"2024-03-27T10:58:00.298463Z","shell.execute_reply.started":"2024-03-27T10:57:59.714022Z","shell.execute_reply":"2024-03-27T10:58:00.297308Z"},"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\"])\ncv = StratifiedGroupKFold(n_splits=10, shuffle=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:58:00.299982Z","iopub.execute_input":"2024-03-27T10:58:00.301012Z","iopub.status.idle":"2024-03-27T10:58:00.468328Z","shell.execute_reply.started":"2024-03-27T10:58:00.300972Z","shell.execute_reply":"2024-03-27T10:58:00.467228Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import lightgbm as lgb","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:58:00.469758Z","iopub.execute_input":"2024-03-27T10:58:00.470140Z","iopub.status.idle":"2024-03-27T10:58:00.476229Z","shell.execute_reply.started":"2024-03-27T10:58:00.470109Z","shell.execute_reply":"2024-03-27T10:58:00.475072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,  \n    \"learning_rate\": 0.05,\n    \"n_estimators\": 2000,\n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 7,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_tres\":True,\n    'num_leaves':64,\n    \"device\": device, \n    \"min_data_in_bin\":256\n}\n\nfitted_models = []\ncv_scores = []\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#   Because it takes a long time to divide the data set, \n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# each time the data set is divided, two models are trained to each other twice, which saves time.\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n    \n    \n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_valid, y_valid,\n        eval_set = [(X_train, y_train)],\n        callbacks = [lgb.log_evaluation(200), lgb.early_stopping(60)] )\n    fitted_models.append(model)\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set = [(X_valid, y_valid)],\n        callbacks = [lgb.log_evaluation(200), lgb.early_stopping(100)] )\n    fitted_models.append(model)\n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n    \nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:58:00.478511Z","iopub.execute_input":"2024-03-27T10:58:00.479618Z","iopub.status.idle":"2024-03-27T10:59:16.082938Z","shell.execute_reply.started":"2024-03-27T10:58:00.479573Z","shell.execute_reply":"2024-03-27T10:59:16.081851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb.plot_importance(fitted_models[4], importance_type=\"split\", figsize=(10,50))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-27T11:13:35.688747Z","iopub.execute_input":"2024-03-27T11:13:35.689285Z","iopub.status.idle":"2024-03-27T11:13:39.172908Z","shell.execute_reply.started":"2024-03-27T11:13:35.689247Z","shell.execute_reply":"2024-03-27T11:13:39.171633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, ClassifierMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:59:19.476409Z","iopub.execute_input":"2024-03-27T10:59:19.477042Z","iopub.status.idle":"2024-03-27T10:59:19.484215Z","shell.execute_reply.started":"2024-03-27T10:59:19.477009Z","shell.execute_reply":"2024-03-27T10:59:19.483384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Here is the online weight calculation code in the effect and time of a piece of code, forgive me for forgetting the original author's notebook","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score\ndef gini_stability(base, w_fallingrate=88.0, w_resstd=-0.5):\n    gini_in_time = base.loc[:, [\"WEEK_NUM\", \"target\", \"score\"]]\\\n        .sort_values(\"WEEK_NUM\")\\\n        .groupby(\"WEEK_NUM\")[[\"target\", \"score\"]]\\\n        .apply(lambda x: 2*roc_auc_score(x[\"target\"], x[\"score\"])-1).tolist()\n    \n    x = np.arange(len(gini_in_time))\n    y = gini_in_time\n    a, b = np.polyfit(x, y, 1)\n    y_hat = a*x + b\n    residuals = y - y_hat\n    res_std = np.std(residuals)\n    avg_gini = np.mean(gini_in_time)\n    return avg_gini + w_fallingrate * min(0, a) + w_resstd * res_std\n\ndef stratified_sample(df, week_num_col='WEEK_NUM', target_col='target', n_samples=1000):\n    \"\"\"\n    Perform stratified sampling to ensure each combination of week number and target is represented.\n    \n    Parameters:\n    - df: pandas DataFrame containing the data.\n    - week_num_col: Name of the column containing week numbers.\n    - target_col: Name of the column containing target values.\n    - n_samples: Total number of samples to return.\n    \n    Returns:\n    - A sampled pandas DataFrame with n_samples (if possible) ensuring representation of each group.\n    \"\"\"\n    \n    samples_per_group = max(1, n_samples // df.groupby([week_num_col, target_col]).ngroups)\n    \n    sampled_df = df.groupby([week_num_col, target_col]).apply(\n        lambda x: x.sample(n=min(samples_per_group, len(x)), replace=True if len(x) < samples_per_group else False)\n    ).reset_index(drop=True)\n    \n    if len(sampled_df) < n_samples:\n        additional_samples = n_samples - len(sampled_df)\n        additional_sampled_df = df.sample(n=additional_samples, replace=True)\n        sampled_df = pd.concat([sampled_df, additional_sampled_df], ignore_index=True)\n    \n    return sampled_df\nclass WeightedVotingModel(BaseEstimator, ClassifierMixin):\n    def __init__(self, estimators, num_iters=100, scale=0.1):\n        super().__init__()\n        self.estimators = estimators\n        self.weights = np.ones(len(self.estimators)) / len(self.estimators)\n        \n        self.num_iters = num_iters\n        self.scale = scale\n        \n    def fit(self, X, y=None):\n        \n        X[\"score\"] = self.predict_proba(X.drop(columns=[\"target\", \"WEEK_NUM\"]))[:, 1]\n        last_gini = gini_stability(X)\n        \n        for itr in range(self.num_iters):\n            idx = np.random.randint(len(self.estimators))\n            \n            new_weights = self.weights\n            \n            # choose weight to change\n            delta = np.random.normal(loc=0.0, scale=self.scale)\n            if new_weights[idx] + delta >= 0:\n                new_weights[idx] += delta\n            new_weights = new_weights / new_weights.sum()\n            \n            old_weights = self.weights\n            self.weights = new_weights\n            \n            # compute new gini score\n            X[\"score\"] = self.predict_proba(X.drop(columns=[\"target\",  \"WEEK_NUM\", \"score\"]))[:, 1]\n            new_gini = gini_stability(X)\n            \n            print(f\"Iteration {itr + 1}/{self.num_iters} || last_gini: {last_gini:.5f} || new_gini: {new_gini:.5f}\")\n            \n            # choose to update the weights or not\n            if new_gini < last_gini:\n                # return old weights because old gini was better\n                self.weights = old_weights\n            else:\n                # accept new weights and change current gini\n                last_gini = new_gini\n            \n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.sum(y_preds * self.weights[:, None], axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        #print(self.weights[:, None, None])\n        return np.sum(y_preds * self.weights[:, None, None], axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:59:19.485688Z","iopub.execute_input":"2024-03-27T10:59:19.486251Z","iopub.status.idle":"2024-03-27T10:59:19.509217Z","shell.execute_reply.started":"2024-03-27T10:59:19.486222Z","shell.execute_reply":"2024-03-27T10:59:19.508374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# This is to delete the week with only one type of data to avoid errors in calculating the auc","metadata":{}},{"cell_type":"code","source":"dt=pd.DataFrame()\ndt[\"target\"]=y\ndt[\"WEEK_NUM\"]=weeks\ndt=dt.groupby(\"WEEK_NUM\").sum()\ntodrop=list(dt[dt['target']==0] .index)\nfor week in todrop:\n    df_train = df_train[weeks!=week]\n    y = y[weeks!=week]\n    weeks = weeks[weeks!=week]\ndf_train[\"target\"]=y\ndf_train[\"WEEK_NUM\"]=weeks","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:59:19.510636Z","iopub.execute_input":"2024-03-27T10:59:19.511196Z","iopub.status.idle":"2024-03-27T10:59:19.540054Z","shell.execute_reply.started":"2024-03-27T10:59:19.511166Z","shell.execute_reply":"2024-03-27T10:59:19.538792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nweighted_model = WeightedVotingModel(fitted_models, num_iters=40, scale=0.1)\ndf_almost_val = stratified_sample(df_train, n_samples=n_samples)\nweighted_model.fit(df_almost_val)\nweighted_model.weights\nsmall_train = stratified_sample(df_train, n_samples=n_samples)\n\nsmall_train['score'] = weighted_model.predict_proba(small_train.drop(columns=[\"target\", \"WEEK_NUM\"]))[:, 1]\nprint(f\"n_samples: {n_samples} || gini_stability: {gini_stability(small_train)}\")\ndf_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")\ny_pred = pd.Series(weighted_model.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-03-27T10:59:19.542029Z","iopub.execute_input":"2024-03-27T10:59:19.542609Z","iopub.status.idle":"2024-03-27T11:00:27.300888Z","shell.execute_reply.started":"2024-03-27T10:59:19.542575Z","shell.execute_reply":"2024-03-27T11:00:27.299545Z"},"trusted":true},"execution_count":null,"outputs":[]}]}