{"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":177521361,"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-15T02:39:05.519207Z","iopub.execute_input":"2024-05-15T02:39:05.519509Z","iopub.status.idle":"2024-05-15T02:39:08.483323Z","shell.execute_reply.started":"2024-05-15T02:39:05.519484Z","shell.execute_reply":"2024-05-15T02:39:08.482480Z"},"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-15T02:39:08.484640Z","iopub.execute_input":"2024-05-15T02:39:08.484900Z","iopub.status.idle":"2024-05-15T02:39:08.537615Z","shell.execute_reply.started":"2024-05-15T02:39:08.484877Z","shell.execute_reply":"2024-05-15T02:39:08.536636Z"},"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-15T02:39:08.538615Z","iopub.execute_input":"2024-05-15T02:39:08.538877Z","iopub.status.idle":"2024-05-15T02:39:08.558460Z","shell.execute_reply.started":"2024-05-15T02:39:08.538855Z","shell.execute_reply":"2024-05-15T02:39:08.557677Z"},"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-15T02:39:08.561731Z","iopub.execute_input":"2024-05-15T02:39:08.562020Z","iopub.status.idle":"2024-05-15T02:39:09.693434Z","shell.execute_reply.started":"2024-05-15T02:39:08.561997Z","shell.execute_reply":"2024-05-15T02:39:09.692490Z"},"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-15T02:39:09.694542Z","iopub.execute_input":"2024-05-15T02:39:09.694820Z","iopub.status.idle":"2024-05-15T02:39:09.699839Z","shell.execute_reply.started":"2024-05-15T02:39:09.694795Z","shell.execute_reply":"2024-05-15T02:39:09.699012Z"},"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-15T02:39:09.701035Z","iopub.execute_input":"2024-05-15T02:39:09.701364Z","iopub.status.idle":"2024-05-15T02:39:09.709895Z","shell.execute_reply.started":"2024-05-15T02:39:09.701332Z","shell.execute_reply":"2024-05-15T02:39:09.709114Z"},"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-15T02:39:09.711002Z","iopub.execute_input":"2024-05-15T02:39:09.711592Z","iopub.status.idle":"2024-05-15T02:39:09.902303Z","shell.execute_reply.started":"2024-05-15T02:39:09.711558Z","shell.execute_reply":"2024-05-15T02:39:09.901339Z"},"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-15T02:39:09.904967Z","iopub.execute_input":"2024-05-15T02:39:09.905258Z","iopub.status.idle":"2024-05-15T02:39:10.101675Z","shell.execute_reply.started":"2024-05-15T02:39:09.905233Z","shell.execute_reply":"2024-05-15T02:39:10.100785Z"},"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-15T02:39:10.102917Z","iopub.execute_input":"2024-05-15T02:39:10.103304Z","iopub.status.idle":"2024-05-15T02:39:10.251298Z","shell.execute_reply.started":"2024-05-15T02:39:10.103252Z","shell.execute_reply":"2024-05-15T02:39:10.250434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Selection","metadata":{}},{"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-15T02:39:10.252335Z","iopub.execute_input":"2024-05-15T02:39:10.252595Z","iopub.status.idle":"2024-05-15T02:39:10.258214Z","shell.execute_reply.started":"2024-05-15T02:39:10.252572Z","shell.execute_reply":"2024-05-15T02:39:10.257323Z"},"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-15T02:39:10.259218Z","iopub.execute_input":"2024-05-15T02:39:10.259512Z","iopub.status.idle":"2024-05-15T02:39:10.284936Z","shell.execute_reply.started":"2024-05-15T02:39:10.259488Z","shell.execute_reply":"2024-05-15T02:39:10.284141Z"},"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 \n                          [\"target\", \"riskassesment_940T\",\n                           \"riskassesment_302T_rng\", \"riskassesment_302T_mean\"]])\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-15T02:39:10.286108Z","iopub.execute_input":"2024-05-15T02:39:10.286518Z","iopub.status.idle":"2024-05-15T02:39:10.640140Z","shell.execute_reply.started":"2024-05-15T02:39:10.286487Z","shell.execute_reply":"2024-05-15T02:39:10.639253Z"},"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\", \"riskassesment_940T\",\n                           \"riskassesment_302T_rng\", \"riskassesment_302T_mean\"])\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T02:39:10.644545Z","iopub.execute_input":"2024-05-15T02:39:10.645029Z","iopub.status.idle":"2024-05-15T02:39:12.518212Z","shell.execute_reply.started":"2024-05-15T02:39:10.645002Z","shell.execute_reply":"2024-05-15T02:39:12.517343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,  \n    \"learning_rate\": 0.03,\n    \"n_estimators\": 2000,  \n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    'num_leaves':64,\n    \"device\": \"gpu\", \n    \"verbose\": -1,\n    \"min_data_in_bin\":471\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-15T02:39:12.519270Z","iopub.execute_input":"2024-05-15T02:39:12.519592Z","iopub.status.idle":"2024-05-15T02:39:12.524929Z","shell.execute_reply.started":"2024-05-15T02:39:12.519567Z","shell.execute_reply":"2024-05-15T02:39:12.524020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nfitted_models_lgb = []\n\ncv_scores_lgb = []\n\noof_pred = np.zeros(df_train.shape[0])\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\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    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set = [(X_valid, y_valid)],\n        callbacks = [lgb.log_evaluation(200), lgb.early_stopping(100)] )\n    \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    oof_pred[idx_valid] = y_pred_valid\n    \n    del model\n    gc.collect()\n\nprint(\"CV AUC scores: \", cv_scores_lgb)\nprint(\"Average CV AUC score: \", np.mean(cv_scores_lgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-15T02:39:12.526332Z","iopub.execute_input":"2024-05-15T02:39:12.526678Z","iopub.status.idle":"2024-05-15T02:42:17.560739Z","shell.execute_reply.started":"2024-05-15T02:39:12.526648Z","shell.execute_reply":"2024-05-15T02:42:17.559818Z"},"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-15T02:42:17.562240Z","iopub.execute_input":"2024-05-15T02:42:17.562548Z","iopub.status.idle":"2024-05-15T02:42:17.569077Z","shell.execute_reply.started":"2024-05-15T02:42:17.562522Z","shell.execute_reply":"2024-05-15T02:42:17.568200Z"},"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-15T02:42:17.570289Z","iopub.execute_input":"2024-05-15T02:42:17.570560Z","iopub.status.idle":"2024-05-15T02:42:18.220694Z","shell.execute_reply.started":"2024-05-15T02:42:17.570537Z","shell.execute_reply":"2024-05-15T02:42:18.219703Z"},"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_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T02:42:18.221843Z","iopub.execute_input":"2024-05-15T02:42:18.222189Z","iopub.status.idle":"2024-05-15T02:42:18.229617Z","shell.execute_reply.started":"2024-05-15T02:42:18.222154Z","shell.execute_reply":"2024-05-15T02:42:18.228626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(oof_pred, \"oof_pred.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-15T02:42:18.231063Z","iopub.execute_input":"2024-05-15T02:42:18.231495Z","iopub.status.idle":"2024-05-15T02:42:18.261211Z","shell.execute_reply.started":"2024-05-15T02:42:18.231463Z","shell.execute_reply":"2024-05-15T02:42:18.260346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(model, \"model.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-15T02:42:18.262249Z","iopub.execute_input":"2024-05-15T02:42:18.262556Z","iopub.status.idle":"2024-05-15T02:42:18.352454Z","shell.execute_reply.started":"2024-05-15T02:42:18.262531Z","shell.execute_reply":"2024-05-15T02:42:18.351517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"joblib.dump(cat_cols, \"cat_columns.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-05-15T02:42:18.353402Z","iopub.execute_input":"2024-05-15T02:42:18.353671Z","iopub.status.idle":"2024-05-15T02:42:18.361609Z","shell.execute_reply.started":"2024-05-15T02:42:18.353647Z","shell.execute_reply":"2024-05-15T02:42:18.360856Z"},"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-15T02:42:18.363092Z","iopub.execute_input":"2024-05-15T02:42:18.363565Z","iopub.status.idle":"2024-05-15T02:42:18.844224Z","shell.execute_reply.started":"2024-05-15T02:42:18.363531Z","shell.execute_reply":"2024-05-15T02:42:18.843248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}