{"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":"# 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":{"_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-18T19:22:37.148451Z","iopub.execute_input":"2024-03-18T19:22:37.149025Z","iopub.status.idle":"2024-03-18T19:22:42.033259Z","shell.execute_reply.started":"2024-03-18T19:22:37.148966Z","shell.execute_reply":"2024-03-18T19:22:42.031795Z"},"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-18T19:22:42.035904Z","iopub.execute_input":"2024-03-18T19:22:42.036435Z","iopub.status.idle":"2024-03-18T19:22:42.049295Z","shell.execute_reply.started":"2024-03-18T19:22:42.036384Z","shell.execute_reply":"2024-03-18T19:22:42.047652Z"},"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-18T19:22:42.051664Z","iopub.execute_input":"2024-03-18T19:22:42.052262Z","iopub.status.idle":"2024-03-18T19:23:04.636165Z","shell.execute_reply.started":"2024-03-18T19:22:42.052209Z","shell.execute_reply":"2024-03-18T19:23:04.634853Z"},"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-18T19:23:04.639323Z","iopub.execute_input":"2024-03-18T19:23:04.640099Z","iopub.status.idle":"2024-03-18T19:23:04.715127Z","shell.execute_reply.started":"2024-03-18T19:23:04.640039Z","shell.execute_reply":"2024-03-18T19:23:04.713732Z"},"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-18T19:23:04.717054Z","iopub.execute_input":"2024-03-18T19:23:04.717930Z","iopub.status.idle":"2024-03-18T19:23:07.015626Z","shell.execute_reply.started":"2024-03-18T19:23:04.717883Z","shell.execute_reply":"2024-03-18T19:23:07.014440Z"},"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-18T19:23:07.016895Z","iopub.execute_input":"2024-03-18T19:23:07.017289Z","iopub.status.idle":"2024-03-18T19:23:07.038854Z","shell.execute_reply.started":"2024-03-18T19:23:07.017256Z","shell.execute_reply":"2024-03-18T19:23:07.037457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Get rid of all columns with more than 40% missing data","metadata":{}},{"cell_type":"code","source":"column_names = data.columns\n\ndf = pd.DataFrame(data)\n\n# Calculate the percentage of missing values in each column\nmissing_percentage = df.isna().mean() * 100\n\n# Filter columns with missing values over 40%\ncolumns_to_drop = missing_percentage[missing_percentage > 40].index\n\n# Drop columns\ndf.drop(columns=columns_to_drop, inplace=True)\n\ndata = df.dropna()","metadata":{"execution":{"iopub.status.busy":"2024-03-18T19:23:07.041296Z","iopub.execute_input":"2024-03-18T19:23:07.042458Z","iopub.status.idle":"2024-03-18T19:23:31.015610Z","shell.execute_reply.started":"2024-03-18T19:23:07.042394Z","shell.execute_reply":"2024-03-18T19:23:31.013507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train Test Split","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n# Assuming you have a DataFrame named 'df'\n# Replace df with your actual DataFrame\n\n# Splitting the DataFrame into X and y\nX = data.drop(4, axis = 1) # Selecting the first three columns as features\ny = data.iloc[:, 4]   # Selecting the fourth column as target variable\n\n# Perform train-test split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n","metadata":{"execution":{"iopub.status.busy":"2024-03-18T19:24:37.410239Z","iopub.execute_input":"2024-03-18T19:24:37.410778Z","iopub.status.idle":"2024-03-18T19:24:43.820757Z","shell.execute_reply.started":"2024-03-18T19:24:37.410736Z","shell.execute_reply":"2024-03-18T19:24:43.819354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Ordinal Encoding","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import OrdinalEncoder\n\noe = OrdinalEncoder()\nX_train = oe.fit_transform(X_train)\nX_test = oe.fit_transform(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-03-18T19:24:47.560489Z","iopub.execute_input":"2024-03-18T19:24:47.560990Z","iopub.status.idle":"2024-03-18T19:26:07.891877Z","shell.execute_reply.started":"2024-03-18T19:24:47.560948Z","shell.execute_reply":"2024-03-18T19:26:07.889609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = np.array(X_train)\nX_test = np.array(X_test)\ny_train = np.array(y_train).astype(np.float32)\ny_test = np.array(y_test).astype(np.float32)","metadata":{"execution":{"iopub.status.busy":"2024-03-18T19:26:08.194254Z","iopub.execute_input":"2024-03-18T19:26:08.194803Z","iopub.status.idle":"2024-03-18T19:26:08.331753Z","shell.execute_reply.started":"2024-03-18T19:26:08.194752Z","shell.execute_reply":"2024-03-18T19:26:08.329960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Neural Network\n","metadata":{}},{"cell_type":"code","source":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# Define the model\nmodel = Sequential()\nmodel.add(Dense(4, input_dim=35, activation='relu'))  # Input layer with 4 neurons, input dimension 2 (features)\nmodel.add(Dense(1, activation='sigmoid'))  # Output layer with 1 neuron (binary classification)\n\n# Compile the model\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n# Train the model\nmodel.fit(X_train, y_train, epochs=20, batch_size=200)\n\n# Evaluate the model\nloss, accuracy = model.evaluate(X_test, y_test)","metadata":{"execution":{"iopub.status.busy":"2024-03-18T19:26:08.334210Z","iopub.execute_input":"2024-03-18T19:26:08.334706Z","iopub.status.idle":"2024-03-18T19:29:25.256973Z","shell.execute_reply.started":"2024-03-18T19:26:08.334658Z","shell.execute_reply":"2024-03-18T19:29:25.255371Z"},"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":"!jupyter nbconvert --to pdf /kaggle/working/notebook.ipynb","metadata":{"execution":{"iopub.status.busy":"2024-03-18T19:24:31.758438Z","iopub.status.idle":"2024-03-18T19:24:31.758874Z","shell.execute_reply.started":"2024-03-18T19:24:31.758667Z","shell.execute_reply":"2024-03-18T19:24:31.758691Z"},"trusted":true},"execution_count":null,"outputs":[]}]}