Spaces:
Sleeping
Sleeping
File size: 24,809 Bytes
99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 3377b5a 99be397 | 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 | {
"cells": [
{
"cell_type": "markdown",
"id": "cell-00",
"metadata": {},
"source": [
"# Classification with a Decision Tree (CART)\n",
"\n",
"We train a single **decision tree** to predict whether a loan applicant is a\n",
"*good* or *bad* credit risk, using the German Credit dataset (1,000 past\n",
"applicants). Decision trees are a great first model because the result is easy to\n",
"read: it's just a sequence of yes/no questions.\n",
"\n",
"We follow the standard supervised-learning workflow: **load → split → preprocess → fit → evaluate.**"
]
},
{
"cell_type": "markdown",
"id": "cell-01",
"metadata": {},
"source": [
"## 1. Imports\n",
"\n",
"[scikit-learn](https://scikit-learn.org/) provides the model and the\n",
"preprocessing/evaluation tools; pandas and numpy handle the data."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cell-02",
"metadata": {
"execution": {
"iopub.execute_input": "2026-06-08T10:52:08.449606Z",
"iopub.status.busy": "2026-06-08T10:52:08.448949Z",
"iopub.status.idle": "2026-06-08T10:52:11.701293Z",
"shell.execute_reply": "2026-06-08T10:52:11.700566Z"
}
},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.pipeline import Pipeline\n",
"from sklearn.preprocessing import OneHotEncoder\n",
"from sklearn.impute import SimpleImputer\n",
"from sklearn.compose import ColumnTransformer\n",
"from sklearn import tree\n",
"from sklearn import metrics"
]
},
{
"cell_type": "markdown",
"id": "cell-03",
"metadata": {},
"source": [
"## 2. Load and prepare the data\n",
"\n",
"Each row is one applicant. We make two preparation choices:\n",
"\n",
"- **Drop `Foreign_worker` and `Gender`.** These are sensitive attributes — using\n",
" them to judge creditworthiness would be discriminatory, so we exclude them.\n",
"- **Recode the target** `Credit_risk` to numbers: `0 = good`, `1 = bad`. Models\n",
" need numeric labels."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "cell-04",
"metadata": {
"execution": {
"iopub.execute_input": "2026-06-08T10:52:11.706673Z",
"iopub.status.busy": "2026-06-08T10:52:11.705757Z",
"iopub.status.idle": "2026-06-08T10:52:11.721517Z",
"shell.execute_reply": "2026-06-08T10:52:11.720617Z"
}
},
"outputs": [],
"source": [
"# load and prepare data\n",
"\n",
"data = pd.read_csv('../german_credit_from_r.csv')\n",
"data.drop(['Foreign_worker', 'Gender'], axis=1, inplace=True)\n",
"data['Credit_risk'] = data['Credit_risk'].map({'GOOD': 0, 'BAD': 1})"
]
},
{
"cell_type": "markdown",
"id": "cell-05",
"metadata": {},
"source": [
"## 3. Train/test split\n",
"\n",
"We hold out 20% of the data as a **test set** the model never sees during\n",
"training, to estimate how it will do on *new* applicants. `random_state=42` fixes\n",
"the split so the notebook is reproducible."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "cell-06",
"metadata": {
"execution": {
"iopub.execute_input": "2026-06-08T10:52:11.726745Z",
"iopub.status.busy": "2026-06-08T10:52:11.726004Z",
"iopub.status.idle": "2026-06-08T10:52:11.732974Z",
"shell.execute_reply": "2026-06-08T10:52:11.731919Z"
}
},
"outputs": [],
"source": [
"# train/test split\n",
"\n",
"X = data.drop('Credit_risk', axis=1)\n",
"y = data['Credit_risk']\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
]
},
{
"cell_type": "markdown",
"id": "cell-07",
"metadata": {},
"source": [
"## 4. Preprocessing\n",
"\n",
"Different column types need different handling, bundled in a `ColumnTransformer`:\n",
"\n",
"- **Numeric** features (age, duration, amount, …): fill missing values with the\n",
" column mean. Trees split on thresholds, so we don't need to scale them.\n",
"- **Categorical** features (account status, purpose, …): **one-hot encode** into\n",
" 0/1 columns. `handle_unknown=\"ignore\"` is safe if a category shows up in the\n",
" test set that wasn't in training.\n",
"\n",
"Preprocessing and the classifier are chained in one `Pipeline`, so identical\n",
"steps apply to train and test data."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cell-08",
"metadata": {
"execution": {
"iopub.execute_input": "2026-06-08T10:52:11.737193Z",
"iopub.status.busy": "2026-06-08T10:52:11.736879Z",
"iopub.status.idle": "2026-06-08T10:52:11.740943Z",
"shell.execute_reply": "2026-06-08T10:52:11.740106Z"
}
},
"outputs": [],
"source": [
"# define preprocessing pipeline\n",
"\n",
"numeric_features = [\"Duration\", \"Credit_amount\", \"Installment_rate\", \"Resident_since\", \"Age\", \"Existing_credits\", \"People_maintenance_for\"]\n",
"numeric_transformer = Pipeline(steps=[(\"imputer\", SimpleImputer(strategy=\"mean\"))])\n",
"\n",
"categorical_features = [\"Account_status\", \"Credit_history\", \"Purpose\", \"Savings_bonds\", \"Present_employment_since\", \"Other_debtors_guarantors\", \"Property\", \"Other_installment_plans\", \"Housing\", \"Job\", \"Telephone\"]\n",
"categorical_transformer = Pipeline(steps=[(\"encoder\", OneHotEncoder(handle_unknown=\"ignore\"))])\n",
"\n",
"preprocessor = ColumnTransformer(\n",
" transformers=[\n",
" (\"num\", numeric_transformer, numeric_features),\n",
" (\"cat\", categorical_transformer, categorical_features),\n",
" ]\n",
")\n",
"\n",
"pipe = Pipeline([\n",
" (\"preprocessor\", preprocessor),\n",
" (\"classifier\", tree.DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=42)),\n",
"])"
]
},
{
"cell_type": "markdown",
"id": "cell-09",
"metadata": {},
"source": [
"## 5. Fit the model\n",
"\n",
"We grow the tree using **entropy** (information gain) to pick splits, capped at\n",
"`max_depth=3` so it stays small and readable.\n",
"\n",
"💡 **Try it:** change `max_depth` (e.g. 2, 5, 10). A deeper tree fits the training\n",
"data more closely — but does it actually do better on the *test* set, or does it\n",
"start to **overfit**?"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "cell-10",
"metadata": {
"execution": {
"iopub.execute_input": "2026-06-08T10:52:11.745797Z",
"iopub.status.busy": "2026-06-08T10:52:11.745012Z",
"iopub.status.idle": "2026-06-08T10:52:11.803167Z",
"shell.execute_reply": "2026-06-08T10:52:11.801875Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"<style>#sk-container-id-1 {color: black;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>Pipeline(steps=[('preprocessor',\n",
" ColumnTransformer(transformers=[('num',\n",
" Pipeline(steps=[('imputer',\n",
" SimpleImputer())]),\n",
" ['Duration', 'Credit_amount',\n",
" 'Installment_rate',\n",
" 'Resident_since', 'Age',\n",
" 'Existing_credits',\n",
" 'People_maintenance_for']),\n",
" ('cat',\n",
" Pipeline(steps=[('encoder',\n",
" OneHotEncoder(handle_unknown='ignore'))]),\n",
" ['Account_status',\n",
" 'Credit_history', 'Purpose',\n",
" 'Savings_bonds',\n",
" 'Present_employment_since',\n",
" 'Other_debtors_guarantors',\n",
" 'Property',\n",
" 'Other_installment_plans',\n",
" 'Housing', 'Job',\n",
" 'Telephone'])])),\n",
" ('classifier',\n",
" DecisionTreeClassifier(criterion='entropy', max_depth=3,\n",
" random_state=42))])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" ><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">Pipeline</label><div class=\"sk-toggleable__content\"><pre>Pipeline(steps=[('preprocessor',\n",
" ColumnTransformer(transformers=[('num',\n",
" Pipeline(steps=[('imputer',\n",
" SimpleImputer())]),\n",
" ['Duration', 'Credit_amount',\n",
" 'Installment_rate',\n",
" 'Resident_since', 'Age',\n",
" 'Existing_credits',\n",
" 'People_maintenance_for']),\n",
" ('cat',\n",
" Pipeline(steps=[('encoder',\n",
" OneHotEncoder(handle_unknown='ignore'))]),\n",
" ['Account_status',\n",
" 'Credit_history', 'Purpose',\n",
" 'Savings_bonds',\n",
" 'Present_employment_since',\n",
" 'Other_debtors_guarantors',\n",
" 'Property',\n",
" 'Other_installment_plans',\n",
" 'Housing', 'Job',\n",
" 'Telephone'])])),\n",
" ('classifier',\n",
" DecisionTreeClassifier(criterion='entropy', max_depth=3,\n",
" random_state=42))])</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">preprocessor: ColumnTransformer</label><div class=\"sk-toggleable__content\"><pre>ColumnTransformer(transformers=[('num',\n",
" Pipeline(steps=[('imputer', SimpleImputer())]),\n",
" ['Duration', 'Credit_amount',\n",
" 'Installment_rate', 'Resident_since', 'Age',\n",
" 'Existing_credits',\n",
" 'People_maintenance_for']),\n",
" ('cat',\n",
" Pipeline(steps=[('encoder',\n",
" OneHotEncoder(handle_unknown='ignore'))]),\n",
" ['Account_status', 'Credit_history', 'Purpose',\n",
" 'Savings_bonds', 'Present_employment_since',\n",
" 'Other_debtors_guarantors', 'Property',\n",
" 'Other_installment_plans', 'Housing', 'Job',\n",
" 'Telephone'])])</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">num</label><div class=\"sk-toggleable__content\"><pre>['Duration', 'Credit_amount', 'Installment_rate', 'Resident_since', 'Age', 'Existing_credits', 'People_maintenance_for']</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">SimpleImputer</label><div class=\"sk-toggleable__content\"><pre>SimpleImputer()</pre></div></div></div></div></div></div></div></div><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">cat</label><div class=\"sk-toggleable__content\"><pre>['Account_status', 'Credit_history', 'Purpose', 'Savings_bonds', 'Present_employment_since', 'Other_debtors_guarantors', 'Property', 'Other_installment_plans', 'Housing', 'Job', 'Telephone']</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" ><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">OneHotEncoder</label><div class=\"sk-toggleable__content\"><pre>OneHotEncoder(handle_unknown='ignore')</pre></div></div></div></div></div></div></div></div></div></div><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-7\" type=\"checkbox\" ><label for=\"sk-estimator-id-7\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">DecisionTreeClassifier</label><div class=\"sk-toggleable__content\"><pre>DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=42)</pre></div></div></div></div></div></div></div>"
],
"text/plain": [
"Pipeline(steps=[('preprocessor',\n",
" ColumnTransformer(transformers=[('num',\n",
" Pipeline(steps=[('imputer',\n",
" SimpleImputer())]),\n",
" ['Duration', 'Credit_amount',\n",
" 'Installment_rate',\n",
" 'Resident_since', 'Age',\n",
" 'Existing_credits',\n",
" 'People_maintenance_for']),\n",
" ('cat',\n",
" Pipeline(steps=[('encoder',\n",
" OneHotEncoder(handle_unknown='ignore'))]),\n",
" ['Account_status',\n",
" 'Credit_history', 'Purpose',\n",
" 'Savings_bonds',\n",
" 'Present_employment_since',\n",
" 'Other_debtors_guarantors',\n",
" 'Property',\n",
" 'Other_installment_plans',\n",
" 'Housing', 'Job',\n",
" 'Telephone'])])),\n",
" ('classifier',\n",
" DecisionTreeClassifier(criterion='entropy', max_depth=3,\n",
" random_state=42))])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# fit the model on the training data\n",
"\n",
"pipe.fit(X_train, y_train)"
]
},
{
"cell_type": "markdown",
"id": "cell-11",
"metadata": {},
"source": [
"## 6. Evaluate\n",
"\n",
"We score the model on the held-out test set using **AUC** (Area Under the ROC\n",
"Curve). AUC measures how well the model *ranks* applicants by risk — **1.0** is a\n",
"perfect ranking, **0.5** is no better than random. Because it looks at the whole\n",
"ranking, it doesn't depend on picking a particular probability cut-off.\n",
"\n",
"💡 **Try it:** note this AUC — you'll compare it against the Bagging and Random\n",
"Forest notebooks, which build on this single tree."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "cell-12",
"metadata": {
"execution": {
"iopub.execute_input": "2026-06-08T10:52:11.807364Z",
"iopub.status.busy": "2026-06-08T10:52:11.806756Z",
"iopub.status.idle": "2026-06-08T10:52:11.821134Z",
"shell.execute_reply": "2026-06-08T10:52:11.820129Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AUC: 0.769\n"
]
}
],
"source": [
"# evaluate on the test set\n",
"\n",
"preds = pd.DataFrame(pipe.predict_proba(X_test))\n",
"preds.columns = ['prob_0', 'prob_1']\n",
"fpr, tpr, thresholds = metrics.roc_curve(y_test, preds[\"prob_1\"], pos_label=1)\n",
"\n",
"print('AUC: ', np.round(metrics.auc(fpr, tpr), 3))"
]
}
],
"metadata": {
"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.15"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|