{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Question 3: Exploring Anonymized Data - Can You Find the Golden Feature?\n", "\n", "\n", "\n", "**What is Anonymized Data?**\n", "\n", "\n", "\n", "Anonymized data is information that has been processed to remove or obscure personally identifiable details, making it impossible to trace back to specific individuals. In credit risk modeling, features are often anonymized (e.g., `P_2`, `D_39`, `B_1`) to protect customer privacy while still enabling powerful predictive analytics.\n", "\n", "\n", "\n", "**The Challenge:**\n", "\n", "\n", "\n", "Credit default prediction is central to managing risk in consumer lending. American Express, the world's largest payment card issuer, uses machine learning to predict whether cardholders will default on their payments. This helps optimize lending decisions and creates a better customer experience.\n", "\n", "\n", "\n", "You are provided with an anonymized dataset containing behavioral and profile features. Your objective is to build a classification model that predicts credit default (0 = No Default, 1 = Default).\n", "\n", "\n", "\n", "**Your Mission:** Can you discover the 'golden feature' - the most powerful predictor hidden in this anonymized data?\n", "\n", "\n", "\n", "Your work will be evaluated based on the completion of the following tasks:\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 1: Read Data\n", "\n", "\n", "\n", "**Tasks:**\n", "\n", "\n", "\n", "1. Read the dataset `Q3_data.csv` using `read_csv()`\n", "\n", "2. Inspect the first few rows using `head()`\n", "\n", "3. Display dataset information using `info()`\n", "\n", "4. Show statistical description using `describe()`\n", "\n", "5. Plot the target distribution (target column)\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import kagglehub\n", "\n", "\n", "\n", "# Download latest version\n", "\n", "path = kagglehub.dataset_download(\"mohammad2012191/q3-ka-ai-2026\")\n", "\n", "\n", "\n", "print(\"Path to dataset files:\", path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "# The 'path' variable is defined in the download cell\n", "df = pd.read_csv(os.path.join(path, 'Q3_data.csv'))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.head()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.info()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.describe()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df['Target'].value_counts().plot(kind='bar')\n", "plt.title('Target Distribution (0: No Default, 1: Default)')\n", "plt.xlabel('Target')\n", "plt.ylabel('Count')\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 2: Data Cleaning\n", "\n", "\n", "\n", "**Tasks:**\n", "\n", "\n", "\n", "Inspect and fix the following when needed:\n", "\n", "\n", "\n", "1. **Handle missing values appropriately**\n", "\n", "2. **Check and remove duplicates** if any exist\n", "\n", "3. **Encode categorical variables** if needed\n", "\n", "4. **Apply feature scaling** to numerical features (Use StandardScaler)\n", "\n", "5. **Check for target imbalance and state if it is imbalanced or not**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(df.isnull().sum())\n", "df = df.fillna(df.median())\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f'Duplicates: {df.duplicated().sum()}')\n", "df = df.drop_duplicates()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.preprocessing import LabelEncoder\n", "\n", "categorical_cols = df.select_dtypes(include=['object']).columns\n", "if len(categorical_cols) > 0:\n", " le = LabelEncoder()\n", " for col in categorical_cols:\n", " df[col] = le.fit_transform(df[col].astype(str))\n", " print(f'Encoded columns: {list(categorical_cols)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.preprocessing import StandardScaler\n", "\n", "scaler = StandardScaler()\n", "X_cols = df.drop(columns=['Target']).columns\n", "df[X_cols] = scaler.fit_transform(df[X_cols])\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df['Target'].value_counts()\n", "# there is imbalance" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 3: Modeling\n", "\n", "\n", "\n", "**Tasks:**\n", "\n", "\n", "\n", "1. Split the dataset into features (X) and target (y)\n", "\n", "2. Use the correct split: **KFold** OR **StratifiedKFold**\n", "\n", "3. Train a **CatBoostClassifier** model\n", "\n", "4. Evaluate using the appropriate metric only (Accuracy vs. F1 Score).\n", "\n", "5. Print the averaged score across all folds" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X = df.drop(columns=['Target'])\n", "y = df['Target']\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import StratifiedKFold\n", "from sklearn.ensemble import RandomForestClassifier\n", "from catboost import CatBoostClassifier\n", "from sklearn.metrics import f1_score\n", "\n", "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", "model = CatBoostClassifier(n_estimators=100, random_state=42)\n", "\n", "f1 = []\n", "\n", "for train_idx, val_idx in skf.split(X, y):\n", " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", " \n", " model.fit(X_train, y_train)\n", " preds = model.predict(X_val)\n", " f1.append(f1_score(y_val, preds))\n", "\n", "print(f'F1: {np.mean(f1):.4f}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 4: Find the Golden Feature!\n", "\n", "\n", "\n", "**Tasks:**\n", "\n", "\n", "\n", "1. Plot feature importance from your trained model\n", "\n", "2. Identify and print the name of the most important feature (the 'golden feature')\n", "\n", "3. Plot the distribution of predictions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "importances = model.feature_importances_\n", "feat_importances = pd.Series(importances, index=X.columns).sort_values(ascending=False)\n", "\n", "plt.figure(figsize=(10, 6))\n", "feat_importances[:10].plot(kind='barh')\n", "plt.gca().invert_yaxis()\n", "plt.title('Top 10 Feature Importances')\n", "plt.xlabel('Importance')\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "golden_feature = feat_importances.index[0]\n", "print(f'The Golden Feature is: {golden_feature}')\n", "print(f'Importance: {feat_importances.iloc[0]:.4f}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 5: Bonus - Retrain with Golden Feature Only\n", "\n", "\n", "\n", "**Task:**\n", "\n", "\n", "\n", "Now that you've found the golden feature, let's see how powerful it really is!\n", "\n", "\n", "\n", "Retrain your CatBoostClassifier using **ONLY the golden feature** and compare its performance to the full model:\n", "\n", "\n", "\n", "1. Create new X with only the golden feature\n", "\n", "2. Run the same KFold loop with this single feature\n", "\n", "3. Print and compare the accuracy with the full model" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import StratifiedKFold\n", "from sklearn.ensemble import RandomForestClassifier\n", "from catboost import CatBoostClassifier\n", "from sklearn.metrics import f1_score\n", "\n", "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", "model = CatBoostClassifier(n_estimators=100, random_state=42)\n", "\n", "# Retrain with only the golden feature\n", "X_golden = X[[golden_feature]]\n", "\n", "golden_accuracies = []\n", "for train_idx, val_idx in skf.split(X_golden, y):\n", " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", " \n", " model.fit(X_train, y_train)\n", " preds = model.predict(X_val)\n", " golden_accuracies.append(f1_score(y_val, preds))\n", "\n", "print(f'Accuracy with ONLY {golden_feature}: {np.mean(golden_accuracies):.4f}')\n", "print(f'Full Model Accuracy: {np.mean(f1):.4f}')\n", "print(f'Difference: {np.mean(f1) - np.mean(golden_accuracies):.4f}')\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "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.9.18" } }, "nbformat": 4, "nbformat_minor": 4 }