{"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"}],"dockerImageVersionId":30648,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport gc\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import StratifiedGroupKFold, KFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nfrom scipy.misc import derivative\n\nimport joblib\n\nimport lightgbm as lgb\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-29T20:26:53.360476Z","iopub.execute_input":"2024-04-29T20:26:53.361244Z","iopub.status.idle":"2024-04-29T20:26:59.969010Z","shell.execute_reply.started":"2024-04-29T20:26:53.361203Z","shell.execute_reply":"2024-04-29T20:26:59.967999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pre-Fitted Voting Model","metadata":{}},{"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)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:26:59.970728Z","iopub.execute_input":"2024-04-29T20:26:59.971060Z","iopub.status.idle":"2024-04-29T20:26:59.982959Z","shell.execute_reply.started":"2024-04-29T20:26:59.971032Z","shell.execute_reply":"2024-04-29T20:26:59.981694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pipeline","metadata":{}},{"cell_type":"code","source":"class Pipeline:\n    @staticmethod\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\n        return df\n    \n    @staticmethod\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())\n                \n        df = df.drop(\"date_decision\", \"MONTH\")\n\n        return df\n    \n    @staticmethod\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\n                if isnull > 0.95:\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\n                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n\n        return df","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:26:59.984556Z","iopub.execute_input":"2024-04-29T20:26:59.985508Z","iopub.status.idle":"2024-04-29T20:27:00.000843Z","shell.execute_reply.started":"2024-04-29T20:26:59.985449Z","shell.execute_reply":"2024-04-29T20:26:59.999723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Automatic Aggregation","metadata":{}},{"cell_type":"code","source":"class Aggregator:\n    @staticmethod\n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\",)]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        \n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n    \n    @staticmethod\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n\n        return expr_max\n\n    @staticmethod\n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:00.005445Z","iopub.execute_input":"2024-04-29T20:27:00.007910Z","iopub.status.idle":"2024-04-29T20:27:00.021423Z","shell.execute_reply.started":"2024-04-29T20:27:00.007872Z","shell.execute_reply":"2024-04-29T20:27:00.020466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### File I/O","metadata":{}},{"cell_type":"code","source":"def read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    \n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    \n    return df\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    for path in glob(str(regex_path)):\n        chunks.append(pl.read_parquet(path).pipe(Pipeline.set_table_dtypes))\n        \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:00.022952Z","iopub.execute_input":"2024-04-29T20:27:00.023394Z","iopub.status.idle":"2024-04-29T20:27:00.038307Z","shell.execute_reply.started":"2024-04-29T20:27:00.023367Z","shell.execute_reply":"2024-04-29T20:27:00.035877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Engineering","metadata":{}},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n        \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        \n    df_base = df_base.pipe(Pipeline.handle_dates)\n    \n    return df_base","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:00.040643Z","iopub.execute_input":"2024-04-29T20:27:00.041386Z","iopub.status.idle":"2024-04-29T20:27:00.050297Z","shell.execute_reply.started":"2024-04-29T20:27:00.041350Z","shell.execute_reply":"2024-04-29T20:27:00.049361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    \n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    \n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    \n    return df_data, cat_cols","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:00.052424Z","iopub.execute_input":"2024-04-29T20:27:00.053074Z","iopub.status.idle":"2024-04-29T20:27:00.066466Z","shell.execute_reply.started":"2024-04-29T20:27:00.053039Z","shell.execute_reply":"2024-04-29T20:27:00.065469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Configuration","metadata":{}},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:00.068147Z","iopub.execute_input":"2024-04-29T20:27:00.068781Z","iopub.status.idle":"2024-04-29T20:27:00.076676Z","shell.execute_reply.started":"2024-04-29T20:27:00.068745Z","shell.execute_reply":"2024-04-29T20:27:00.075697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train Files Read & Feature Engineering","metadata":{}},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:00.078135Z","iopub.execute_input":"2024-04-29T20:27:00.078697Z","iopub.status.idle":"2024-04-29T20:27:31.950733Z","shell.execute_reply.started":"2024-04-29T20:27:00.078648Z","shell.execute_reply":"2024-04-29T20:27:31.949718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\n\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:31.954182Z","iopub.execute_input":"2024-04-29T20:27:31.954819Z","iopub.status.idle":"2024-04-29T20:27:39.445530Z","shell.execute_reply.started":"2024-04-29T20:27:31.954787Z","shell.execute_reply":"2024-04-29T20:27:39.444466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Test Files Read & Feature Engineering","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_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:39.446756Z","iopub.execute_input":"2024-04-29T20:27:39.447045Z","iopub.status.idle":"2024-04-29T20:27:39.849970Z","shell.execute_reply.started":"2024-04-29T20:27:39.447020Z","shell.execute_reply":"2024-04-29T20:27:39.849050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\n\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:39.851071Z","iopub.execute_input":"2024-04-29T20:27:39.851370Z","iopub.status.idle":"2024-04-29T20:27:39.881102Z","shell.execute_reply.started":"2024-04-29T20:27:39.851345Z","shell.execute_reply":"2024-04-29T20:27:39.880156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Elimination","metadata":{}},{"cell_type":"code","source":"df_train = df_train.pipe(Pipeline.filter_cols)\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\n\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:39.882279Z","iopub.execute_input":"2024-04-29T20:27:39.882545Z","iopub.status.idle":"2024-04-29T20:27:42.021885Z","shell.execute_reply.started":"2024-04-29T20:27:39.882522Z","shell.execute_reply":"2024-04-29T20:27:42.020903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pandas Conversion","metadata":{}},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)\ndf_test, cat_cols = to_pandas(df_test, cat_cols)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:42.023120Z","iopub.execute_input":"2024-04-29T20:27:42.023428Z","iopub.status.idle":"2024-04-29T20:27:55.767309Z","shell.execute_reply.started":"2024-04-29T20:27:42.023402Z","shell.execute_reply":"2024-04-29T20:27:55.766458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Garbage Collection","metadata":{}},{"cell_type":"code","source":"del data_store\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:55.768419Z","iopub.execute_input":"2024-04-29T20:27:55.768739Z","iopub.status.idle":"2024-04-29T20:27:55.913086Z","shell.execute_reply.started":"2024-04-29T20:27:55.768712Z","shell.execute_reply":"2024-04-29T20:27:55.912220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### EDA","metadata":{}},{"cell_type":"code","source":"print(\"Train is duplicated:\\t\", df_train[\"case_id\"].duplicated().any())\nprint(\"Train Week Range:\\t\", (df_train[\"WEEK_NUM\"].min(), df_train[\"WEEK_NUM\"].max()))\n\nprint()\n\nprint(\"Test is duplicated:\\t\", df_test[\"case_id\"].duplicated().any())\nprint(\"Test Week Range:\\t\", (df_test[\"WEEK_NUM\"].min(), df_test[\"WEEK_NUM\"].max()))","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:55.914313Z","iopub.execute_input":"2024-04-29T20:27:55.914672Z","iopub.status.idle":"2024-04-29T20:27:55.958756Z","shell.execute_reply.started":"2024-04-29T20:27:55.914617Z","shell.execute_reply":"2024-04-29T20:27:55.957791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[\"WEEK_NUM\"].hist(bins=92)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:55.960019Z","iopub.execute_input":"2024-04-29T20:27:55.960386Z","iopub.status.idle":"2024-04-29T20:27:56.346931Z","shell.execute_reply.started":"2024-04-29T20:27:55.960351Z","shell.execute_reply":"2024-04-29T20:27:56.346022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.lineplot(\n    data=df_train,\n    x=\"WEEK_NUM\",\n    y=\"target\",\n)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:27:56.348248Z","iopub.execute_input":"2024-04-29T20:27:56.348543Z","iopub.status.idle":"2024-04-29T20:28:13.046271Z","shell.execute_reply.started":"2024-04-29T20:27:56.348516Z","shell.execute_reply":"2024-04-29T20:28:13.045268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"cell_type":"markdown","source":"1. 시간에 따라서 train validation을 나눠서 학습.","metadata":{}},{"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\n\ndef plot_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    plt.scatter(x, y)\n    y_hat = a*x + b\n    plt.plot(x, y_hat)\n    plt.show()\n    \ndef gini_score(\n    preds: np.ndarray, data: lgb.Dataset,\n):\n\n    global weeks_train, weeks_valid\n    label = data.get_label()\n    y_pred = special.expit(preds)\n    auc_score = roc_auc_score(label, y_pred)\n    y_pred = pd.DataFrame(y_pred, columns=['score'])\n    label = pd.DataFrame(label, columns=['target'])\n    if len(weeks_valid) == len(label):\n        final_score = gini_stability(pd.concat([weeks_valid.reset_index(drop=True), label, y_pred], axis=1))\n    elif len(weeks_train) == len(label):\n        final_score = gini_stability(pd.concat([weeks_train.reset_index(drop=True), label, y_pred], axis=1))\n\n    # # eval_name, eval_result, is_higher_better\n    return 'gini_score', final_score, True","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:28:13.047562Z","iopub.execute_input":"2024-04-29T20:28:13.047911Z","iopub.status.idle":"2024-04-29T20:28:13.060397Z","shell.execute_reply.started":"2024-04-29T20:28:13.047882Z","shell.execute_reply":"2024-04-29T20:28:13.059370Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom scipy import optimize\nfrom scipy import special\n\nclass FocalLoss:\n\n    def __init__(self, gamma, alpha=None):\n        self.alpha = alpha\n        self.gamma = gamma\n\n    def at(self, y):\n        if self.alpha is None:\n            return np.ones_like(y)\n        return np.where(y, self.alpha, 1 - self.alpha)\n\n    def pt(self, y, p):\n        p = np.clip(p, 1e-15, 1 - 1e-15)\n        return np.where(y, p, 1 - p)\n\n    def __call__(self, y_true, y_pred):\n        at = self.at(y_true)\n        pt = self.pt(y_true, y_pred)\n        return -at * (1 - pt) ** self.gamma * np.log(pt)\n\n    def grad(self, y_true, y_pred):\n        y = 2 * y_true - 1  # {0, 1} -> {-1, 1}\n        at = self.at(y_true)\n        pt = self.pt(y_true, y_pred)\n        g = self.gamma\n        return at * y * (1 - pt) ** g * (g * pt * np.log(pt) + pt - 1)\n\n    def hess(self, y_true, y_pred):\n        y = 2 * y_true - 1  # {0, 1} -> {-1, 1}\n        at = self.at(y_true)\n        pt = self.pt(y_true, y_pred)\n        g = self.gamma\n\n        u = at * y * (1 - pt) ** g\n        du = -at * y * g * (1 - pt) ** (g - 1)\n        v = g * pt * np.log(pt) + pt - 1\n        dv = g * np.log(pt) + g + 1\n\n        return (du * v + u * dv) * y * (pt * (1 - pt))\n\n    def init_score(self, y_true):\n        res = optimize.minimize_scalar(\n            lambda p: self(y_true, p).sum(),\n            bounds=(0, 1),\n            method='bounded'\n        )\n        p = res.x\n        log_odds = np.log(p / (1 - p))\n        return log_odds\n\n    def lgb_obj(self, preds, train_data):\n        y = train_data.get_label()\n        print((y != qwer[1]).sum())\n        p = special.expit(preds)\n        return self.grad(y, p), self.hess(y, p)\n\n    def lgb_eval(self, preds, train_data):\n        y = train_data.get_label()\n        p = special.expit(preds)\n        is_higher_better = False\n        return 'focal_loss', self(y, p).mean(), is_higher_better","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:28:13.061748Z","iopub.execute_input":"2024-04-29T20:28:13.062007Z","iopub.status.idle":"2024-04-29T20:28:13.078789Z","shell.execute_reply.started":"2024-04-29T20:28:13.061984Z","shell.execute_reply":"2024-04-29T20:28:13.077968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom scipy import optimize\nfrom scipy import special\nweeks_train, weeks_valid = None, None\nclass TimeDecayLoss:\n\n    def __init__(self, alpha, k):\n        self.alpha = alpha\n        self.k = k\n        \n    def pt(self, y, p):\n        p = np.clip(p, 1e-15, 1 - 1e-15)\n        return np.where(y, p, 1 - p)\n    \n    def time_weight(self, weeks):\n        return np.log(self.alpha - (weeks / self.k))\n\n    def __call__(self, y_true, y_pred):\n        pt = self.pt(y_true, y_pred)\n        return -np.log(pt)\n\n    def grad(self, y_true, y_pred):\n        return (y_pred - y_true)\n\n    def hess(self, y_true, y_pred):\n        return y_pred * (1-y_pred)\n\n    def init_score(self, y_true):\n        res = optimize.minimize_scalar(\n            lambda p: self(y_true, p, weeks).sum(),\n            bounds=(0, 1),\n            method='bounded'\n        )\n        p = res.x\n        log_odds = np.log(p / (1 - p))\n        return log_odds\n\n    def lgb_obj(self, preds, train_data):\n        global weeks_train\n        tw = self.time_weight(weeks_train)\n        y = train_data.get_label()\n        p = special.expit(preds)\n        return self.grad(y, p) * tw, self.hess(y, p) * tw\n\n    def lgb_eval(self, preds, train_data):\n        y = train_data.get_label()\n        p = special.expit(preds)\n        is_higher_better = False\n        return 'time_decay_loss', self(y, p).mean(), is_higher_better","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:28:13.080051Z","iopub.execute_input":"2024-04-29T20:28:13.080404Z","iopub.status.idle":"2024-04-29T20:28:13.095035Z","shell.execute_reply.started":"2024-04-29T20:28:13.080370Z","shell.execute_reply":"2024-04-29T20:28:13.094079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\n# fl = FocalLoss(gamma=2., alpha=None)\ntl = TimeDecayLoss(alpha=np.exp(1)+0.5, k=92)\ncv = KFold(n_splits=3, shuffle=True)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 8,\n    \"learning_rate\": 0.05,\n    \"n_estimators\": 1000,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": 1,\n    \"random_state\": 42,\n    \"device\": \"gpu\",\n#     'num_leaves': 64,\n#     \"objective\": tl.lgb_obj,\n    \"verbose\": 1,\n\n}\n# params = {\n#     \"boosting_type\": \"gbdt\",\n#     \"objective\": \"binary\",\n#     \"metric\": \"auc\",\n#     \"max_depth\": 10,  \n#     \"learning_rate\": 0.05,\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\": device, \n#     \"verbose\": -1,\n# }\n\nfitted_models = []\nbetter_models = []\nauc_scores = []\nfinal_scores = []\nn_cv = 3\n# for i in range(n_cv):\n#     if i == 0:\n#         fold = (weeks.quantile(i/n_cv)<=weeks) & (weeks<=weeks.quantile((i+1)/n_cv))\n#     else:\n#         fold = (weeks.quantile(i/n_cv)<weeks) & (weeks<=weeks.quantile((i+1)/n_cv))\n#     idx_train, idx_valid = np.where(~fold)[0], np.where(fold)[0]\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid =  X.iloc[idx_valid], y.iloc[idx_valid]\n    global weeks_train, weeks_valid\n    weeks_train = weeks.iloc[idx_train]\n    weeks_valid = weeks.iloc[idx_valid]\n    \n    train_dataset = lgb.Dataset(\n        X_train, y_train,\n#         init_score=np.full_like(y_train, fl.init_score(y_train), dtype=float),\n    )\n    val_dataset = lgb.Dataset(\n        X_valid, y_valid,\n#         init_score=np.full_like(y_valid, fl.init_score(y_valid), dtype=float),\n        reference=train_dataset,\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(100), lgb.early_stopping(100)]\n#     )\n    model = lgb.train(\n        params=params,\n        train_set=train_dataset,\n#         num_boost_round=10,\n        valid_sets=(train_dataset, val_dataset),\n        valid_names=('train', 'val'),\n#         early_stopping_rounds=20,\n#         verbose_eval=100,\n        feval=gini_score\n    )\n    \n    y_valid_pred = special.expit(model.predict(X_valid))\n    auc_score = roc_auc_score(y_valid, y_valid_pred)\n    y_valid_pred = pd.DataFrame(y_valid_pred, columns=['score'], index=y_valid.index)\n    final_score = gini_stability(pd.concat([weeks.iloc[idx_valid], y_valid, y_valid_pred], axis=1))\n    print(f'\\033[95m auc score: {auc_score}, final score: {final_score} \\033[0m')\n    auc_scores.append(auc_score)\n    final_scores.append(final_score)\n    \n    fitted_models.append(model)\n#     if final_score > 0.53:\n#         better_models.append(model)\n        \n# model = VotingModel(better_models)\nmodel = VotingModel(fitted_models)","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2024-04-29T20:33:48.496638Z","iopub.execute_input":"2024-04-29T20:33:48.497419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gc\ngc.collect()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(final_scores)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_range = [weeks.quantile(i/n_cv) for i in range(1, n_cv+1)]\nsns.lineplot(\n    x=x_range,\n    y=auc_scores,\n    label='auc_socres'\n)\nsns.lineplot(\n    x=x_range,\n    y=final_scores,\n    label='final_socres'\n)\nplt.legend()\n\nplt.show()\nprint(x_range)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"2. 초반 50%만 학습하고 나머지로 validation","metadata":{}},{"cell_type":"code","source":"# weeks = df_train[\"WEEK_NUM\"]\n# train_idx = np.where(weeks.quantile(0.5)>=weeks)[0]\n# X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"]).iloc[train_idx]\n# y = df_train[\"target\"].iloc[train_idx]\n# weeks = weeks.iloc[train_idx]\n\n# n_cv = 5\n# cv = StratifiedGroupKFold(n_splits=n_cv, shuffle=False)\n\n# params = {\n#     \"boosting_type\": \"gbdt\",\n#     \"objective\": \"binary\",\n#     \"metric\": \"auc\",\n#     \"max_depth\": 8,\n#     \"learning_rate\": 0.05,\n#     \"n_estimators\": 1000,\n#     \"colsample_bytree\": 0.8, \n#     \"colsample_bynode\": 0.8,\n#     \"verbose\": -1,\n#     \"random_state\": 42,\n#     \"device\": \"gpu\",\n# }\n\n# fitted_models = []\n# auc_scores = []\n# final_scores = []\n# for idx_train, idx_valid in cv.split(X, y, groups=weeks):\n#     X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n#     X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\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(100), lgb.early_stopping(100)]\n#     )\n    \n#     y_valid_pred = model.predict_proba(X_valid)[:, 1]\n#     auc_score = roc_auc_score(y_valid, y_valid_pred)\n#     y_valid_pred = pd.DataFrame(y_valid_pred, columns=['score'], index=y_valid.index)\n#     final_score = gini_stability(pd.concat([weeks.iloc[idx_valid], y_valid, y_valid_pred], axis=1))\n#     print(f'\\033[95m auc score: {auc_score}, final score: {final_score} \\033[0m')\n#     auc_scores.append(auc_score)\n#     final_scores.append(final_score)\n    \n#     fitted_models.append(model)\n\n# model = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.521759Z","iopub.status.idle":"2024-04-29T20:32:43.522117Z","shell.execute_reply.started":"2024-04-29T20:32:43.521947Z","shell.execute_reply":"2024-04-29T20:32:43.521962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# val_idx = np.where(weeks.quantile(0.5)<weeks)[0]\n# X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"]).iloc[val_idx]\n# y = df_train[\"target\"].iloc[val_idx]\n# weeks = df_train[\"WEEK_NUM\"].iloc[val_idx]\n# y_pred = pd.DataFrame(model.predict_proba(X)[:, 1], columns=['score'], index=y.index)\n# plot_gini_stability(pd.concat([weeks, y, y_pred], axis=1))","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.523772Z","iopub.status.idle":"2024-04-29T20:32:43.524120Z","shell.execute_reply.started":"2024-04-29T20:32:43.523953Z","shell.execute_reply":"2024-04-29T20:32:43.523968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction","metadata":{}},{"cell_type":"code","source":"X_test = df_test.drop(columns=[\"WEEK_NUM\"])\nX_test = X_test.set_index(\"case_id\")\n\ny_pred = pd.Series(special.expit(model.predict(X_test)), index=X_test.index)","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.525146Z","iopub.status.idle":"2024-04-29T20:32:43.525477Z","shell.execute_reply.started":"2024-04-29T20:32:43.525313Z","shell.execute_reply":"2024-04-29T20:32:43.525327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submission","metadata":{}},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.526380Z","iopub.status.idle":"2024-04-29T20:32:43.526715Z","shell.execute_reply.started":"2024-04-29T20:32:43.526532Z","shell.execute_reply":"2024-04-29T20:32:43.526544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Check null: \", df_subm[\"score\"].isnull().any())\n\ndf_subm.head()","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.527498Z","iopub.status.idle":"2024-04-29T20:32:43.527857Z","shell.execute_reply.started":"2024-04-29T20:32:43.527690Z","shell.execute_reply":"2024-04-29T20:32:43.527705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.529302Z","iopub.status.idle":"2024-04-29T20:32:43.529636Z","shell.execute_reply.started":"2024-04-29T20:32:43.529473Z","shell.execute_reply":"2024-04-29T20:32:43.529487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## check features","metadata":{}},{"cell_type":"code","source":"importances = np.mean(np.array([model.feature_importance(importance_type='gain') for model in fitted_models]), axis=0)\n# importances = fitted_models[0].booster_.feature_importance(importance_type='gain')\nindices = np.argsort(importances)[::-1]\n","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.530927Z","iopub.status.idle":"2024-04-29T20:32:43.531266Z","shell.execute_reply.started":"2024-04-29T20:32:43.531097Z","shell.execute_reply":"2024-04-29T20:32:43.531112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"top_n = 30\nplt.barh(range(top_n), importances[indices][:top_n], color='g', align='center')\nplt.yticks(range(top_n), X_train.columns[indices][:top_n])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-29T20:32:43.532356Z","iopub.status.idle":"2024-04-29T20:32:43.532716Z","shell.execute_reply.started":"2024-04-29T20:32:43.532521Z","shell.execute_reply":"2024-04-29T20:32:43.532535Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}