{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"},{"sourceId":8405978,"sourceType":"datasetVersion","datasetId":4976625},{"sourceId":177639500,"sourceType":"kernelVersion"}],"dockerImageVersionId":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nimport lightgbm as lgb","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-23T16:30:44.307033Z","iopub.execute_input":"2024-05-23T16:30:44.307844Z","iopub.status.idle":"2024-05-23T16:30:51.011201Z","shell.execute_reply.started":"2024-05-23T16:30:44.307811Z","shell.execute_reply":"2024-05-23T16:30:51.010428Z"},"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 transform_cols(df: pl.DataFrame) -> pl.DataFrame:\n        \"\"\"\n        Transforms columns in the DataFrame according to predefined rules.\n\n        Args:\n        - df (pl.DataFrame): Input DataFrame.\n\n        Returns:\n        - pl.DataFrame: DataFrame with transformed columns.\n        \"\"\"\n        if \"riskassesment_302T\" in df.columns:\n            if df[\"riskassesment_302T\"].dtype == pl.Null:\n                df = df.with_columns(\n                    [\n                        pl.Series(\n                            \"riskassesment_302T_rng\", df[\"riskassesment_302T\"], pl.UInt8\n                        ),\n                        pl.Series(\n                            \"riskassesment_302T_mean\", df[\"riskassesment_302T\"], pl.UInt8\n                        ),\n                    ]\n                )\n            else:\n                pct_low: pl.Series = (\n                    df[\"riskassesment_302T\"]\n                    .str.split(\" - \")\n                    .apply(lambda x: x[0].replace(\"%\", \"\"))\n                    .cast(pl.UInt8)\n                )\n                pct_high: pl.Series = (\n                    df[\"riskassesment_302T\"]\n                    .str.split(\" - \")\n                    .apply(lambda x: x[1].replace(\"%\", \"\"))\n                    .cast(pl.UInt8)\n                )\n\n                diff: pl.Series = pct_high - pct_low\n                avg: pl.Series = ((pct_low + pct_high) / 2).cast(pl.Float32)\n\n                del pct_high, pct_low\n                gc.collect()\n\n                df = df.with_columns(\n                    [\n                        diff.alias(\"riskassesment_302T_rng\"),\n                        avg.alias(\"riskassesment_302T_mean\"),\n                    ]\n                )\n\n            df.drop(\"riskassesment_302T\")\n\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        for col in df.columns:\n            if col[-1] == \"C\":\n                if (df[col] == 0).mean() > 0.9:\n                    df = df.drop(col)\n        \n        return df\n\ncategories = {}\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        \n        #--------------------------------\n        expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        expr_var = [pl.var(col).alias(f\"var_{col}\") for col in cols]\n\n#         expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n#         expr_median = [pl.median(col).alias(f\"median_{col}\") for col in cols]\n        #--------------------------------\n        \n        \n        return expr_max +expr_last+expr_mean#+expr_var+expr_count#+expr_min+expr_median\n    \n    def cat_expr(df, test=False):\n        agg_cols = []\n        if test:\n            cat_cols = categories.keys()\n            for col in df.columns:\n                if col in cat_cols:\n                    for value in categories[col]:\n                        agg_cols += [pl.col(col).filter(pl.col(col) == value).count().alias(f\"{col}_{value}_C\")]\n        else:\n            for col in df.select([pl.col(pl.String), pl.col(pl.Boolean)]).columns:\n                values = df[col].unique().to_list()\n                if len(values) <= 10 and df[col].is_null().mean() < 0.9:\n                    try:\n                        categories[col] = list(set(categories[col] + values))\n                    except:\n                        categories[col] = values\n                    for value in values:\n                        agg_cols += [pl.col(col).filter(pl.col(col) == value).count().alias(f\"{col}_{value}_C\")]\n\n        return agg_cols\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        \n        #--------------------------------\n#         expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n#         expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        #--------------------------------\n        \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\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        \n        #--------------------------------\n        expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        #--------------------------------\n        \n        return  expr_max +expr_last#+expr_count\n    \n    def get_exprs(df, test=False, cat_cols=False):\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        if cat_cols:\n            exprs += Aggregator.cat_expr(df, test)\n\n        return exprs\n\ndef read_file(path, depth=None, test=False, cat_cols=False):\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, test, cat_cols)) \n    return df\n\ndef read_files(regex_path, depth=None, test=False, cat_cols=False):\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, test, cat_cols))\n        chunks.append(df)\n    \n    df = pl.concat(chunks, how=\"diagonal_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-23T16:30:51.012770Z","iopub.execute_input":"2024-05-23T16:30:51.013171Z","iopub.status.idle":"2024-05-23T16:30:51.065330Z","shell.execute_reply.started":"2024-05-23T16:30:51.013145Z","shell.execute_reply":"2024-05-23T16:30:51.064541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = joblib.load(\"/kaggle/input/home-credit-feature-engineering/df_train.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:30:51.066588Z","iopub.execute_input":"2024-05-23T16:30:51.067206Z","iopub.status.idle":"2024-05-23T16:31:00.065217Z","shell.execute_reply.started":"2024-05-23T16:30:51.067173Z","shell.execute_reply":"2024-05-23T16:31:00.064442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat_cols = joblib.load(\"/kaggle/input/home-credit-feature-engineering/cat_columns.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:00.067335Z","iopub.execute_input":"2024-05-23T16:31:00.067659Z","iopub.status.idle":"2024-05-23T16:31:00.074853Z","shell.execute_reply.started":"2024-05-23T16:31:00.067633Z","shell.execute_reply":"2024-05-23T16:31:00.074122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"categories = joblib.load(\"/kaggle/input/home-credit-feature-engineering/categories.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:00.075849Z","iopub.execute_input":"2024-05-23T16:31:00.076099Z","iopub.status.idle":"2024-05-23T16:31:00.096162Z","shell.execute_reply.started":"2024-05-23T16:31:00.076077Z","shell.execute_reply":"2024-05-23T16:31:00.095349Z"},"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-23T16:31:00.097201Z","iopub.execute_input":"2024-05-23T16:31:00.097521Z","iopub.status.idle":"2024-05-23T16:31:00.102090Z","shell.execute_reply.started":"2024-05-23T16:31:00.097490Z","shell.execute_reply":"2024-05-23T16:31:00.101214Z"},"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, True, True),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1, True),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1, True),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1, True),\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1, True),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1, True),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1, True),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1, True),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1, True),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1, True),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2, True),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2, True),\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2, True),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2, True)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:00.103145Z","iopub.execute_input":"2024-05-23T16:31:00.103482Z","iopub.status.idle":"2024-05-23T16:31:00.534286Z","shell.execute_reply.started":"2024-05-23T16:31:00.103450Z","shell.execute_reply":"2024-05-23T16:31:00.533335Z"},"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()","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:00.535530Z","iopub.execute_input":"2024-05-23T16:31:00.535872Z","iopub.status.idle":"2024-05-23T16:31:00.745959Z","shell.execute_reply.started":"2024-05-23T16:31:00.535840Z","shell.execute_reply":"2024-05-23T16:31:00.744899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"chunks = []\n\nfor path in glob(str(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\")):\n    print(path)\n    df = pl.read_parquet(path, columns=[\"case_id\", \"num_group1\", \"pmts_month_158T\", \"pmts_month_706T\"])\n    df = df.group_by([\"case_id\", \"num_group1\"]).agg(\n        pl.count(\"pmts_month_158T\").alias(\"count_pmts_month_158T\"),\n        pl.count(\"pmts_month_706T\").alias(\"count_pmts_month_706T\"),\n    ).group_by(\"case_id\").agg(\n        pl.when(pl.col(\"count_pmts_month_158T\") > 0).then(pl.col(\"count_pmts_month_158T\")).otherwise(None).min().alias(\"min_count_pmts_month_158T\"),\n        pl.when(pl.col(\"count_pmts_month_158T\") > 0).then(pl.col(\"count_pmts_month_158T\")).otherwise(None).max().alias(\"max_count_pmts_month_158T\"),\n        pl.when(pl.col(\"count_pmts_month_158T\") > 0).then(pl.col(\"count_pmts_month_158T\")).otherwise(None).mean().alias(\"mean_count_pmts_month_158T\"),\n        pl.when(pl.col(\"count_pmts_month_158T\") > 0).then(pl.col(\"count_pmts_month_158T\")).otherwise(None).std().alias(\"std_count_pmts_month_158T\"),\n        pl.when(pl.col(\"count_pmts_month_706T\") > 0).then(pl.col(\"count_pmts_month_706T\")).otherwise(None).min().alias(\"min_count_pmts_month_706T\"),\n        pl.when(pl.col(\"count_pmts_month_706T\") > 0).then(pl.col(\"count_pmts_month_706T\")).otherwise(None).max().alias(\"max_count_pmts_month_706T\"),\n        pl.when(pl.col(\"count_pmts_month_706T\") > 0).then(pl.col(\"count_pmts_month_706T\")).otherwise(None).mean().alias(\"mean_count_pmts_month_706T\"),\n        pl.when(pl.col(\"count_pmts_month_706T\") > 0).then(pl.col(\"count_pmts_month_706T\")).otherwise(None).std().alias(\"std_count_pmts_month_706T\"),\n#         [f(pl.when(pl.col(col) > 0).then(pl.col(col)).otherwise(None)).alias(f\"{agg}_{col}\") for f, agg in [(pl.max, \"max\"), (pl.min, \"min\"), (pl.mean, \"mean\")] for col in [\"count_pmts_month_158T\", \"count_pmts_month_706T\"]]\n    )\n    chunks.append(df)\n\ncredit_bureau_a_2_feats = pl.concat(chunks, how=\"diagonal_relaxed\")\ncredit_bureau_a_2_feats = credit_bureau_a_2_feats.unique(subset=[\"case_id\"])\n\ndel df\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:00.747329Z","iopub.execute_input":"2024-05-23T16:31:00.747640Z","iopub.status.idle":"2024-05-23T16:31:00.898192Z","shell.execute_reply.started":"2024-05-23T16:31:00.747617Z","shell.execute_reply":"2024-05-23T16:31:00.897311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Selection","metadata":{}},{"cell_type":"code","source":"df_test = df_test.pipe(Pipeline.transform_cols)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:00.901608Z","iopub.execute_input":"2024-05-23T16:31:00.901862Z","iopub.status.idle":"2024-05-23T16:31:00.909848Z","shell.execute_reply.started":"2024-05-23T16:31:00.901841Z","shell.execute_reply":"2024-05-23T16:31:00.908923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.join(credit_bureau_a_2_feats, how=\"left\", on=\"case_id\")","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:00.910769Z","iopub.execute_input":"2024-05-23T16:31:00.911060Z","iopub.status.idle":"2024-05-23T16:31:00.920243Z","shell.execute_reply.started":"2024-05-23T16:31:00.911037Z","shell.execute_reply":"2024-05-23T16:31:00.919426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.select([col for col in df_train.columns if col not in [\"target\", \"date_decision\"]])\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-05-23T16:31:00.921370Z","iopub.execute_input":"2024-05-23T16:31:00.921656Z","iopub.status.idle":"2024-05-23T16:31:01.278773Z","shell.execute_reply.started":"2024-05-23T16:31:00.921633Z","shell.execute_reply":"2024-05-23T16:31:01.277895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oof_df = df_train[[\"case_id\", \"WEEK_NUM\", \"target\"]]","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:01.279991Z","iopub.execute_input":"2024-05-23T16:31:01.280262Z","iopub.status.idle":"2024-05-23T16:31:01.303561Z","shell.execute_reply.started":"2024-05-23T16:31:01.280237Z","shell.execute_reply":"2024-05-23T16:31:01.302696Z"},"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=5, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:01.304711Z","iopub.execute_input":"2024-05-23T16:31:01.304992Z","iopub.status.idle":"2024-05-23T16:31:03.187817Z","shell.execute_reply.started":"2024-05-23T16:31:01.304968Z","shell.execute_reply":"2024-05-23T16:31:03.186815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-23T16:31:03.189068Z","iopub.execute_input":"2024-05-23T16:31:03.189434Z","iopub.status.idle":"2024-05-23T16:31:12.908392Z","shell.execute_reply.started":"2024-05-23T16:31:03.189401Z","shell.execute_reply":"2024-05-23T16:31:12.907531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\n    \"booster\": \"gbtree\",\n    \"objective\": \"binary:logistic\",\n    \"eval_metric\": \"auc\",\n    \"max_depth\": 10,\n    \"learning_rate\": 0.05,\n    \"n_estimators\": 1000,\n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"alpha\": 0.1,  \n    \"lambda\": 10,  \n    \"tree_method\": 'gpu_hist',\n    \"random_state\": 42,\n    \"verbosity\": 0,\n    \"enable_categorical\":True,\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:12.909484Z","iopub.execute_input":"2024-05-23T16:31:12.909736Z","iopub.status.idle":"2024-05-23T16:31:12.915348Z","shell.execute_reply.started":"2024-05-23T16:31:12.909714Z","shell.execute_reply":"2024-05-23T16:31:12.914255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nimport xgboost as xgb\n\nfitted_models_xgb = []\n\ncv_scores_xgb = []\n\noof_pred = np.zeros(df_train.shape[0])\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# \n    X_valid, y_valid, week_valid = df_train.iloc[idx_valid], y.iloc[idx_valid], weeks[idx_valid]\n    \n    X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n    X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\n    \n    model = xgb.XGBClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid)],\n        early_stopping_rounds=100, verbose=200)\n    \n    fitted_models_xgb.append(model)\n    \n    y_pred_valid = model.predict_proba(X_valid)[:, 1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_xgb.append(auc_score)\n    oof_pred[idx_valid] = y_pred_valid\n    \n    del model\n    gc.collect()\n    \nprint(\"CV AUC scores: \", cv_scores_xgb)\nprint(\"Average CV AUC score: \", np.mean(cv_scores_xgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:12.916924Z","iopub.execute_input":"2024-05-23T16:31:12.917233Z","iopub.status.idle":"2024-05-23T16:31:23.975987Z","shell.execute_reply.started":"2024-05-23T16:31:12.917209Z","shell.execute_reply":"2024-05-23T16:31:23.975044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:23.977007Z","iopub.execute_input":"2024-05-23T16:31:23.977265Z","iopub.status.idle":"2024-05-23T16:31:23.984113Z","shell.execute_reply.started":"2024-05-23T16:31:23.977237Z","shell.execute_reply":"2024-05-23T16:31:23.983163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oof_df[\"score\"] = oof_pred\ngini_score = gini_stability(oof_df)\nprint(\"gini_score:\\t\", gini_score)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:23.985641Z","iopub.execute_input":"2024-05-23T16:31:23.986027Z","iopub.status.idle":"2024-05-23T16:31:24.556844Z","shell.execute_reply.started":"2024-05-23T16:31:23.985994Z","shell.execute_reply":"2024-05-23T16:31:24.555743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(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        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models_xgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:24.558161Z","iopub.execute_input":"2024-05-23T16:31:24.558443Z","iopub.status.idle":"2024-05-23T16:31:24.565704Z","shell.execute_reply.started":"2024-05-23T16:31:24.558421Z","shell.execute_reply":"2024-05-23T16:31:24.564835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(oof_pred, \"oof_pred.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:24.566817Z","iopub.execute_input":"2024-05-23T16:31:24.567135Z","iopub.status.idle":"2024-05-23T16:31:24.589899Z","shell.execute_reply.started":"2024-05-23T16:31:24.567104Z","shell.execute_reply":"2024-05-23T16:31:24.589075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(model, \"model.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:24.590844Z","iopub.execute_input":"2024-05-23T16:31:24.591106Z","iopub.status.idle":"2024-05-23T16:31:24.597290Z","shell.execute_reply.started":"2024-05-23T16:31:24.591083Z","shell.execute_reply":"2024-05-23T16:31:24.596454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(cat_cols, \"cat_columns.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:24.598458Z","iopub.execute_input":"2024-05-23T16:31:24.598740Z","iopub.status.idle":"2024-05-23T16:31:24.608264Z","shell.execute_reply.started":"2024-05-23T16:31:24.598717Z","shell.execute_reply":"2024-05-23T16:31:24.607327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")\n\ndf_test[cat_cols] = df_test[cat_cols].astype(\"category\")\n\ny_pred = pd.Series(model.predict_proba(df_test)[:, 1], index=df_test.index)\n\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm[\"score\"] = y_pred.values\ndf_subm.to_csv(\"submission.csv\", index=False) \ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:24.609347Z","iopub.execute_input":"2024-05-23T16:31:24.609649Z","iopub.status.idle":"2024-05-23T16:31:25.480335Z","shell.execute_reply.started":"2024-05-23T16:31:24.609627Z","shell.execute_reply":"2024-05-23T16:31:25.479091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import shap\n# explainer = shap.TreeExplainer(model.estimators[4])\n# shap_values = explainer.shap_values(X_valid)\n\n# shap.summary_plot(shap_values=shap_values, \n#                   feature_names=X_valid.columns, \n#                   plot_type=\"dot\", \n#                   max_display=40, \n#                   plot_size=(17,17),\n#                   features=X_valid)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T16:31:25.481119Z","iopub.status.idle":"2024-05-23T16:31:25.481454Z","shell.execute_reply.started":"2024-05-23T16:31:25.481278Z","shell.execute_reply":"2024-05-23T16:31:25.481291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}