{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"},{"sourceId":8405978,"sourceType":"datasetVersion","datasetId":4976625,"isSourceIdPinned":true},{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-22T15:48:22.831830Z","iopub.execute_input":"2024-05-22T15:48:22.832103Z","iopub.status.idle":"2024-05-22T15:48:27.554338Z","shell.execute_reply.started":"2024-05-22T15:48:22.832078Z","shell.execute_reply":"2024-05-22T15:48:27.553289Z"},"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-22T15:48:31.988018Z","iopub.execute_input":"2024-05-22T15:48:31.988468Z","iopub.status.idle":"2024-05-22T15:48:32.040669Z","shell.execute_reply.started":"2024-05-22T15:48:31.988442Z","shell.execute_reply":"2024-05-22T15:48:32.039822Z"},"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-22T15:54:17.273091Z","iopub.execute_input":"2024-05-22T15:54:17.273752Z","iopub.status.idle":"2024-05-22T15:54:19.080736Z","shell.execute_reply.started":"2024-05-22T15:54:17.273718Z","shell.execute_reply":"2024-05-22T15:54:19.079915Z"},"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-22T15:54:19.082264Z","iopub.execute_input":"2024-05-22T15:54:19.082574Z","iopub.status.idle":"2024-05-22T15:54:19.087868Z","shell.execute_reply.started":"2024-05-22T15:54:19.082549Z","shell.execute_reply":"2024-05-22T15:54:19.086886Z"},"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-22T15:54:19.089162Z","iopub.execute_input":"2024-05-22T15:54:19.089566Z","iopub.status.idle":"2024-05-22T15:54:19.101994Z","shell.execute_reply.started":"2024-05-22T15:54:19.089534Z","shell.execute_reply":"2024-05-22T15:54:19.101062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = df_train.drop(columns=['riskassesment_940T', 'riskassesment_302T_mean', 'riskassesment_302T_rng'])","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:54:19.104339Z","iopub.execute_input":"2024-05-22T15:54:19.104651Z","iopub.status.idle":"2024-05-22T15:54:20.435446Z","shell.execute_reply.started":"2024-05-22T15:54:19.104618Z","shell.execute_reply":"2024-05-22T15:54:20.434473Z"},"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-22T15:54:20.436676Z","iopub.execute_input":"2024-05-22T15:54:20.436968Z","iopub.status.idle":"2024-05-22T15:54:20.442533Z","shell.execute_reply.started":"2024-05-22T15:54:20.436942Z","shell.execute_reply":"2024-05-22T15:54:20.441780Z"},"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-22T15:54:20.444096Z","iopub.execute_input":"2024-05-22T15:54:20.444452Z","iopub.status.idle":"2024-05-22T15:54:20.713369Z","shell.execute_reply.started":"2024-05-22T15:54:20.444421Z","shell.execute_reply":"2024-05-22T15:54:20.712665Z"},"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-22T15:54:20.714448Z","iopub.execute_input":"2024-05-22T15:54:20.714729Z","iopub.status.idle":"2024-05-22T15:54:20.972395Z","shell.execute_reply.started":"2024-05-22T15:54:20.714706Z","shell.execute_reply":"2024-05-22T15:54:20.971441Z"},"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_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#         [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-22T15:54:20.973609Z","iopub.execute_input":"2024-05-22T15:54:20.973880Z","iopub.status.idle":"2024-05-22T15:54:21.193448Z","shell.execute_reply.started":"2024-05-22T15:54:20.973857Z","shell.execute_reply":"2024-05-22T15:54:21.192623Z"},"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-22T15:54:21.196270Z","iopub.execute_input":"2024-05-22T15:54:21.196777Z","iopub.status.idle":"2024-05-22T15:54:21.202330Z","shell.execute_reply.started":"2024-05-22T15:54:21.196746Z","shell.execute_reply":"2024-05-22T15:54:21.201312Z"},"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-22T15:54:21.203566Z","iopub.execute_input":"2024-05-22T15:54:21.203859Z","iopub.status.idle":"2024-05-22T15:54:21.215867Z","shell.execute_reply.started":"2024-05-22T15:54:21.203834Z","shell.execute_reply":"2024-05-22T15:54:21.215153Z"},"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-22T15:54:21.216916Z","iopub.execute_input":"2024-05-22T15:54:21.217171Z","iopub.status.idle":"2024-05-22T15:54:21.644300Z","shell.execute_reply.started":"2024-05-22T15:54:21.217149Z","shell.execute_reply":"2024-05-22T15:54:21.643342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv(\"/kaggle/input/home-credit-credit-risk-model-stability/sample_submission.csv\")\nn_est=6000\nDRY_RUN = True if sample.shape[0] == 10 else False   \n# if DRY_RUN:\n#     df_train = df_train.iloc[:50000]\n#     n_est=600","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:54:21.645739Z","iopub.execute_input":"2024-05-22T15:54:21.646377Z","iopub.status.idle":"2024-05-22T15:54:21.664535Z","shell.execute_reply.started":"2024-05-22T15:54:21.646340Z","shell.execute_reply":"2024-05-22T15:54:21.663552Z"},"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-22T15:54:21.667279Z","iopub.execute_input":"2024-05-22T15:54:21.667756Z","iopub.status.idle":"2024-05-22T15:54:21.674003Z","shell.execute_reply.started":"2024-05-22T15:54:21.667711Z","shell.execute_reply":"2024-05-22T15:54:21.672872Z"},"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-22T15:54:21.844580Z","iopub.execute_input":"2024-05-22T15:54:21.844848Z","iopub.status.idle":"2024-05-22T15:54:21.962796Z","shell.execute_reply.started":"2024-05-22T15:54:21.844825Z","shell.execute_reply":"2024-05-22T15:54:21.961993Z"},"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-22T15:54:22.180382Z","iopub.execute_input":"2024-05-22T15:54:22.180699Z","iopub.status.idle":"2024-05-22T15:54:22.460051Z","shell.execute_reply.started":"2024-05-22T15:54:22.180673Z","shell.execute_reply":"2024-05-22T15:54:22.459244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom catboost import CatBoostClassifier, Pool\n\nfitted_models_cat = []\n\ncv_scores_cat = []\n\noof_pred = np.zeros(df_train.shape[0])\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n    df_res_cat = pd.DataFrame()\n    \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    train_pool = Pool(X_train, y_train,cat_features=cat_cols)\n    val_pool = Pool(X_valid, y_valid,cat_features=cat_cols)\n    clf = CatBoostClassifier(\n        eval_metric='AUC',\n        task_type='GPU',\n        learning_rate=0.03,\n        iterations=n_est,\n        devices='0:1'\n    )\n    \n    random_seed=3107\n    clf.fit(train_pool, eval_set=val_pool,verbose=300)\n    fitted_models_cat.append(clf)\n    y_pred_valid = clf.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_cat.append(auc_score)\n    oof_pred[idx_valid] = y_pred_valid\n    \n    del clf\n    gc.collect()\n    \n    \nprint(\"CV AUC scores: \", cv_scores_cat)\nprint(\"Average CV AUC score: \", np.mean(cv_scores_cat))","metadata":{"execution":{"iopub.status.busy":"2024-05-22T15:54:22.624173Z","iopub.execute_input":"2024-05-22T15:54:22.624791Z"},"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-21T08:11:22.263629Z","iopub.execute_input":"2024-05-21T08:11:22.264008Z","iopub.status.idle":"2024-05-21T08:11:22.271413Z","shell.execute_reply.started":"2024-05-21T08:11:22.263977Z","shell.execute_reply":"2024-05-21T08:11:22.270420Z"},"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-21T08:11:23.896730Z","iopub.execute_input":"2024-05-21T08:11:23.897358Z","iopub.status.idle":"2024-05-21T08:11:24.051553Z","shell.execute_reply.started":"2024-05-21T08:11:23.897328Z","shell.execute_reply":"2024-05-21T08:11:24.050541Z"},"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_cat)","metadata":{"execution":{"iopub.status.busy":"2024-05-21T08:11:26.110379Z","iopub.execute_input":"2024-05-21T08:11:26.111035Z","iopub.status.idle":"2024-05-21T08:11:26.118494Z","shell.execute_reply.started":"2024-05-21T08:11:26.111002Z","shell.execute_reply":"2024-05-21T08:11:26.117458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(oof_pred, \"oof_pred.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-21T08:11:28.917239Z","iopub.execute_input":"2024-05-21T08:11:28.918046Z","iopub.status.idle":"2024-05-21T08:11:28.925861Z","shell.execute_reply.started":"2024-05-21T08:11:28.918012Z","shell.execute_reply":"2024-05-21T08:11:28.924713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(model, \"model.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-21T08:11:29.405340Z","iopub.execute_input":"2024-05-21T08:11:29.406079Z","iopub.status.idle":"2024-05-21T08:11:29.700467Z","shell.execute_reply.started":"2024-05-21T08:11:29.406042Z","shell.execute_reply":"2024-05-21T08:11:29.699534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(cat_cols, \"cat_columns.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-21T08:11:30.292284Z","iopub.execute_input":"2024-05-21T08:11:30.293032Z","iopub.status.idle":"2024-05-21T08:11:30.300656Z","shell.execute_reply.started":"2024-05-21T08:11:30.292999Z","shell.execute_reply":"2024-05-21T08:11:30.299562Z"},"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\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-21T08:11:32.338078Z","iopub.execute_input":"2024-05-21T08:11:32.338918Z","iopub.status.idle":"2024-05-21T08:11:32.450648Z","shell.execute_reply.started":"2024-05-21T08:11:32.338884Z","shell.execute_reply":"2024-05-21T08:11:32.449574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}