{"metadata":{"colab":{"machine_shape":"hm","name":"Home Credit 2024 Starter Notebook","provenance":[]},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7493015,"sourceType":"competition"}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.12"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"\n# IMPORTANT: RUN THIS CELL IN ORDER TO IMPORT YOUR KAGGLE DATA SOURCES\n# TO THE CORRECT LOCATION (/kaggle/input) IN YOUR NOTEBOOK,\n# THEN FEEL FREE TO DELETE THIS CELL.\n# NOTE: THIS NOTEBOOK ENVIRONMENT DIFFERS FROM KAGGLE'S PYTHON\n# ENVIRONMENT SO THERE MAY BE MISSING LIBRARIES USED BY YOUR\n# NOTEBOOK.\n\nimport os\nimport sys\nfrom tempfile import NamedTemporaryFile\nfrom urllib.request import urlopen\nfrom urllib.parse import unquote, urlparse\nfrom urllib.error import HTTPError\nfrom zipfile import ZipFile\nimport tarfile\nimport shutil\n\nCHUNK_SIZE = 40960\nDATA_SOURCE_MAPPING = 'home-credit-credit-risk-model-stability:https%3A%2F%2Fstorage.googleapis.com%2Fkaggle-competitions-data%2Fkaggle-v2%2F50160%2F7602123%2Fbundle%2Farchive.zip%3FX-Goog-Algorithm%3DGOOG4-RSA-SHA256%26X-Goog-Credential%3Dgcp-kaggle-com%2540kaggle-161607.iam.gserviceaccount.com%252F20240308%252Fauto%252Fstorage%252Fgoog4_request%26X-Goog-Date%3D20240308T203110Z%26X-Goog-Expires%3D259200%26X-Goog-SignedHeaders%3Dhost%26X-Goog-Signature%3D6a40e82824a6b85aa368917b6358b8dd328c7c39adbb237a213013592d4eedfc04541a25fdc0f684c66de6f667a7782ca6aedeebe2116c2376a925d0cacb478e72835897f98a69502d9de443051aaf5131a69e27499d3e2e1097855f7fd6729dee0b310f1524398bd5018474158a3ea4af978972328404e9f016b54a3dd4e8419841d784984b25f307b42d134e6d20e7cda44e5965a419014d6cd6fde18d8d6b28d211216726af44b8168f1123544aea3302ee21acaade8e7b57ee2b672c494eebdbe7bb6d13966e929fc661f9c98ebdaed930c8ab78ca691e8f58ac392f7db45885e50987c152b315368771bb6e42dbac9256d0b50a9b1dffb4c37c36aa0647'\n\nKAGGLE_INPUT_PATH='/kaggle/input'\nKAGGLE_WORKING_PATH='/kaggle/working'\nKAGGLE_SYMLINK='kaggle'\n\n!umount /kaggle/input/ 2> /dev/null\nshutil.rmtree('/kaggle/input', ignore_errors=True)\nos.makedirs(KAGGLE_INPUT_PATH, 0o777, exist_ok=True)\nos.makedirs(KAGGLE_WORKING_PATH, 0o777, exist_ok=True)\n\ntry:\n  os.symlink(KAGGLE_INPUT_PATH, os.path.join(\"..\", 'input'), target_is_directory=True)\nexcept FileExistsError:\n  pass\ntry:\n  os.symlink(KAGGLE_WORKING_PATH, os.path.join(\"..\", 'working'), target_is_directory=True)\nexcept FileExistsError:\n  pass\n\nfor data_source_mapping in DATA_SOURCE_MAPPING.split(','):\n    directory, download_url_encoded = data_source_mapping.split(':')\n    download_url = unquote(download_url_encoded)\n    filename = urlparse(download_url).path\n    destination_path = os.path.join(KAGGLE_INPUT_PATH, directory)\n    try:\n        with urlopen(download_url) as fileres, NamedTemporaryFile() as tfile:\n            total_length = fileres.headers['content-length']\n            print(f'Downloading {directory}, {total_length} bytes compressed')\n            dl = 0\n            data = fileres.read(CHUNK_SIZE)\n            while len(data) > 0:\n                dl += len(data)\n                tfile.write(data)\n                done = int(50 * dl / int(total_length))\n                sys.stdout.write(f\"\\r[{'=' * done}{' ' * (50-done)}] {dl} bytes downloaded\")\n                sys.stdout.flush()\n                data = fileres.read(CHUNK_SIZE)\n            if filename.endswith('.zip'):\n              with ZipFile(tfile) as zfile:\n                zfile.extractall(destination_path)\n            else:\n              with tarfile.open(tfile.name) as tarfile:\n                tarfile.extractall(destination_path)\n            print(f'\\nDownloaded and uncompressed: {directory}')\n    except HTTPError as e:\n        print(f'Failed to load (likely expired) {download_url} to path {destination_path}')\n        continue\n    except OSError as e:\n        print(f'Failed to load {download_url} to path {destination_path}')\n        continue\n\nprint('Data source import complete.')\n","metadata":{"id":"7NJInSYCw1AX","outputId":"4d4d0ab3-4233-4f88-b176-04b134d38b57"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Example Notebook\n\nWelcome to the example notebook for the Home Credit Kaggle competition. The goal of this competition is to determine how likely a customer is going to default on an issued loan. The main difference between the [first](https://www.kaggle.com/c/home-credit-default-risk) and this competition is that now your submission will be scored with a custom metric that will take into account how well the model performs in future. A decline in performance will be penalized. The goal is to create a model that is stable and performs well in the future.\n\nIn this notebook you will see how to:\n* Load the data\n* Join tables with Polars - a DataFrame library implemented in Rust language, designed to be blazingy fast and memory efficient.  \n* Create simple aggregation features\n* Train a LightGBM model\n* Create a submission table\n\n## Load the data","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","id":"KIx6htR1w1Aa"}},{"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.execute_input":"2024-02-07T21:24:50.024915Z","iopub.status.busy":"2024-02-07T21:24:50.023647Z","iopub.status.idle":"2024-02-07T21:24:54.729412Z","shell.execute_reply":"2024-02-07T21:24:54.728256Z","shell.execute_reply.started":"2024-02-07T21:24:50.024838Z"},"id":"PbHbLBMZw1Ab","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.execute_input":"2024-02-07T21:24:54.733356Z","iopub.status.busy":"2024-02-07T21:24:54.732337Z","iopub.status.idle":"2024-02-07T21:24:54.746195Z","shell.execute_reply":"2024-02-07T21:24:54.744741Z","shell.execute_reply.started":"2024-02-07T21:24:54.733288Z"},"id":"Ory0eUuow1Ac","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.execute_input":"2024-02-07T21:24:54.751423Z","iopub.status.busy":"2024-02-07T21:24:54.749698Z","iopub.status.idle":"2024-02-07T21:25:16.159261Z","shell.execute_reply":"2024-02-07T21:25:16.158289Z","shell.execute_reply.started":"2024-02-07T21:24:54.751353Z"},"id":"GAvTMNv7w1Ac","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.execute_input":"2024-02-07T21:25:16.162856Z","iopub.status.busy":"2024-02-07T21:25:16.161619Z","iopub.status.idle":"2024-02-07T21:25:16.23912Z","shell.execute_reply":"2024-02-07T21:25:16.238115Z","shell.execute_reply.started":"2024-02-07T21:25:16.162811Z"},"id":"PYCL0tnzw1Ac","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":{"id":"wi4D8WHfw1Ac"}},{"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.execute_input":"2024-02-07T21:25:16.24119Z","iopub.status.busy":"2024-02-07T21:25:16.24057Z","iopub.status.idle":"2024-02-07T21:25:18.454532Z","shell.execute_reply":"2024-02-07T21:25:18.452798Z","shell.execute_reply.started":"2024-02-07T21:25:16.241152Z"},"id":"q9DxVCCHw1Ac","outputId":"5765bbcc-c455-4599-927e-32d5df9b2c37","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.execute_input":"2024-02-07T21:25:18.456308Z","iopub.status.busy":"2024-02-07T21:25:18.455848Z","iopub.status.idle":"2024-02-07T21:25:18.474933Z","shell.execute_reply":"2024-02-07T21:25:18.473491Z","shell.execute_reply.started":"2024-02-07T21:25:18.456258Z"},"id":"01s5o4kUw1Ad","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.execute_input":"2024-02-07T21:25:18.477539Z","iopub.status.busy":"2024-02-07T21:25:18.47705Z","iopub.status.idle":"2024-02-07T21:25:28.525841Z","shell.execute_reply":"2024-02-07T21:25:28.524407Z","shell.execute_reply.started":"2024-02-07T21:25:18.477494Z"},"id":"cMFMQYlLw1Ad","outputId":"a04b667f-934b-452d-806d-33c19f3465dc","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.execute_input":"2024-02-07T21:25:28.529014Z","iopub.status.busy":"2024-02-07T21:25:28.52813Z","iopub.status.idle":"2024-02-07T21:25:28.534479Z","shell.execute_reply":"2024-02-07T21:25:28.53334Z","shell.execute_reply.started":"2024-02-07T21:25:28.528913Z"},"id":"qpG58ApXw1Ad","outputId":"ecc64648-4ca8-42d5-a5bf-376a3903d957","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import xgboost as xgb\n\nxgb_model = xgb.XGBClassifier(\n\n    objective='binary:logistic',\n    tree_method=\"hist\",\n    enable_categorical=True,\n    eval_metric='auc',\n    subsample=1,\n    colsample_bytree=1,\n    min_child_weight=1,\n    max_depth=20,\n    #gamma=0.7,\n    #reg_alpha=0.7,\n    n_estimators=1200,\n    random_state=42,\n)\n\n# Training the model on the training data\nxgb_model.fit(\n    X_train, y_train,\n    eval_set=[(X_valid, y_valid)],\n    early_stopping_rounds=100,\n    verbose=True,\n)","metadata":{"id":"2b6ztJ_YzAZB","outputId":"917460cb-8d1e-4204-fec0-0c6707099b93"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\ndef 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}')\n'''","metadata":{"execution":{"iopub.execute_input":"2024-02-07T21:27:22.507036Z","iopub.status.busy":"2024-02-07T21:27:22.506645Z","iopub.status.idle":"2024-02-07T21:27:23.796452Z","shell.execute_reply":"2024-02-07T21:27:23.79501Z","shell.execute_reply.started":"2024-02-07T21:27:22.507Z"},"id":"LDMrNY76w1Ae","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":{"id":"9_L88eAEw1Af"}}]}