{"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":52461,"sourceType":"modelInstanceVersion","modelInstanceId":44071},{"sourceId":52462,"sourceType":"modelInstanceVersion","modelInstanceId":44072}],"dockerImageVersionId":30698,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys  # System-specific parameters and functions\nimport subprocess  # Spawn new processes, connect to their input/output/error pipes, and obtain their return codes\nimport os  # Operating system dependent functionality\nimport gc  # Garbage Collector interface\nfrom pathlib import Path  # Object-oriented filesystem paths\nfrom glob import glob  # Unix style pathname pattern expansion\n\nimport numpy as np  # Fundamental package for scientific computing with Python\nimport pandas as pd  # Powerful data structures for data manipulation and analysis\nimport polars as pl  # Fast DataFrame library implemented in Rust\n\nfrom datetime import datetime  # Basic date and time types\nimport seaborn as sns  # Statistical data visualization\nimport matplotlib.pyplot as plt  # MATLAB-like plotting framework\n\nimport joblib  # Save and load Python objects\n\nimport warnings  # Warning control\nwarnings.filterwarnings('ignore')  # Ignore warnings\n\nfrom sklearn.base import BaseEstimator, RegressorMixin  # Base classes for all estimators in scikit-learn\nfrom sklearn.metrics import roc_auc_score  # ROC AUC score\nimport lightgbm as lgb  # LightGBM: Gradient boosting framework\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold  # Cross-validation strategies\nfrom imblearn.over_sampling import SMOTE  # Oversampling technique for imbalanced datasets\nfrom sklearn.preprocessing import OrdinalEncoder  # Encode categorical features as an integer array\nfrom sklearn.impute import KNNImputer  # Imputation for completing missing values using k-Nearest Neighbors","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-20T11:07:37.356823Z","iopub.execute_input":"2024-05-20T11:07:37.357729Z","iopub.status.idle":"2024-05-20T11:07:37.367399Z","shell.execute_reply.started":"2024-05-20T11:07:37.357687Z","shell.execute_reply":"2024-05-20T11:07:37.366061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT = '/kaggle/input/home-credit-credit-risk-model-stability' ","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.369272Z","iopub.execute_input":"2024-05-20T11:07:37.370141Z","iopub.status.idle":"2024-05-20T11:07:37.380890Z","shell.execute_reply.started":"2024-05-20T11:07:37.370112Z","shell.execute_reply":"2024-05-20T11:07:37.379895Z"},"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        \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","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.382409Z","iopub.execute_input":"2024-05-20T11:07:37.383350Z","iopub.status.idle":"2024-05-20T11:07:37.393894Z","shell.execute_reply.started":"2024-05-20T11:07:37.383158Z","shell.execute_reply":"2024-05-20T11:07:37.392949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class 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","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.395964Z","iopub.execute_input":"2024-05-20T11:07:37.396550Z","iopub.status.idle":"2024-05-20T11:07:37.409072Z","shell.execute_reply.started":"2024-05-20T11:07:37.396514Z","shell.execute_reply":"2024-05-20T11:07:37.407946Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.410315Z","iopub.execute_input":"2024-05-20T11:07:37.410863Z","iopub.status.idle":"2024-05-20T11:07:37.425792Z","shell.execute_reply.started":"2024-05-20T11:07:37.410827Z","shell.execute_reply":"2024-05-20T11:07:37.424781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.427003Z","iopub.execute_input":"2024-05-20T11:07:37.427591Z","iopub.status.idle":"2024-05-20T11:07:37.438318Z","shell.execute_reply.started":"2024-05-20T11:07:37.427561Z","shell.execute_reply":"2024-05-20T11:07:37.437514Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.439926Z","iopub.execute_input":"2024-05-20T11:07:37.440551Z","iopub.status.idle":"2024-05-20T11:07:37.450380Z","shell.execute_reply.started":"2024-05-20T11:07:37.440522Z","shell.execute_reply":"2024-05-20T11:07:37.449368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.451985Z","iopub.execute_input":"2024-05-20T11:07:37.452670Z","iopub.status.idle":"2024-05-20T11:07:37.464374Z","shell.execute_reply.started":"2024-05-20T11:07:37.452631Z","shell.execute_reply":"2024-05-20T11:07:37.463473Z"},"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    \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-20T11:07:37.465755Z","iopub.execute_input":"2024-05-20T11:07:37.466049Z","iopub.status.idle":"2024-05-20T11:07:37.477187Z","shell.execute_reply.started":"2024-05-20T11:07:37.466023Z","shell.execute_reply":"2024-05-20T11:07:37.476271Z"},"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-05-20T11:07:37.481007Z","iopub.execute_input":"2024-05-20T11:07:37.481586Z","iopub.status.idle":"2024-05-20T11:07:37.491260Z","shell.execute_reply.started":"2024-05-20T11:07:37.481548Z","shell.execute_reply":"2024-05-20T11:07:37.490046Z"},"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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:07:37.492718Z","iopub.execute_input":"2024-05-20T11:07:37.493268Z","iopub.status.idle":"2024-05-20T11:08:46.213569Z","shell.execute_reply.started":"2024-05-20T11:07:37.493237Z","shell.execute_reply":"2024-05-20T11:08:46.212493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\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)\nnums=df_train.select_dtypes(exclude='category').columns\nfrom itertools import combinations, permutations\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()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:08:46.214901Z","iopub.execute_input":"2024-05-20T11:08:46.215519Z","iopub.status.idle":"2024-05-20T11:09:34.367130Z","shell.execute_reply.started":"2024-05-20T11:08:46.215483Z","shell.execute_reply":"2024-05-20T11:09:34.365708Z"},"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        use.append(vx)\n    return use","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:09:34.368618Z","iopub.execute_input":"2024-05-20T11:09:34.368967Z","iopub.status.idle":"2024-05-20T11:09:34.374827Z","shell.execute_reply.started":"2024-05-20T11:09:34.368939Z","shell.execute_reply":"2024-05-20T11:09:34.373485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def group_columns_by_correlation(matrix, threshold=0.8):\n    correlation_matrix = matrix.corr()\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-20T11:09:34.376121Z","iopub.execute_input":"2024-05-20T11:09:34.376632Z","iopub.status.idle":"2024-05-20T11:09:34.388693Z","shell.execute_reply.started":"2024-05-20T11:09:34.376602Z","shell.execute_reply":"2024-05-20T11:09:34.387718Z"},"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            grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use=reduce_group(grps)\n            uses=uses+use\n    else:\n        uses=uses+v\n\n# Subset the DataFrame to keep only the selected columns\ndf_train = df_train[uses] ","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:09:34.389810Z","iopub.execute_input":"2024-05-20T11:09:34.390680Z","iopub.status.idle":"2024-05-20T11:10:00.430772Z","shell.execute_reply.started":"2024-05-20T11:09:34.390650Z","shell.execute_reply":"2024-05-20T11:10:00.429511Z"},"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-20T11:10:00.432570Z","iopub.execute_input":"2024-05-20T11:10:00.432970Z","iopub.status.idle":"2024-05-20T11:10:00.610258Z","shell.execute_reply.started":"2024-05-20T11:10:00.432931Z","shell.execute_reply":"2024-05-20T11:10:00.609470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\ndel data_store\ngc.collect()\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\ndf_test, cat_cols = to_pandas(df_test)\ndf_test = reduce_mem_usage(df_test)\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:00.611773Z","iopub.execute_input":"2024-05-20T11:10:00.612531Z","iopub.status.idle":"2024-05-20T11:10:01.038060Z","shell.execute_reply.started":"2024-05-20T11:10:00.612491Z","shell.execute_reply":"2024-05-20T11:10:01.036781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train['target']=0\ndf_test['target']=1","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:01.039311Z","iopub.execute_input":"2024-05-20T11:10:01.039635Z","iopub.status.idle":"2024-05-20T11:10:01.047585Z","shell.execute_reply.started":"2024-05-20T11:10:01.039608Z","shell.execute_reply":"2024-05-20T11:10:01.046225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train=pd.concat([df_train,df_test])\ndf_train=reduce_mem_usage(df_train)\n\ny = df_train[\"target\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n\n\njoblib.dump((df_train,y,df_test),'data.pkl')","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:01.048950Z","iopub.execute_input":"2024-05-20T11:10:01.049332Z","iopub.status.idle":"2024-05-20T11:10:15.390384Z","shell.execute_reply.started":"2024-05-20T11:10:01.049304Z","shell.execute_reply":"2024-05-20T11:10:15.389099Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:15.391994Z","iopub.execute_input":"2024-05-20T11:10:15.392365Z","iopub.status.idle":"2024-05-20T11:10:15.403527Z","shell.execute_reply.started":"2024-05-20T11:10:15.392336Z","shell.execute_reply":"2024-05-20T11:10:15.402522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class 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":{"execution":{"iopub.status.busy":"2024-05-20T11:10:15.404827Z","iopub.execute_input":"2024-05-20T11:10:15.405368Z","iopub.status.idle":"2024-05-20T11:10:15.421133Z","shell.execute_reply.started":"2024-05-20T11:10:15.405338Z","shell.execute_reply":"2024-05-20T11:10:15.419522Z"},"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\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\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","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:15.422706Z","iopub.execute_input":"2024-05-20T11:10:15.423318Z","iopub.status.idle":"2024-05-20T11:10:15.440058Z","shell.execute_reply.started":"2024-05-20T11:10:15.423280Z","shell.execute_reply":"2024-05-20T11:10:15.439175Z"},"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":{"execution":{"iopub.status.busy":"2024-05-20T11:10:15.441295Z","iopub.execute_input":"2024-05-20T11:10:15.442382Z","iopub.status.idle":"2024-05-20T11:10:15.458251Z","shell.execute_reply.started":"2024-05-20T11:10:15.442334Z","shell.execute_reply":"2024-05-20T11:10:15.457316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb_notebook_info = joblib.load('/kaggle/input/credit-models/other/catmodels/1/notebook_info.joblib')\nprint(f\"- [lgb] notebook_start_time: {lgb_notebook_info['notebook_start_time']}\")\nprint(f\"- [lgb] description: {lgb_notebook_info['description']}\")\n\ncols = lgb_notebook_info['cols']\ncat_cols = lgb_notebook_info['cat_cols']\nprint(f\"- [lgb] len(cols): {len(cols)}\")\nprint(f\"- [lgb] len(cat_cols): {len(cat_cols)}\")\n\nlgb_models = joblib.load('/kaggle/input/credit-models/other/catmodels/1/lgb_models.joblib')\nlgb_models\n\ncat_notebook_info = joblib.load('/kaggle/input/credit-models/other/home-credit/1/notebook_info.joblib')\nprint(f\"- [cat] notebook_start_time: {cat_notebook_info['notebook_start_time']}\")\nprint(f\"- [cat] description: {cat_notebook_info['description']}\")\n\ncat_models = joblib.load('/kaggle/input/credit-models/other/home-credit/1/cat_models.joblib')\ncat_models","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:15.459750Z","iopub.execute_input":"2024-05-20T11:10:15.460841Z","iopub.status.idle":"2024-05-20T11:10:19.419472Z","shell.execute_reply.started":"2024-05-20T11:10:15.460785Z","shell.execute_reply":"2024-05-20T11:10:19.418580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\ndata_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-20T11:10:19.420511Z","iopub.execute_input":"2024-05-20T11:10:19.421299Z","iopub.status.idle":"2024-05-20T11:10:19.681325Z","shell.execute_reply.started":"2024-05-20T11:10:19.421268Z","shell.execute_reply":"2024-05-20T11:10:19.680310Z"},"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()\n\n\ndf_test = df_test.select(['case_id'] + cols)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\ndf_test = df_test.set_index('case_id')\nprint(\"test data shape:\\t\", df_test.shape)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:19.682676Z","iopub.execute_input":"2024-05-20T11:10:19.683006Z","iopub.status.idle":"2024-05-20T11:10:20.252843Z","shell.execute_reply.started":"2024-05-20T11:10:19.682976Z","shell.execute_reply":"2024-05-20T11:10:20.251703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\n    \"\"\"\n    A custom ensemble model that performs voting aggregation for predictions.\n\n    Parameters:\n    ----------\n    estimators : list\n        List of estimators (models) to be used for voting aggregation.\n\n    Methods:\n    --------\n    fit(X, y=None):\n        Fit the ensemble model. This method does nothing as it's not required for voting aggregation.\n\n    predict(X):\n        Perform prediction using voting aggregation on the provided features.\n\n    predict_proba(X):\n        Perform prediction with probabilities using voting aggregation on the provided features.\n\n    \"\"\"\n    def __init__(self, estimators):\n        \"\"\"\n        Initialize the VotingModel.\n\n        Parameters:\n        ----------\n        estimators : list\n            List of estimators (models) to be used for voting aggregation.\n        \"\"\"\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        \"\"\"\n        Fit the ensemble model.\n\n        This method does nothing as it's not required for voting aggregation.\n\n        Parameters:\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            Training data.\n        y : array-like, shape (n_samples,) (default=None)\n            Target values.\n\n        Returns:\n        --------\n        self : object\n            Returns self.\n        \"\"\"\n        return self\n    \n    def predict(self, X):\n        \"\"\"\n        Perform prediction using voting aggregation on the provided features.\n\n        Parameters:\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            Features to perform prediction on.\n\n        Returns:\n        --------\n        y_pred : array-like, shape (n_samples,)\n            Predicted target values.\n        \"\"\"\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        \"\"\"\n        Perform prediction with probabilities using voting aggregation on the provided features.\n\n        Parameters:\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            Features to perform prediction on.\n\n        Returns:\n        --------\n        y_pred_proba : array-like, shape (n_samples, n_classes)\n            Predicted probabilities.\n        \"\"\"\n        # lgb\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]\n        \n        # cat\n        X[cat_cols] = X[cat_cols].astype(str)\n        y_preds += [estimator.predict_proba(X) for estimator in self.estimators[-5:]]\n        \n        return np.mean(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:20.254380Z","iopub.execute_input":"2024-05-20T11:10:20.254884Z","iopub.status.idle":"2024-05-20T11:10:20.266084Z","shell.execute_reply.started":"2024-05-20T11:10:20.254847Z","shell.execute_reply":"2024-05-20T11:10:20.264933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = VotingModel(lgb_models + cat_models)\nlen(model.estimators)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:20.272453Z","iopub.execute_input":"2024-05-20T11:10:20.272800Z","iopub.status.idle":"2024-05-20T11:10:20.285609Z","shell.execute_reply.started":"2024-05-20T11:10:20.272774Z","shell.execute_reply":"2024-05-20T11:10:20.284326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(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\")\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"sub.csv\")\ndf_train,y,df_test=joblib.load('/kaggle/working/data.pkl')","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:20.287259Z","iopub.execute_input":"2024-05-20T11:10:20.287619Z","iopub.status.idle":"2024-05-20T11:10:21.399300Z","shell.execute_reply.started":"2024-05-20T11:10:20.287590Z","shell.execute_reply":"2024-05-20T11:10:21.398238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fitted_models_lgb=[]\nmodel = lgb.LGBMClassifier()\nmodel.fit(df_train,y)\nfitted_models_lgb.append(model)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:10:21.400994Z","iopub.execute_input":"2024-05-20T11:10:21.401490Z","iopub.status.idle":"2024-05-20T11:14:02.665617Z","shell.execute_reply.started":"2024-05-20T11:10:21.401425Z","shell.execute_reply":"2024-05-20T11:14:02.664594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\n    \"\"\"\n    A custom ensemble model for voting aggregation of predictions.\n\n    Parameters:\n    ----------\n    estimators : list\n        List of fitted estimators (models) to be used for voting aggregation.\n\n    Methods:\n    --------\n    fit(X, y=None):\n        Fit the ensemble model. This method does nothing as it's not required for voting aggregation.\n\n    predict(X):\n        Perform prediction using voting aggregation on the provided features.\n\n    predict_proba(X):\n        Perform prediction with probabilities using voting aggregation on the provided features.\n\n    \"\"\"\n    def __init__(self, estimators):\n        \"\"\"\n        Initialize the VotingModel.\n\n        Parameters:\n        ----------\n        estimators : list\n            List of fitted estimators (models) to be used for voting aggregation.\n        \"\"\"\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        \"\"\"\n        Fit the ensemble model.\n\n        This method does nothing as it's not required for voting aggregation.\n\n        Parameters:\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            Training data.\n        y : array-like, shape (n_samples,) (default=None)\n            Target values.\n\n        Returns:\n        --------\n        self : object\n            Returns self.\n        \"\"\"\n        return self\n    \n    def predict(self, X):\n        \"\"\"\n        Perform prediction using voting aggregation on the provided features.\n\n        Parameters:\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            Features to perform prediction on.\n\n        Returns:\n        --------\n        y_pred : array-like, shape (n_samples,)\n            Predicted target values.\n        \"\"\"\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        \"\"\"\n        Perform prediction with probabilities using voting aggregation on the provided features.\n\n        Parameters:\n        ----------\n        X : array-like or sparse matrix, shape (n_samples, n_features)\n            Features to perform prediction on.\n\n        Returns:\n        --------\n        y_pred_proba : array-like, shape (n_samples, n_classes)\n            Predicted probabilities.\n        \"\"\"\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_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:14:02.667240Z","iopub.execute_input":"2024-05-20T11:14:02.667852Z","iopub.status.idle":"2024-05-20T11:14:02.677831Z","shell.execute_reply.started":"2024-05-20T11:14:02.667812Z","shell.execute_reply":"2024-05-20T11:14:02.676655Z"},"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\")\n\ny_pred = pd.Series(model.predict_proba(df_test)[:,1], index=df_test.index)\ncondition=y_pred<0.98\ndf_subm = pd.read_csv(\"/kaggle/working/sub.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm.loc[condition, 'score'] = (df_subm.loc[condition, 'score'] - 0.073).clip(0)\ndf_subm.to_csv(\"submission.csv\")\n!rm -rf data.pkl","metadata":{"execution":{"iopub.status.busy":"2024-05-20T11:14:02.678980Z","iopub.execute_input":"2024-05-20T11:14:02.679269Z","iopub.status.idle":"2024-05-20T11:14:04.032111Z","shell.execute_reply.started":"2024-05-20T11:14:02.679246Z","shell.execute_reply":"2024-05-20T11:14:04.030450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}