File size: 10,700 Bytes
2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | {
"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
}
|