{"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":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import joblib  # Import joblib for saving and loading models\nfrom pathlib import Path  # Import Path for working with file paths\nimport gc  # Import gc for garbage collection\nfrom glob import glob  # Import glob for file matching\nimport numpy as np  # Import numpy for numerical computing\nimport pandas as pd  # Import pandas for data manipulation\nimport polars as pl  # Import polars for fast data manipulation\nfrom sklearn.base import BaseEstimator, RegressorMixin  # Import BaseEstimator and RegressorMixin from sklearn.base\nfrom sklearn.metrics import roc_auc_score  # Import roc_auc_score from sklearn.metrics\nfrom sklearn.model_selection import train_test_split # Import train_test_split from the sklearn.model_selection\nfrom scipy.stats import spearmanr, kendalltau  # Import spearmanr and kendalltau from scipy.stats\nimport warnings  # Import warnings to ignore warnings\nimport lightgbm as lgb\nimport warnings  # Import warnings to ignore warnings\nwarnings.filterwarnings('ignore')  # Ignore warnings","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-27T12:03:24.004545Z","iopub.execute_input":"2024-05-27T12:03:24.005026Z","iopub.status.idle":"2024-05-27T12:03:24.011827Z","shell.execute_reply.started":"2024-05-27T12:03:24.004988Z","shell.execute_reply":"2024-05-27T12:03:24.010814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_table_dtypes(df: pl.DataFrame) -> pl.DataFrame:\n # Uncomment the code if wish to check for the count\n # Checking the number of data type exist within the dataset\n # I = 0 # For counting integer\n # D = 0 # For counting date\n # F = 0 # For counting float\n # S = 0 # For counting string\n\n\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).alias(col)) # Set Data type to be integer IF the column title is case_id, week_num, num_group1 and num_group2\n         # I += 1\n\n      #elif col in [\"date_decision\"]:\n        # df = df.with_columns(pl.col(col).cast(pl.Date).alias(col)) # Set Data type to be date IF column title is date_decision\n         # D += 1\n\n      #Since there are special notations of P, M, A, D, T or L as the last character of most columns, they are utilized\n      elif col[-1] in (\"P\", \"A\"):\n          df = df.with_columns(pl.col(col).cast(pl.Float64).alias(col)) # Set Data type to be float IF column title is P and A\n         # F += 1\n\n      elif col[-1] in (\"M\",):\n           df = df.with_columns(pl.col(col).cast(pl.Utf8).alias(col)) # Set Data type to be string IF column title is M (String in ploars is Utf8)\n          # S += 1\n\n      elif col[-1] in (\"D\",):\n          df = df.with_columns(pl.col(col).cast(pl.Date).alias(col)) # Set Data type to be date IF column title is D\n         # D += 1\n\n # print(f\"Integer: {I}\")\n#print(f\"Date: {D}\")\n##3print(f\"Float: {F}\")\n#print(f\"String: {S}\")\n  return df\n\n\n# Defining a method to handle date columns and calculate time differences\ndef 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\"))  # Calculate time differences\n            df = df.with_columns(pl.col(col).dt.total_days())  # Convert time differences to total days\n    df = df.drop(\"date_decision\", \"MONTH\")  # Drop unnecessary columns\n    return df\n\n# Data Cleaning\n# Defining a method to filter out columns based on missing values and frequency\ndef 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() # This line calculate the percentage of null values within the column\n          if isnull > 0.7:\n              df = df.drop(col)  # Drop columns with more than 70% missing values as it is not usable and might interfere with predictions and machine model\n\n\n  for col in df.columns:\n      if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) & (df[col].dtype == pl.Utf8): # (Same here, pl does not have string, but Utf8)\n          freq = df[col].n_unique()\n          if (freq == 1) | (freq > 200):\n              df = df.drop(col)  # Drop columns with only one unique value or more than 200 unique values\n  return df","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:24.013344Z","iopub.execute_input":"2024-05-27T12:03:24.013753Z","iopub.status.idle":"2024-05-27T12:03:24.027218Z","shell.execute_reply.started":"2024-05-27T12:03:24.013727Z","shell.execute_reply":"2024-05-27T12:03:24.026290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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-05-27T12:03:24.028335Z","iopub.execute_input":"2024-05-27T12:03:24.028655Z","iopub.status.idle":"2024-05-27T12:03:24.043476Z","shell.execute_reply.started":"2024-05-27T12:03:24.028630Z","shell.execute_reply":"2024-05-27T12:03:24.042504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_file(path):\n    # Read csv file into a Polars DataFrame\n    df = pl.read_csv(path)\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:24.045313Z","iopub.execute_input":"2024-05-27T12:03:24.045801Z","iopub.status.idle":"2024-05-27T12:03:24.054576Z","shell.execute_reply.started":"2024-05-27T12:03:24.045774Z","shell.execute_reply":"2024-05-27T12:03:24.053612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_files(regex_path):\n    chunks = []\n\n    # Iterate over files matching the regex pattern\n    for path in glob(str(regex_path)):\n\n        # Read csv file into a Polars DataFrame\n        df = pl.read_csv(path)\n        chunks.append(df)\n\n    # Concatenate DataFrames and drop duplicate rows based on \"case_id\"\n    df = pl.concat(chunks, how=\"vertical_relaxed\").unique(subset=[\"case_id\"])\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:24.055805Z","iopub.execute_input":"2024-05-27T12:03:24.056414Z","iopub.status.idle":"2024-05-27T12:03:24.065824Z","shell.execute_reply.started":"2024-05-27T12:03:24.056379Z","shell.execute_reply":"2024-05-27T12:03:24.064917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_train = \"/kaggle/input/home-credit-credit-risk-model-stability/csv_files/train/\"\npath_test = \"/kaggle/input/home-credit-credit-risk-model-stability/csv_files/test/\"\n","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:24.066894Z","iopub.execute_input":"2024-05-27T12:03:24.067186Z","iopub.status.idle":"2024-05-27T12:03:24.077303Z","shell.execute_reply.started":"2024-05-27T12:03:24.067161Z","shell.execute_reply":"2024-05-27T12:03:24.076484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading the train file & Applying function to set the data type\ntrain_basetable = read_file(path_train + \"train_base.csv\").pipe(set_table_dtypes)\ndata_train_static0 = read_files(path_train + \"train_static_0_0.csv\").pipe(set_table_dtypes)\ndata_train_static1 = read_files(path_train + \"train_static_0_1.csv\").pipe(set_table_dtypes)\n\n# The data here is being concatenated vertically because they all shares same attributes but have different ID\n# Meaning the data with same attributes are spreaded out to different files\ntrain_static = pl.concat(\n    [\n      data_train_static0,\n      data_train_static1,\n    ],\n    how=\"vertical_relaxed\",\n)\n\ndata_train_static_cb0 = read_files(path_train + \"train_static_cb_0.csv\").pipe(set_table_dtypes)\ndata_train_person_1 =  read_files(path_train + \"train_person_1.csv\").pipe(set_table_dtypes)\ndata_train_credit_bureau_b_2 = read_files(path_train + \"train_credit_bureau_b_2.csv\").pipe(set_table_dtypes)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:24.190204Z","iopub.execute_input":"2024-05-27T12:03:24.190598Z","iopub.status.idle":"2024-05-27T12:03:48.446754Z","shell.execute_reply.started":"2024-05-27T12:03:24.190570Z","shell.execute_reply":"2024-05-27T12:03:48.445688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading the test file & Applying function to set the data type\ntest_basetable = read_file(path_test + \"test_base.csv\")#.pipe(set_table_dtypes)\ndata_test_static0 =  read_files(path_test + \"test_static_0_0.csv\").pipe(set_table_dtypes)\ndata_test_static1 = read_files(path_test + \"test_static_0_1.csv\").pipe(set_table_dtypes)\ndata_test_static2 = read_files(path_test + \"test_static_0_2.csv\").pipe(set_table_dtypes)\n\n\n# The data here is being concatenated vertically because they all shares same attributes but have different ID\n# Meaning the data with same attributes are spreaded out to different files\ntest_static = pl.concat(\n    [\n      data_test_static0,\n      data_test_static1,\n      data_test_static2,\n    ],\n    how=\"vertical_relaxed\",\n)\n\ndata_test_static_cb0 =  read_files(path_test + \"test_static_cb_0.csv\").pipe(set_table_dtypes)\ndata_test_person_1 = read_files(path_test + \"test_person_1.csv\").pipe(set_table_dtypes)\ndata_test_credit_bureau_b_2 = read_files(path_test + \"test_credit_bureau_b_2.csv\").pipe(set_table_dtypes)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:48.448365Z","iopub.execute_input":"2024-05-27T12:03:48.448685Z","iopub.status.idle":"2024-05-27T12:03:48.518964Z","shell.execute_reply.started":"2024-05-27T12:03:48.448660Z","shell.execute_reply":"2024-05-27T12:03:48.517900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Aggregating the TRAIN file\n# 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 = data_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\n# Here num_group1=0 has special meaning, it is the person who applied for the loan. Thus, rows where num_group1 is not equal 0 are removed\n# After that , remove num_group1 column because it has served its purpose\ntrain_person_1_feats_2 = data_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\n# Here we have num_goup1 and num_group2, so we need to aggregate again.\ntrain_credit_bureau_b_2_feats = data_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\n\n\n# For this run, only columns end with letter \"A\" and \"M\" are selected and others are removed\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 data_train_static_cb0.columns:\n    if col[-1] in (\"A\", \"M\"):\n        selected_static_cb_cols.append(col)\nprint(selected_static_cb_cols)\n\n\n# Join all tables together.\ndata_train = train_basetable.join(\n    train_static.select([\"case_id\"]+selected_static_cols), how=\"left\", on=\"case_id\" #remove all the attributes except \"A\" and \"M\" with case_id\n).join(\n    data_train_static_cb0.select([\"case_id\"]+selected_static_cb_cols), how=\"left\", on=\"case_id\" #remove all the attributes except \"A\" and \"M\" with 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-05-27T12:03:48.520246Z","iopub.execute_input":"2024-05-27T12:03:48.520606Z","iopub.status.idle":"2024-05-27T12:03:50.143994Z","shell.execute_reply.started":"2024-05-27T12:03:48.520579Z","shell.execute_reply":"2024-05-27T12:03:50.143161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:50.145946Z","iopub.execute_input":"2024-05-27T12:03:50.146257Z","iopub.status.idle":"2024-05-27T12:03:50.174577Z","shell.execute_reply.started":"2024-05-27T12:03:50.146231Z","shell.execute_reply":"2024-05-27T12:03:50.173515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#data_train = handle_dates(data_train)\ndata_train = filter_cols(data_train)\ndata_train","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:50.175904Z","iopub.execute_input":"2024-05-27T12:03:50.176338Z","iopub.status.idle":"2024-05-27T12:03:50.651368Z","shell.execute_reply.started":"2024-05-27T12:03:50.176310Z","shell.execute_reply":"2024-05-27T12:03:50.650372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Aggregating the TEST file\ntest_person_1_feats_1 = data_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 = data_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 = data_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\n\nselected_static_cols = []\nfor col in test_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 data_test_static_cb0.columns:\n    if col[-1] in (\"A\", \"M\",):\n        selected_static_cb_cols.append(col)\nprint(selected_static_cb_cols)\n\n\ndata_test = test_basetable.join(\n    test_static.select([\"case_id\"]+selected_static_cols), how=\"left\", on=\"case_id\"\n).join(\n    data_test_static_cb0.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-05-27T12:03:50.652689Z","iopub.execute_input":"2024-05-27T12:03:50.652995Z","iopub.status.idle":"2024-05-27T12:03:50.668532Z","shell.execute_reply.started":"2024-05-27T12:03:50.652965Z","shell.execute_reply":"2024-05-27T12:03:50.667464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_test","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:50.669761Z","iopub.execute_input":"2024-05-27T12:03:50.670075Z","iopub.status.idle":"2024-05-27T12:03:50.686998Z","shell.execute_reply.started":"2024-05-27T12:03:50.670044Z","shell.execute_reply":"2024-05-27T12:03:50.686142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#data_test = handle_dates(data_test)\ndata_test","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:50.688474Z","iopub.execute_input":"2024-05-27T12:03:50.689099Z","iopub.status.idle":"2024-05-27T12:03:50.708830Z","shell.execute_reply.started":"2024-05-27T12:03:50.689064Z","shell.execute_reply":"2024-05-27T12:03:50.707787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"case_ids = data_train[\"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_train.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_train.filter(pl.col(\"case_id\").is_in(case_ids))[[\"case_id\", \"WEEK_NUM\", \"target\"]].to_pandas(),\n        data_train.filter(pl.col(\"case_id\").is_in(case_ids))[cols_pred].to_pandas(),\n        data_train.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-05-27T12:03:50.710005Z","iopub.execute_input":"2024-05-27T12:03:50.710329Z","iopub.status.idle":"2024-05-27T12:03:55.478113Z","shell.execute_reply.started":"2024-05-27T12:03:50.710303Z","shell.execute_reply":"2024-05-27T12:03:55.477269Z"},"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-05-27T12:03:55.480841Z","iopub.execute_input":"2024-05-27T12:03:55.481174Z","iopub.status.idle":"2024-05-27T12:03:55.486318Z","shell.execute_reply.started":"2024-05-27T12:03:55.481145Z","shell.execute_reply":"2024-05-27T12:03:55.485336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb_train = lgb.Dataset(X_train, label=y_train)\nlgb_valid = lgb.Dataset(X_valid, label=y_valid, reference=lgb_train)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 3,\n    \"num_leaves\": 31,\n    \"learning_rate\": 0.05,\n    \"feature_fraction\": 0.9,\n    \"bagging_fraction\": 0.8,\n    \"bagging_freq\": 5,\n    \"n_estimators\": 1000,\n    \"verbose\": -1,\n}\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)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:03:55.487820Z","iopub.execute_input":"2024-05-27T12:03:55.488230Z","iopub.status.idle":"2024-05-27T12:05:23.899773Z","shell.execute_reply.started":"2024-05-27T12:03:55.488196Z","shell.execute_reply":"2024-05-27T12:05:23.898767Z"},"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-05-27T12:05:23.900998Z","iopub.execute_input":"2024-05-27T12:05:23.901388Z","iopub.status.idle":"2024-05-27T12:05:45.392992Z","shell.execute_reply.started":"2024-05-27T12:05:23.901352Z","shell.execute_reply":"2024-05-27T12:05:45.391704Z"},"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-05-27T12:05:45.394468Z","iopub.execute_input":"2024-05-27T12:05:45.394846Z","iopub.status.idle":"2024-05-27T12:05:46.378824Z","shell.execute_reply.started":"2024-05-27T12:05:45.394811Z","shell.execute_reply":"2024-05-27T12:05:46.377704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_submission = data_test[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-05-27T12:05:46.380105Z","iopub.execute_input":"2024-05-27T12:05:46.380505Z","iopub.status.idle":"2024-05-27T12:05:46.457984Z","shell.execute_reply.started":"2024-05-27T12:05:46.380469Z","shell.execute_reply":"2024-05-27T12:05:46.456965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\n    \"case_id\": data_test[\"case_id\"].to_numpy(),\n    \"score\": y_submission_pred\n}).set_index('case_id')\nsubmission.to_csv(\"./submission.csv\")\nsubmission","metadata":{"execution":{"iopub.status.busy":"2024-05-27T12:05:46.459324Z","iopub.execute_input":"2024-05-27T12:05:46.459717Z","iopub.status.idle":"2024-05-27T12:05:46.477883Z","shell.execute_reply.started":"2024-05-27T12:05:46.459685Z","shell.execute_reply":"2024-05-27T12:05:46.477043Z"},"trusted":true},"execution_count":null,"outputs":[]}]}