The Loan Desk

Machine Learning in CodeHard+10 XP+10

The Loan Desk

A small bank wants a model that says "yes" or "no" to loan requests. Its table mixes several kinds of column, and each needs its own treatment.

ColumnKindWhat to do
incomenumber, may be Nonefill with the median, then scale
debtnumber, may be Nonefill with the median, then scale
jobwordone-hot, ignoring unseen jobs
has_guarantoralready 0 or 1pass through untouched

Task: write loan_desk(table, labels, new_rows, seed).

  • table and new_rows are dicts with those four columns. labels holds "yes" or "no" for each row of table.
  • Make income and debt float so each None becomes np.nan.
  • Split with train_test_split(X, y, test_size=0.25, random_state=seed, stratify=y).
  • Build a ColumnTransformer with ("numbers", ..., ["income", "debt"]) and ("words", ..., ["job"]), using remainder="passthrough" so has_guarantor survives.
  • Put it in a Pipeline with KNeighborsClassifier(n_neighbors=3) last, and fit it on the training rows only.
  • Return {"width": number of columns the ColumnTransformer outputs, "score": test score rounded to 3 decimal places, "predictions": list of predictions for new_rows}.

Examples

table = {"income": [52, 61, None, 23, 19, 70, 25, 58, None, 21, 66, 27], "debt": [5, 8, 4, 30, 28, None, 25, 6, 9, None, 7, 31], "job": ["nurse", "chef", "nurse", "chef", "driver", "nurse", "driver", "driver", "chef", "nurse", "driver", "chef"], "has_guarantor": [1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0]}
labels = ["yes", "yes", "yes", "no", "no", "yes", "no", "yes", "yes", "no", "yes", "no"]
new_rows = {"income": [60, 22], "debt": [None, 29], "job": ["chef", "pilot"], "has_guarantor": [1, 0]}
seed = 0
returns {'width': 6, 'score': 1.0, 'predictions': ['yes', 'no']}
table = {"income": [40, 45, 15, 18, 42, 12, 48, 16], "debt": [2, None, 20, 22, 3, 25, 1, None], "job": ["a", "b", "a", "b", "c", "c", "a", "b"], "has_guarantor": [1, 1, 0, 0, 1, 0, 1, 0]}
labels = ["yes", "yes", "no", "no", "yes", "no", "yes", "no"]
new_rows = {"income": [44, 14], "debt": [2, 21], "job": ["c", "d"], "has_guarantor": [1, 0]}
seed = 0
returns {'width': 6, 'score': 1.0, 'predictions': ['yes', 'no']}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run