{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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":30886,"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\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport lightgbm as lgb\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.metrics import roc_auc_score \nfrom sklearn.impute import KNNImputer\nfrom sklearn.preprocessing import OrdinalEncoder, StandardScaler, RobustScaler\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom imblearn.over_sampling import SMOTE","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-02-20T17:21:48.214796Z","iopub.execute_input":"2025-02-20T17:21:48.215189Z","iopub.status.idle":"2025-02-20T17:21:56.424498Z","shell.execute_reply.started":"2025-02-20T17:21:48.215141Z","shell.execute_reply":"2025-02-20T17:21:56.423248Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-24T01:03:59.095932Z","iopub.execute_input":"2024-05-24T01:03:59.096467Z","iopub.status.idle":"2024-05-24T01:03:59.103474Z","shell.execute_reply.started":"2024-05-24T01:03:59.096435Z","shell.execute_reply":"2024-05-24T01:03:59.100532Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Loading data","metadata":{}},{"cell_type":"code","source":"class Pipeline:\n    def set_table_dtypes(df: pl.DataFrame) -> pl.DataFrame:\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","metadata":{"execution":{"iopub.status.busy":"2024-05-24T01:04:17.09211Z","iopub.execute_input":"2024-05-24T01:04:17.092518Z","iopub.status.idle":"2024-05-24T01:04:17.104103Z","shell.execute_reply.started":"2024-05-24T01:04:17.092489Z","shell.execute_reply":"2024-05-24T01:04:17.103207Z"},"trusted":true},"outputs":[],"execution_count":null},{"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        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-05-24T01:04:19.278083Z","iopub.execute_input":"2024-05-24T01:04:19.278699Z","iopub.status.idle":"2024-05-24T01:04:19.306323Z","shell.execute_reply.started":"2024-05-24T01:04:19.27866Z","shell.execute_reply":"2024-05-24T01:04:19.305045Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Training data","metadata":{}},{"cell_type":"code","source":"%%time\ndata_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-24T01:04:23.499367Z","iopub.execute_input":"2024-05-24T01:04:23.499806Z","iopub.status.idle":"2024-05-24T01:06:44.619801Z","shell.execute_reply.started":"2024-05-24T01:04:23.499775Z","shell.execute_reply":"2024-05-24T01:06:44.618574Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%time\ndf_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()\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        use.append(vx)\n    return use\n\ndef 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\n\nuses=[]\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# print(uses)\nprint(len(uses))\nuses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train=df_train[uses]","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Test data","metadata":{}},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:31:11.291958Z","iopub.execute_input":"2024-05-22T06:31:11.292304Z","iopub.status.idle":"2024-05-22T06:31:11.69389Z","shell.execute_reply.started":"2024-05-22T06:31:11.292278Z","shell.execute_reply":"2024-05-22T06:31:11.692568Z"},"trusted":true},"outputs":[],"execution_count":null},{"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)\nweek_num = list(df_test[\"WEEK_NUM\"])\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:31:11.69541Z","iopub.execute_input":"2024-05-22T06:31:11.695865Z","iopub.status.idle":"2024-05-22T06:31:12.281172Z","shell.execute_reply.started":"2024-05-22T06:31:11.695827Z","shell.execute_reply":"2024-05-22T06:31:12.279841Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Data info","metadata":{}},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:31:12.28248Z","iopub.execute_input":"2024-05-22T06:31:12.283292Z","iopub.status.idle":"2024-05-22T06:31:13.857728Z","shell.execute_reply.started":"2024-05-22T06:31:12.283254Z","shell.execute_reply":"2024-05-22T06:31:13.856426Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)\ndf_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:31:13.859178Z","iopub.execute_input":"2024-05-22T06:31:13.859542Z","iopub.status.idle":"2024-05-22T06:31:24.515844Z","shell.execute_reply.started":"2024-05-22T06:31:13.859512Z","shell.execute_reply":"2024-05-22T06:31:24.51472Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Preprocessing","metadata":{}},{"cell_type":"code","source":"class Preprocess:\n    def drop_na_cols(df: pd.DataFrame, threshold = 0.6):\n        # Drop columns whose nan counts is above a percentage threshold\n        # done in reading file with th 0.7\n        to_drop = []\n        preserve_df = df[[\"target\", \"case_id\", \"WEEK_NUM\"]].copy()\n        for col in df.columns:\n            if df[col].isna().sum() / len(df) > threshold or df[col].isnull().sum() / len(df) > threshold:\n                to_drop.append(col)\n        df = df.drop(columns=to_drop)\n        df[[\"target\", \"case_id\", \"WEEK_NUM\"]] = preserve_df\n        return df\n    \n    def drop_na_rows(df: pd.DataFrame, threshold=0.8) -> pd.DataFrame:\n        min_non_nan_values = int((threshold) * df.shape[1])\n        df = df.dropna(thresh=min_non_nan_values)\n        return df\n    \n    def replace_inf(df: pd.DataFrame) -> pd.DataFrame:\n        numeric_cols = df.select_dtypes(include=[np.number]).columns\n        df[numeric_cols] = df[numeric_cols].applymap(lambda x: np.nan if np.isinf(x) else x)\n        return df\n\ndef transform_with_unseen(encoder, train_df, test_df, column_name):\n    known_categories = encoder.categories_[0]\n    category_mapping = {category: idx for idx, category in enumerate(known_categories)}\n    test_df[column_name] = test_df[column_name].map(category_mapping)\n    \n    for cat_feature in cat_cols:\n        all_categories = list(set(train_df[cat_feature].unique()) | set(test_df[cat_feature].unique()))\n        train_df[cat_feature] = pd.Categorical(train_df[cat_feature], categories=all_categories)\n        test_df[cat_feature] = pd.Categorical(test_df[cat_feature], categories=all_categories)\n    \n    return test_df\n\ndef fill_df(df: pd.DataFrame, df_test: pd.DataFrame) -> pd.DataFrame:\n        for col in df.columns:\n            if df[col].dtype != 'object' and df[col].dtype != 'string' and df[col].dtype != 'category':\n                if not np.isnan(df[col].mean()):\n                    df[col] = df[col].fillna(df[col].mean().astype(df[col].dtype))\n                    df_test[col] = df_test[col].fillna(df_test[col].mean().astype(df_test[col].dtype))\n                else:\n                    df[col] = df[col].fillna(0)\n                    df_test[col] = df_test[col].fillna(0)\n            else:\n                df[col] = df[col].bfill().ffill()\n                df_test[col] = df_test[col].bfill().ffill()\n        return df, df_test\n    \ndef label_encode(df: pd.DataFrame, df_test: pd.DataFrame) -> pd.DataFrame:\n    enc = OrdinalEncoder(dtype=np.int16, handle_unknown='use_encoded_value', unknown_value=-1)\n    #imputer = SimpleImputer(strategy='constant', fill_value='unseen')\n    # Learn the encoding of train set -> apply to test set\n    for col in df.columns:\n        if df[col].dtype == 'object' or df[col].dtype == 'string' or df[col].dtype == 'category':\n            df[col] = enc.fit_transform(df[col].values.reshape(-1, 1)).flatten()\n            #imputer.fit_transform(df_test[col])\n            df_test[col] = enc.transform(df_test[col].values.reshape(-1, 1)).flatten()\n    return df, df_test\n    \ndef scale_numeric(df: pd.DataFrame, df_test: pd.DataFrame) -> pd.DataFrame:\n    scaler = RobustScaler()\n    # Learn the scaling parameter of train set -> apply to test set\n    for col in df.columns:\n        if df[col].dtype != 'object' and df[col].dtype != 'string' and df[col].dtype != 'category':\n            threshold = df[col].quantile(0.95)\n            df[col] = np.where(df[col] > threshold, threshold, df[col])\n            df[col] = scaler.fit_transform(df[col].values.reshape(-1, 1)).flatten().astype(df[col].dtype)\n            df_test[col] = scaler.transform(df_test[col].values.reshape(-1, 1)).flatten()\n    return df, df_test","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:31:24.517375Z","iopub.execute_input":"2024-05-22T06:31:24.517773Z","iopub.status.idle":"2024-05-22T06:31:24.533474Z","shell.execute_reply.started":"2024-05-22T06:31:24.51774Z","shell.execute_reply":"2024-05-22T06:31:24.532525Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train = df_train.iloc[:800000]\ndf_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:31:24.535081Z","iopub.execute_input":"2024-05-22T06:31:24.535576Z","iopub.status.idle":"2024-05-22T06:31:24.557348Z","shell.execute_reply.started":"2024-05-22T06:31:24.535542Z","shell.execute_reply":"2024-05-22T06:31:24.556086Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%time\ndf_train = (\n                df_train.pipe(Preprocess.drop_na_rows)\n                    .pipe(Preprocess.drop_na_cols)\n                    .pipe(Preprocess.replace_inf)\n            )\ndf_train = df_train.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:31:24.558938Z","iopub.execute_input":"2024-05-22T06:31:24.560015Z","iopub.status.idle":"2024-05-22T06:36:35.264001Z","shell.execute_reply.started":"2024-05-22T06:31:24.559979Z","shell.execute_reply":"2024-05-22T06:36:35.26274Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train = reduce_mem_usage(df_train)","metadata":{},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=4, shuffle=False)","metadata":{},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%time\ndf_test = df_test[df_train.columns]\ndf_train, df_test = fill_df(df_train, df_test)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T06:36:35.269371Z","iopub.execute_input":"2024-05-22T06:36:35.269785Z","iopub.status.idle":"2024-05-22T06:36:35.289766Z","shell.execute_reply.started":"2024-05-22T06:36:35.269752Z","shell.execute_reply":"2024-05-22T06:36:35.288746Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test = df_test.pipe(Preprocess.replace_inf)\ndf_train, df_test = scale_numeric(df_train, df_test)","metadata":{},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test = reduce_mem_usage(df_test)","metadata":{},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train, df_test = label_encode(df_train, df_test)","metadata":{},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Feature selection","metadata":{}},{"cell_type":"code","source":"y = y[:800000]\ny.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:25:45.795023Z","iopub.execute_input":"2024-05-22T10:25:45.795439Z","iopub.status.idle":"2024-05-22T10:25:45.803582Z","shell.execute_reply.started":"2024-05-22T10:25:45.79541Z","shell.execute_reply":"2024-05-22T10:25:45.8025Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.datasets import make_classification\nrf = RandomForestClassifier(n_estimators=100, random_state=42)\nrf.fit(df_train, y)\n\n# Get feature importances\nimportances = rf.feature_importances_\n\n# Sort feature importances in descending order\nindices = (-importances).argsort()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:25:47.577374Z","iopub.execute_input":"2024-05-22T10:25:47.577804Z","iopub.status.idle":"2024-05-22T10:41:56.240344Z","shell.execute_reply.started":"2024-05-22T10:25:47.57777Z","shell.execute_reply":"2024-05-22T10:41:56.239027Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.figure(figsize=(60, 6)) \nplt.bar(range(df_train.shape[1]), importances[indices], color='skyblue', align='center')\nplt.xticks(range(df_train.shape[1]), indices, rotation=90)  # Rotate x-axis labels by 90 degrees\nplt.xlabel('Feature Index')\nplt.ylabel('Feature Importance')\nplt.title('Feature Importances')\nplt.tight_layout()  # Adjust layout to prevent clipping of labels\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:45:20.977806Z","iopub.execute_input":"2024-05-22T10:45:20.978443Z","iopub.status.idle":"2024-05-22T10:45:24.544078Z","shell.execute_reply.started":"2024-05-22T10:45:20.978398Z","shell.execute_reply":"2024-05-22T10:45:24.542709Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import numpy as np\n\n# # Select top 6 features\n# top_n = 200\n# selected_features = indices[:top_n]\n\n# print(\"\\nSelected features:\", selected_features)\n\n# # Extract the top 6 features from the training data\n# df_train_selected = df_train.iloc[:, selected_features]\n# print(df_train_selected)\n# print(\"\\nShape of df_train_selected:\", df_train_selected.shape)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:48:34.321168Z","iopub.execute_input":"2024-05-22T10:48:34.321697Z","iopub.status.idle":"2024-05-22T10:48:34.331246Z","shell.execute_reply.started":"2024-05-22T10:48:34.321661Z","shell.execute_reply":"2024-05-22T10:48:34.329849Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### SMOTE for imbalance handling\n> No improvement","metadata":{}},{"cell_type":"markdown","source":"# Training with baseline model (LightGBM)","metadata":{}},{"cell_type":"code","source":"params = [{\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 12,\n    \"num_leaves\": 32,\n    \"learning_rate\": 0.03,\n    \"n_estimators\": 2000,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\": True,\n    \"num_boost_round\": 400,\n    \"verbose\": -1,\n}, {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"num_leaves\": 64,\n    \"learning_rate\": 0.05,\n    \"n_estimators\": 2000,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\": True,\n    \"num_boost_round\": 300,\n    \"verbose\": -1,\n}]","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:49:20.570348Z","iopub.execute_input":"2024-05-22T10:49:20.570801Z","iopub.status.idle":"2024-05-22T10:49:20.578583Z","shell.execute_reply.started":"2024-05-22T10:49:20.57077Z","shell.execute_reply":"2024-05-22T10:49:20.577166Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"weeks = weeks[:800000]\nweeks.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:49:22.73442Z","iopub.execute_input":"2024-05-22T10:49:22.73485Z","iopub.status.idle":"2024-05-22T10:49:22.74555Z","shell.execute_reply.started":"2024-05-22T10:49:22.734815Z","shell.execute_reply":"2024-05-22T10:49:22.744426Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def cal(df_train,y,weeks,params):\n    fitted_models_lgb = []\n    cv_scores_lgb = []\n\n    iterator = 0\n    for idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n        X_train, y_train = df_train_selected.iloc[idx_train], y.iloc[idx_train]\n        X_valid, y_valid = df_train_selected.iloc[idx_valid], y.iloc[idx_valid]\n\n        if iterator % 2 == 0:\n            model = lgb.LGBMClassifier(**params[0])\n        else:\n            model = lgb.LGBMClassifier(**params[1])\n        model.fit(\n            X_train, y_train,\n            eval_set = [(X_valid, y_valid)],\n            callbacks = [lgb.log_evaluation(50), lgb.early_stopping(50)] )\n\n        fitted_models_lgb.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_lgb.append(auc_score)\n\n        iterator += 1\n\n    print(\"CV AUC scores: \", cv_scores_lgb)\n    print(\"Maximum CV AUC score: \", max(cv_scores_lgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:49:24.747815Z","iopub.execute_input":"2024-05-22T10:49:24.748473Z","iopub.status.idle":"2024-05-22T10:49:24.757197Z","shell.execute_reply.started":"2024-05-22T10:49:24.748442Z","shell.execute_reply":"2024-05-22T10:49:24.755851Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(250,350,10):\n    print(i)\n    selected_features = indices[:i]\n    df_train_selected = df_train.iloc[:, selected_features]\n    cal(df_train_selected,y,weeks,params)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T10:49:38.071005Z","iopub.execute_input":"2024-05-22T10:49:38.071519Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Ensemble","metadata":{}},{"cell_type":"code","source":"class EnsembleModel(BaseEstimator, RegressorMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(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        \n        return np.mean(y_preds, axis=0)\n\nmodel = EnsembleModel(fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T16:45:51.221426Z","iopub.status.idle":"2024-05-19T16:45:51.222172Z","shell.execute_reply.started":"2024-05-19T16:45:51.22191Z","shell.execute_reply":"2024-05-19T16:45:51.221929Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"y_pred = model.predict_proba(df_test)[:, 1]\ny_pred","metadata":{"execution":{"iopub.status.busy":"2024-05-19T16:45:51.223533Z","iopub.status.idle":"2024-05-19T16:45:51.224631Z","shell.execute_reply.started":"2024-05-19T16:45:51.224362Z","shell.execute_reply":"2024-05-19T16:45:51.224393Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"subm_df = pd.read_csv(ROOT / \"sample_submission.csv\")\nsubm_df = subm_df.set_index(\"case_id\")","metadata":{"execution":{"iopub.status.busy":"2024-05-19T16:45:51.226199Z","iopub.status.idle":"2024-05-19T16:45:51.226659Z","shell.execute_reply.started":"2024-05-19T16:45:51.226457Z","shell.execute_reply":"2024-05-19T16:45:51.226474Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"subm_df[\"score\"] = y_pred\nsubm_df[\"WEEK_NUM\"] = week_num\nprint(\"Check null: \", subm_df[\"score\"].isnull().any())","metadata":{"execution":{"iopub.status.busy":"2024-05-19T16:45:51.228569Z","iopub.status.idle":"2024-05-19T16:45:51.228953Z","shell.execute_reply.started":"2024-05-19T16:45:51.228761Z","shell.execute_reply":"2024-05-19T16:45:51.228776Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"condition = subm_df[\"WEEK_NUM\"] < (subm_df[\"WEEK_NUM\"].max() - subm_df[\"WEEK_NUM\"].min())/2 + subm_df[\"WEEK_NUM\"].min() \nsubm_df.loc[condition, 'score'] = (subm_df.loc[condition, 'score'] - 0.02).clip(0)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T16:45:51.229808Z","iopub.status.idle":"2024-05-19T16:45:51.230268Z","shell.execute_reply.started":"2024-05-19T16:45:51.230059Z","shell.execute_reply":"2024-05-19T16:45:51.230083Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"del subm_df[\"WEEK_NUM\"]\nsubm_df.to_csv(\"submission.csv\")\nsubm_df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T16:45:51.231621Z","iopub.status.idle":"2024-05-19T16:45:51.23205Z","shell.execute_reply.started":"2024-05-19T16:45:51.231824Z","shell.execute_reply":"2024-05-19T16:45:51.231841Z"},"trusted":true},"outputs":[],"execution_count":null}]}