{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30635,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Data loading\nДля загрузки данных я использую предлагаемый создателями соревнования ноутбук https://www.kaggle.com/code/jetakow/home-credit-2024-starter-notebook.","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"import polars as pl\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgb\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score \n\ndataPath = \"/kaggle/input/home-credit-credit-risk-model-stability/\"","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:12.402396Z","iopub.execute_input":"2024-03-17T10:02:12.402928Z","iopub.status.idle":"2024-03-17T10:02:15.338194Z","shell.execute_reply.started":"2024-03-17T10:02:12.402884Z","shell.execute_reply":"2024-03-17T10:02:15.336810Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_table_dtypes(df: pl.DataFrame) -> pl.DataFrame:\n    # implement here all desired dtypes for tables\n    # the following is just an example\n    for col in df.columns:\n        # last letter of column name will help you determine the type\n        if col[-1] in (\"P\", \"A\"):\n            df = df.with_columns(pl.col(col).cast(pl.Float64).alias(col))\n\n    return df\n\ndef convert_strings(df: pd.DataFrame) -> pd.DataFrame:\n    for col in df.columns:  \n        if df[col].dtype.name in ['object', 'string']:\n            df[col] = df[col].astype(\"string\").astype('category')\n            current_categories = df[col].cat.categories\n            new_categories = current_categories.to_list() + [\"Unknown\"]\n            new_dtype = pd.CategoricalDtype(categories=new_categories, ordered=True)\n            df[col] = df[col].astype(new_dtype)\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:15.340935Z","iopub.execute_input":"2024-03-17T10:02:15.341289Z","iopub.status.idle":"2024-03-17T10:02:15.351961Z","shell.execute_reply.started":"2024-03-17T10:02:15.341258Z","shell.execute_reply":"2024-03-17T10:02:15.350525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_basetable = pl.read_csv(dataPath + \"csv_files/train/train_base.csv\")\ntrain_static = pl.concat(\n    [\n        pl.read_csv(dataPath + \"csv_files/train/train_static_0_0.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + \"csv_files/train/train_static_0_1.csv\").pipe(set_table_dtypes),\n    ],\n    how=\"vertical_relaxed\",\n)\ntrain_static_cb = pl.read_csv(dataPath + \"csv_files/train/train_static_cb_0.csv\").pipe(set_table_dtypes)\ntrain_person_1 = pl.read_csv(dataPath + \"csv_files/train/train_person_1.csv\").pipe(set_table_dtypes) \ntrain_credit_bureau_b_2 = pl.read_csv(dataPath + \"csv_files/train/train_credit_bureau_b_2.csv\").pipe(set_table_dtypes) ","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:15.353778Z","iopub.execute_input":"2024-03-17T10:02:15.354203Z","iopub.status.idle":"2024-03-17T10:02:35.683746Z","shell.execute_reply.started":"2024-03-17T10:02:15.354169Z","shell.execute_reply":"2024-03-17T10:02:35.682706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_basetable = pl.read_csv(dataPath + \"csv_files/test/test_base.csv\")\ntest_static = pl.concat(\n    [\n        pl.read_csv(dataPath + \"csv_files/test/test_static_0_0.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + \"csv_files/test/test_static_0_1.csv\").pipe(set_table_dtypes),\n        pl.read_csv(dataPath + \"csv_files/test/test_static_0_2.csv\").pipe(set_table_dtypes),\n    ],\n    how=\"vertical_relaxed\",\n)\ntest_static_cb = pl.read_csv(dataPath + \"csv_files/test/test_static_cb_0.csv\").pipe(set_table_dtypes)\ntest_person_1 = pl.read_csv(dataPath + \"csv_files/test/test_person_1.csv\").pipe(set_table_dtypes) \ntest_credit_bureau_b_2 = pl.read_csv(dataPath + \"csv_files/test/test_credit_bureau_b_2.csv\").pipe(set_table_dtypes) ","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:35.686344Z","iopub.execute_input":"2024-03-17T10:02:35.687015Z","iopub.status.idle":"2024-03-17T10:02:35.779262Z","shell.execute_reply.started":"2024-03-17T10:02:35.686971Z","shell.execute_reply":"2024-03-17T10:02:35.777721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Feature engineering\n\nIn this part, we can see a simple example of joining tables via `case_id`. Here the loading and joining is done with polars library. Polars library is blazingly fast and has much smaller memory footprint than pandas. ","metadata":{}},{"cell_type":"code","source":"# We need to use aggregation functions in tables with depth > 1, so tables that contain num_group1 column or \n# also num_group2 column.\ntrain_person_1_feats_1 = train_person_1.group_by(\"case_id\").agg(\n    pl.col(\"mainoccupationinc_384A\").max().alias(\"mainoccupationinc_384A_max\"),\n    (pl.col(\"incometype_1044T\") == \"SELFEMPLOYED\").max().alias(\"mainoccupationinc_384A_any_selfemployed\")\n)\n\n# Here num_group1=0 has special meaning, it is the person who applied for the loan.\ntrain_person_1_feats_2 = train_person_1.select([\"case_id\", \"num_group1\", \"housetype_905L\"]).filter(\n    pl.col(\"num_group1\") == 0\n).drop(\"num_group1\").rename({\"housetype_905L\": \"person_housetype\"})\n\n# Here we have num_goup1 and num_group2, so we need to aggregate again.\ntrain_credit_bureau_b_2_feats = train_credit_bureau_b_2.group_by(\"case_id\").agg(\n    pl.col(\"pmts_pmtsoverdue_635A\").max().alias(\"pmts_pmtsoverdue_635A_max\"),\n    (pl.col(\"pmts_dpdvalue_108P\") > 31).max().alias(\"pmts_dpdvalue_108P_over31\")\n)\n\n# We will process in this examples only A-type and M-type columns, so we need to select them.\nselected_static_cols = []\nfor col in train_static.columns:\n    if col[-1] in (\"A\", \"M\"):\n        selected_static_cols.append(col)\nprint(selected_static_cols)\n\nselected_static_cb_cols = []\nfor col in train_static_cb.columns:\n    if col[-1] in (\"A\", \"M\"):\n        selected_static_cb_cols.append(col)\nprint(selected_static_cb_cols)\n\n# Join all tables together.\ndata = train_basetable.join(\n    train_static.select([\"case_id\"]+selected_static_cols), how=\"left\", on=\"case_id\"\n).join(\n    train_static_cb.select([\"case_id\"]+selected_static_cb_cols), how=\"left\", on=\"case_id\"\n).join(\n    train_person_1_feats_1, how=\"left\", on=\"case_id\"\n).join(\n    train_person_1_feats_2, how=\"left\", on=\"case_id\"\n).join(\n    train_credit_bureau_b_2_feats, how=\"left\", on=\"case_id\"\n)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:35.780950Z","iopub.execute_input":"2024-03-17T10:02:35.781329Z","iopub.status.idle":"2024-03-17T10:02:37.836247Z","shell.execute_reply.started":"2024-03-17T10:02:35.781296Z","shell.execute_reply":"2024-03-17T10:02:37.834927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_person_1_feats_1 = test_person_1.group_by(\"case_id\").agg(\n    pl.col(\"mainoccupationinc_384A\").max().alias(\"mainoccupationinc_384A_max\"),\n    (pl.col(\"incometype_1044T\") == \"SELFEMPLOYED\").max().alias(\"mainoccupationinc_384A_any_selfemployed\")\n)\n\ntest_person_1_feats_2 = test_person_1.select([\"case_id\", \"num_group1\", \"housetype_905L\"]).filter(\n    pl.col(\"num_group1\") == 0\n).drop(\"num_group1\").rename({\"housetype_905L\": \"person_housetype\"})\n\ntest_credit_bureau_b_2_feats = test_credit_bureau_b_2.group_by(\"case_id\").agg(\n    pl.col(\"pmts_pmtsoverdue_635A\").max().alias(\"pmts_pmtsoverdue_635A_max\"),\n    (pl.col(\"pmts_dpdvalue_108P\") > 31).max().alias(\"pmts_dpdvalue_108P_over31\")\n)\n\ndata_submission = test_basetable.join(\n    test_static.select([\"case_id\"]+selected_static_cols), how=\"left\", on=\"case_id\"\n).join(\n    test_static_cb.select([\"case_id\"]+selected_static_cb_cols), how=\"left\", on=\"case_id\"\n).join(\n    test_person_1_feats_1, how=\"left\", on=\"case_id\"\n).join(\n    test_person_1_feats_2, how=\"left\", on=\"case_id\"\n).join(\n    test_credit_bureau_b_2_feats, how=\"left\", on=\"case_id\"\n)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:37.838057Z","iopub.execute_input":"2024-03-17T10:02:37.838562Z","iopub.status.idle":"2024-03-17T10:02:37.856254Z","shell.execute_reply.started":"2024-03-17T10:02:37.838502Z","shell.execute_reply":"2024-03-17T10:02:37.854965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Создание признаков","metadata":{}},{"cell_type":"markdown","source":"Я создаю пять новых признаков:\n\n1. Клиент изменил уровень образования с прошлого кредита  \n   Можно ожидать, что недавно получившие более высокое образование клиенты увеличат уровень дохода, что уменьшает вероятность    дефолта\n2. Клиент изменил семейный статус\n   Большие изменения в жизни клиента повышают вероятность дефолта\n3. Среднее число денег на счету больше суммы долга  \n   Если у клиента обычно много денег, маловероятно, что случится дефолт\n4. Доля кредита к доходу  \n   Чем больше, чем больше рист дефолта\n","metadata":{}},{"cell_type":"code","source":"def transform_add_new_features(df: pl.DataFrame) -> pl.DataFrame:\n    df.with_columns((df['education_1103M'] != df['education_88M']).alias('different_education_level'))\n    df.with_columns((df['maritalst_385M'] != df['maritalst_893M']).alias('different_marital_st'))\n    df.with_columns((df['avgoutstandbalancel6m_4187114A'] >= 2 * df['credamount_770A']).alias('a_lot_of_money'))\n    df = df.with_columns((df[\"currdebt_22A\"] / df['maininc_215A']).alias(\"debt_to_income\"))\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:37.857984Z","iopub.execute_input":"2024-03-17T10:02:37.859199Z","iopub.status.idle":"2024-03-17T10:02:37.869921Z","shell.execute_reply.started":"2024-03-17T10:02:37.859154Z","shell.execute_reply":"2024-03-17T10:02:37.868493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = transform_add_new_features(data)\ndata_submission = transform_add_new_features(data_submission)\n","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:37.872501Z","iopub.execute_input":"2024-03-17T10:02:37.873811Z","iopub.status.idle":"2024-03-17T10:02:37.982259Z","shell.execute_reply.started":"2024-03-17T10:02:37.873755Z","shell.execute_reply":"2024-03-17T10:02:37.981181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"case_ids = data[\"case_id\"].unique().shuffle(seed=1)\ncase_ids_train, case_ids_test = train_test_split(case_ids, train_size=0.6, random_state=1)\ncase_ids_valid, case_ids_test = train_test_split(case_ids_test, train_size=0.5, random_state=1)\n\ncols_pred = []\nfor col in data.columns:\n    if col[-1].isupper() and col[:-1].islower():\n        cols_pred.append(col)\n\nprint(cols_pred)\n\ndef from_polars_to_pandas(case_ids: pl.DataFrame) -> pl.DataFrame:\n    return (\n        data.filter(pl.col(\"case_id\").is_in(case_ids))[[\"case_id\", \"WEEK_NUM\", \"target\"]].to_pandas(),\n        data.filter(pl.col(\"case_id\").is_in(case_ids))[cols_pred].to_pandas(),\n        data.filter(pl.col(\"case_id\").is_in(case_ids))[\"target\"].to_pandas()\n    )\n\nbase_train, X_train, y_train = from_polars_to_pandas(case_ids_train)\nbase_valid, X_valid, y_valid = from_polars_to_pandas(case_ids_valid)\nbase_test, X_test, y_test = from_polars_to_pandas(case_ids_test)\n\nfor df in [X_train, X_valid, X_test]:\n    df = convert_strings(df)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:37.984248Z","iopub.execute_input":"2024-03-17T10:02:37.985592Z","iopub.status.idle":"2024-03-17T10:02:47.775171Z","shell.execute_reply.started":"2024-03-17T10:02:37.985537Z","shell.execute_reply":"2024-03-17T10:02:47.774247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Train: {X_train.shape}\")\nprint(f\"Valid: {X_valid.shape}\")\nprint(f\"Test: {X_test.shape}\")","metadata":{"execution":{"iopub.status.busy":"2024-03-17T10:02:47.778421Z","iopub.execute_input":"2024-03-17T10:02:47.779097Z","iopub.status.idle":"2024-03-17T10:02:47.784472Z","shell.execute_reply.started":"2024-03-17T10:02:47.779059Z","shell.execute_reply":"2024-03-17T10:02:47.783708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training LightGBM\n\nMinimal example of LightGBM training is shown below.","metadata":{}},{"cell_type":"code","source":"import optuna\n\n\ndef objective(trial, X_train, y_train, X_valid, y_valid):\n    lgb_train = lgb.Dataset(X_train, label=y_train)\n    lgb_valid = lgb.Dataset(X_valid, label=y_valid, reference=lgb_train)\n    \n    params = {\n        \"boosting_type\": \"gbdt\",\n        \"objective\": \"binary\",\n        \"metric\": \"auc\",\n        \"max_depth\": trial.suggest_int(\"max_depth\", 2, 64),\n        \"num_leaves\": trial.suggest_int(\"num_leaves\", 4, 256),\n        \"learning_rate\": trial.suggest_float(\"learning_rate\", 1e-3, 1e-1, log=True),\n        \"feature_fraction\": trial.suggest_float(\"feature_fraction\", 0.4, 1.0),\n        \"bagging_fraction\": trial.suggest_float(\"feature_fraction\", 0.4, 1.0),\n        \"bagging_freq\": trial.suggest_int(\"bagging_freq\", 1, 7),\n        \"n_estimators\": trial.suggest_int(\"n_estimators\", 1e2, 1e4, log=True),\n        \"verbose\": -1\n    } \n\n    gbm = lgb.train(\n        params,\n        lgb_train,\n        valid_sets=lgb_valid,\n        callbacks=[lgb.log_evaluation(50), lgb.early_stopping(10)]\n    )\n    \n    y_valid_pred = gbm.predict(X_valid, num_iteration=gbm.best_iteration)\n    score = roc_auc_score(y_valid, y_valid_pred)\n    return score\n\n\nstudy = optuna.create_study(direction=\"maximize\")\nstudy.optimize(lambda trial: objective(trial, X_train, y_train, X_valid, y_valid), n_trials=50)\n\nprint(\"Number of finished trials: {}\".format(len(study.trials)))\n\nprint(\"Best trial:\")\ntrial = study.best_trial\n\nprint(\"  Value: {}\".format(trial.value))\n\nprint(\"  Params: \")\nfor key, value in trial.params.items():\n    print(\"    {}: {}\".format(key, value))","metadata":{"execution":{"iopub.status.busy":"2024-03-17T11:24:25.959315Z","iopub.execute_input":"2024-03-17T11:24:25.959812Z","iopub.status.idle":"2024-03-17T11:27:05.620266Z","shell.execute_reply.started":"2024-03-17T11:24:25.959767Z","shell.execute_reply":"2024-03-17T11:27:05.618753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Evaluation with AUC and then comparison with the stability metric is shown below.","metadata":{}},{"cell_type":"code","source":"trial = study.best_trial\nbest_params = trial.params\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"verbose\": -1,\n    **best_params\n}\n\nlgb_train = lgb.Dataset(X_train, label=y_train)\nlgb_valid = lgb.Dataset(X_valid, label=y_valid, reference=lgb_train)\n\ngbm = lgb.train(\n    params,\n    lgb_train,\n    valid_sets=lgb_valid,\n    callbacks=[lgb.log_evaluation(50), lgb.early_stopping(10)]\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-03-17T11:27:05.623809Z","iopub.execute_input":"2024-03-17T11:27:05.624370Z","iopub.status.idle":"2024-03-17T11:30:01.895460Z","shell.execute_reply.started":"2024-03-17T11:27:05.624313Z","shell.execute_reply":"2024-03-17T11:30:01.894140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for base, X in [(base_train, X_train), (base_valid, X_valid), (base_test, X_test)]:\n    y_pred = gbm.predict(X, num_iteration=gbm.best_iteration)\n    base[\"score\"] = y_pred\n\nprint(f'The AUC score on the train set is: {roc_auc_score(base_train[\"target\"], base_train[\"score\"])}') \nprint(f'The AUC score on the valid set is: {roc_auc_score(base_valid[\"target\"], base_valid[\"score\"])}') \nprint(f'The AUC score on the test set is: {roc_auc_score(base_test[\"target\"], base_test[\"score\"])}')  ","metadata":{"execution":{"iopub.status.busy":"2024-03-17T11:30:01.896908Z","iopub.execute_input":"2024-03-17T11:30:01.897296Z","iopub.status.idle":"2024-03-17T11:31:16.056487Z","shell.execute_reply.started":"2024-03-17T11:30:01.897255Z","shell.execute_reply":"2024-03-17T11:31:16.055124Z"},"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\n\nstability_score_train = gini_stability(base_train)\nstability_score_valid = gini_stability(base_valid)\nstability_score_test = gini_stability(base_test)\n\nprint(f'The stability score on the train set is: {stability_score_train}') \nprint(f'The stability score on the valid set is: {stability_score_valid}') \nprint(f'The stability score on the test set is: {stability_score_test}')  ","metadata":{"execution":{"iopub.status.busy":"2024-03-17T11:31:16.059247Z","iopub.execute_input":"2024-03-17T11:31:16.059633Z","iopub.status.idle":"2024-03-17T11:31:17.197097Z","shell.execute_reply.started":"2024-03-17T11:31:16.059599Z","shell.execute_reply":"2024-03-17T11:31:17.195596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submission\n\nScoring the submission dataset is below, we need to take care of new categories. Then we save the score as a last step. ","metadata":{}},{"cell_type":"code","source":"X_submission = data_submission[cols_pred].to_pandas()\nX_submission = convert_strings(X_submission)\ncategorical_cols = X_train.select_dtypes(include=['category']).columns\n\nfor col in categorical_cols:\n    train_categories = set(X_train[col].cat.categories)\n    submission_categories = set(X_submission[col].cat.categories)\n    new_categories = submission_categories - train_categories\n    X_submission.loc[X_submission[col].isin(new_categories), col] = \"Unknown\"\n    new_dtype = pd.CategoricalDtype(categories=train_categories, ordered=True)\n    X_train[col] = X_train[col].astype(new_dtype)\n    X_submission[col] = X_submission[col].astype(new_dtype)\n\ny_submission_pred = gbm.predict(X_submission, num_iteration=gbm.best_iteration)","metadata":{"execution":{"iopub.status.busy":"2024-03-17T11:31:17.199208Z","iopub.execute_input":"2024-03-17T11:31:17.199561Z","iopub.status.idle":"2024-03-17T11:31:17.328899Z","shell.execute_reply.started":"2024-03-17T11:31:17.199531Z","shell.execute_reply":"2024-03-17T11:31:17.327709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\n    \"case_id\": data_submission[\"case_id\"].to_numpy(),\n    \"score\": y_submission_pred\n}).set_index('case_id')\nsubmission.to_csv(\"./submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-03-17T11:31:17.330184Z","iopub.execute_input":"2024-03-17T11:31:17.330562Z","iopub.status.idle":"2024-03-17T11:31:17.345124Z","shell.execute_reply.started":"2024-03-17T11:31:17.330517Z","shell.execute_reply":"2024-03-17T11:31:17.343820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Best of luck, and most importantly, enjoy the process of learning and discovery! \n\n<img src=\"https://i.imgur.com/obVWIBh.png\" alt=\"Image\" width=\"700\"/>","metadata":{}}]}