Skip to content

MLDay 28 of 50Trees and Ensembles

Project 3

a Credit-Default Model

10 min read

A card issuer wants to know which clients will miss next month's payment, so it can call them early or lower their limit. About one client in five defaults. The team needs a model that clearly beats a simple baseline, and a plain account of why.

The idea

This project lines up three model families on one protocol and keeps the winner.

  1. Load and split with the Phase 3 protocol: 24,000 training rows, 6,000 test rows, stratified.
  2. Clean the codes. Some columns use category codes the documentation never explains.
  3. Compare under one protocol. A logistic baseline (Day 12), a random forest (Day 24) and histogram boosting (Day 25). All three get the same 5 folds of cross-validation on the training rows (Day 10).
  4. Tune the leader, briefly, on the same folds (Day 27).
  5. Score the test set once.
  6. Explain the winner with permutation importance and a partial-dependence chart (Day 26).

The metric is PR-AUC, the area under the precision-recall curve from Day 13. With 22% defaults, accuracy flatters any model: always saying "no default" already scores 0.779.

The formula

scikit-learn computes PR-AUC as average precision. Walk down the clients from riskiest to safest. Each time you reach a real defaulter, note the precision so far, and weight it by the recall that defaulter adds.

AP=∑k(Rk−Rk−1) Pk\text{AP} = \sum_{k} (R_k - R_{k-1})\, P_k
Symbol Meaning
kk a position in the list, sorted from the highest predicted risk down
PkP_k precision in the top kk: the share of them who really default
RkR_k recall in the top kk: the share of all defaulters found so far
Rk−Rk−1R_k - R_{k-1} the recall gained at position kk (zero unless client kk defaults)

Worked: four clients ranked as default, no, default, no. The first adds recall 0.5 at precision 1. The third adds 0.5 at precision 23\frac{2}{3}. So AP=0.5⋅1+0.5⋅0.667=0.83\text{AP} = 0.5 \cdot 1 + 0.5 \cdot 0.667 = 0.83.

A random ranking scores about the default share, 0.221. That is the floor every model below is measured against.

In code

The steps below are one script, run top to bottom. It runs in under a minute on a laptop.

Step 1: load and split. This is the Phase 3 protocol: drop ID, rename the target, stratified 80/20 split.

# script_id: day_028_project_credit_default/credit_model
import os
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd
from scipy.stats import loguniform, randint
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.inspection import partial_dependence, permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "credit_default" / "default_of_credit_card_clients.csv")
df = df.drop(columns="ID").rename(columns={"default payment next month": "default"})
X, y = df.drop(columns="default"), df["default"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
print(f"train {len(X_train):,}, test {len(X_test):,}, default rate {y_train.mean():.3f} / {y_test.mean():.3f}")
train 24,000, test 6,000, default rate 0.221 / 0.221

Step 2: clean the codes. The documentation lists EDUCATION 1–4 (4 is "others") and MARRIAGE 1–3 (3 is "others"). The file also holds codes it never mentions. The PAY_ columns give each month's repayment status, PAY_0 being the latest. They're documented as −1 for paid on time and 1–9 for months late, yet the file also holds −2 and 0. Look at the training rows only.

# script_id: day_028_project_credit_default/credit_model
print("EDUCATION:", X_train["EDUCATION"].value_counts().sort_index().to_dict())
print("MARRIAGE: ", X_train["MARRIAGE"].value_counts().sort_index().to_dict())
print("default rate by PAY_0:", y_train.groupby(X_train["PAY_0"]).mean().round(2).to_dict())
EDUCATION: {0: 12, 1: 8455, 2: 11256, 3: 3903, 4: 97, 5: 235, 6: 42}
MARRIAGE:  {0: 47, 1: 10892, 2: 12806, 3: 255}
default rate by PAY_0: {-2: 0.13, -1: 0.17, 0: 0.13, 1: 0.34, 2: 0.69, 3: 0.77, 4: 0.66, 5: 0.44, 6: 0.6, 7: 0.78, 8: 0.5}

The unknown education and marriage codes are a few hundred rows, so fold them into "others". The −2 and 0 codes default at the same low rate as −1 (paid on time), so they behave like "not late".

Two cleaning steps follow. clean fixes the categories for every model, and makes every column a float, which the partial-dependence step needs. months_late turns −2, −1 and 0 into 0, so the status reads as months late. Only the logistic model gets that second step, because a line reads −2 as "less than paid on time". A tree can split those codes apart by itself.

# script_id: day_028_project_credit_default/credit_model
PAY = ["PAY_0", "PAY_2", "PAY_3", "PAY_4", "PAY_5", "PAY_6"]

def clean(X):
    X = X.copy()
    X["EDUCATION"] = X["EDUCATION"].replace({0: 4, 5: 4, 6: 4})   # unknown codes -> 4, "others"
    X["MARRIAGE"] = X["MARRIAGE"].replace({0: 3})                  # unknown code -> 3, "others"
    return X.astype(float)

def months_late(X):
    return X.assign(**{c: X[c].clip(lower=0) for c in PAY})       # -2, -1, 0 -> 0 months late

X_train, X_test = clean(X_train), clean(X_test)
print("EDUCATION:", X_train["EDUCATION"].value_counts().sort_index().to_dict())
EDUCATION: {1.0: 8455, 2.0: 11256, 3.0: 3903, 4.0: 386}

Step 3: compare under one protocol. The same 5 folds score every model. The logistic model runs twice, once on the raw status codes and once on months late, to show what the cleaning buys. It one-hot encodes the three category columns and scales the rest (Day 14).

# script_id: day_028_project_credit_default/credit_model
CATS = ["SEX", "EDUCATION", "MARRIAGE"]

def linear():
    return [ColumnTransformer([("cats", OneHotEncoder(handle_unknown="ignore"), CATS)], remainder=StandardScaler()),
            LogisticRegression(max_iter=1000)]

models = {
    "logistic, codes": make_pipeline(*linear()),
    "logistic, late": make_pipeline(FunctionTransformer(months_late), *linear()),
    "forest": RandomForestClassifier(n_estimators=300, min_samples_leaf=20, n_jobs=-1, random_state=42),
    "boosting": HistGradientBoostingClassifier(random_state=42),
}
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = {name: cross_val_score(m, X_train, y_train, cv=folds, scoring="average_precision")
          for name, m in models.items()}
for name, s in scores.items():
    print(f"{name:<16} PR-AUC {s.mean():.3f} ± {s.std():.3f}   folds {s.round(3)}")
print("boosting beats forest in", (scores["boosting"] > scores["forest"]).sum(), "of 5 folds")
logistic, codes  PR-AUC 0.507 ± 0.012   folds [0.516 0.526 0.497 0.503 0.493]
logistic, late   PR-AUC 0.530 ± 0.011   folds [0.533 0.549 0.517 0.529 0.522]
forest           PR-AUC 0.560 ± 0.009   folds [0.564 0.575 0.551 0.551 0.558]
boosting         PR-AUC 0.563 ± 0.007   folds [0.567 0.576 0.557 0.557 0.56 ]
boosting beats forest in 5 of 5 folds

Cleaning lifts the baseline from 0.507 to 0.530. Both tree models beat it by about 0.03, and boosting edges the forest by only 0.003 on average, smaller than the fold-to-fold spread (± 0.007). It wins on every one of the same 5 folds, though, so the lead is small but steady. The baseline to beat is "logistic, late".

Step 4: tune the leader. Fifteen random settings, scored on the same folds.

# script_id: day_028_project_credit_default/credit_model
search = RandomizedSearchCV(
    HistGradientBoostingClassifier(random_state=42),
    {"learning_rate": loguniform(0.02, 0.3), "max_leaf_nodes": randint(8, 64),
     "min_samples_leaf": randint(20, 200), "l2_regularization": loguniform(1e-3, 10)},
    n_iter=15, cv=folds, scoring="average_precision", random_state=42, n_jobs=-1).fit(X_train, y_train)
print(f"best of 15 random settings: {search.best_score_:.3f}   defaults: {scores['boosting'].mean():.3f}")
best of 15 random settings: 0.560   defaults: 0.563

None of the 15 beats the defaults, so the defaults stay: here they are already near the top.

Step 5: score the test set once. The choice is made. Refit the winner and the baseline on all training rows, and score each on the 6,000 test rows.

# script_id: day_028_project_credit_default/credit_model
for name in ["logistic, late", "boosting"]:
    p = models[name].fit(X_train, y_train).predict_proba(X_test)[:, 1]
    print(f"{name:<16} test PR-AUC {average_precision_score(y_test, p):.3f}   ROC AUC {roc_auc_score(y_test, p):.3f}")
model = models["boosting"]
print("boosting stopped early after", model.n_iter_, "trees")
logistic, late   test PR-AUC 0.520   ROC AUC 0.746
boosting         test PR-AUC 0.551   ROC AUC 0.781
boosting stopped early after 65 trees

Boosting keeps its lead on unseen clients: 0.551 against 0.520, or 2.5 times the 0.221 floor. Both land a little under their CV scores, as fresh data often does.

Step 6: explain the winner. Permutation importance shuffles one column of the test set and measures the drop in PR-AUC.

# script_id: day_028_project_credit_default/credit_model
imp = permutation_importance(model, X_test, y_test, scoring="average_precision", n_repeats=5, random_state=42)
print(pd.Series(imp.importances_mean, index=X_test.columns).sort_values(ascending=False).head(5).round(3).to_string())
PAY_0        0.195
BILL_AMT1    0.019
LIMIT_BAL    0.013
PAY_6        0.008
BILL_AMT6    0.007

The latest repayment status dominates: shuffling it costs 0.195, ten times the next column. The older PAY_ columns look weak partly because they overlap with PAY_0. Shuffle one, and the model reads much the same story from the others.

Partial dependence shows how PAY_0 moves the prediction. Set every test client's PAY_0 to one value, average the predicted default chance, and repeat for each value. The chart does this for the winner and the baseline.

# script_id: day_028_project_credit_default/credit_model
logit = models["logistic, late"]
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
curves = {}
for m, name, color in [(model, "boosting", "#2a78d6"), (logit, "logistic", "#eb6834")]:
    dep = partial_dependence(m, X_test, ["PAY_0"], response_method="predict_proba", method="brute")
    curves[name] = pd.Series(dep["average"][0], index=dep["grid_values"][0].astype(int))
    ax.plot(curves[name].index, curves[name], "o-", color=color, lw=2, label=name)
ax.set(title="Boosting learns a jump at 2 months late; logistic keeps climbing",
       xlabel="PAY_0: repayment status, latest month", ylabel="Average predicted default chance")
ax.grid(alpha=0.3)
ax.legend(loc="upper left")
fig.tight_layout()
fig.savefig(FIG_DIR / "partial_dependence_pay0.png", dpi=120)
plt.close(fig)
print(pd.DataFrame(curves).T.round(2).to_string())
            -2    -1     0     1     2     3     4     5     6     8
boosting  0.18  0.18  0.17  0.24  0.59  0.59  0.57  0.57  0.57  0.57
logistic  0.16  0.16  0.16  0.31  0.51  0.71  0.85  0.93  0.97  0.99

Boosting learns a jump at 2 months late; logistic keeps climbing

This is why the trees win. Risk really is a step: training clients default at 13–17% when on time, 34% at one month late, and 66–77% from two to four months. Boosting draws that step and then goes flat. Logistic regression can only draw a smooth S-curve, so it keeps climbing, to 0.99 at eight months, while the real rates level off after two.

The model Phase 5 reuses. Days 44–50 rebuild exactly this:

  • the Phase 3 split above, then clean (no months_late);
  • HistGradientBoostingClassifier(random_state=42) with every default: learning_rate=0.1, max_iter=100, max_leaf_nodes=31, min_samples_leaf=20, early stopping on (it stopped at 65 trees; D25's model on the raw codes stopped at 72);
  • fitted on the 24,000 training rows: test PR-AUC 0.551, ROC AUC 0.781.

Quick check

Quick check

1. Why did only the logistic model get the months-late step?

2. About 22% of clients default. A new model scores PR-AUC 0.22. What does that tell you?

3. The random search's best setting scored 0.560 in CV, and the defaults 0.563. Which do you ship?

Next

Day 29 leaves tables for neural networks, starting from a single neuron.

Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).

Next · Day 29 · 7 minFrom Neurons to a Multilayer Perceptron← Previous: Day 27 · Tune Within a Budget
Not tapped yet