Gradient LabOpen in Gradient Lab

Lessons › Projects

Loan decisions with trees and forests

A readable decision tree that explains loan decisions, and a random forest that beats it on accuracy.

No setup needed. Run every step in your browser on Gradient Lab, or download it.

Open the notebook

Level: Intermediate · Time: 35 min · You’ll practise: decision trees, overfitting, random forests, feature importance

Steps

1. Generate 1,000 past applicants

Generate 1,000 synthetic past applicants with income, debt ratio, missed payments and years employed, and whether they repaid.

rng = np.random.default_rng(42)
n = 1000
df = pd.DataFrame({
    "income_k": rng.normal(50, 18, n).clip(10, 150).round(),
    "debt_ratio": rng.uniform(0, 0.8, n).round(2),
    "missed_payments": rng.poisson(0.7, n),
    "years_employed": rng.integers(0, 25, n),
})
risk = 0.04 * df.income_k - 4 * df.debt_ratio - 0.9 * df.missed_payments + 0.05 * df.years_employed
df["repaid"] = (risk + rng.normal(0, 0.6, n) > 0.6).astype(int)
print(df.head(), f"\nRepaid: {df.repaid.mean():.0%}")

X, y = df.drop(columns="repaid"), df["repaid"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

2. A small tree you can read

Train a tree limited to 3 levels and print its questions. You can read it like a flowchart.

tree = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
print("\nThe tree's questions:\n" + export_text(tree, feature_names=list(X.columns)))
print(f"Tree accuracy on unseen applicants: {tree.score(X_test, y_test):.1%}")

3. A deep tree overfits

Remove the depth limit: perfect on training data, worse on new data. That’s overfitting.

deep = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"Unlimited tree: train {deep.score(X_train, y_train):.0%}, test {deep.score(X_test, y_test):.1%}")

4. A random forest: many trees vote

Train a random forest of 200 trees and compare.

forest = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_train, y_train)
print(f"Random forest test accuracy: {forest.score(X_test, y_test):.1%}")

5. Which clues matter most?

See which clues the forest relies on most.

for name, imp in sorted(zip(X.columns, forest.feature_importances_), key=lambda t: -t[1]):
    print(f"  {name:<16} {imp:.2f}")

6. Score two new applicants

Score two new applicants: one low-risk, one high-risk.

applicants = pd.DataFrame([
    {"income_k": 55, "debt_ratio": 0.25, "missed_payments": 0, "years_employed": 6},
    {"income_k": 42, "debt_ratio": 0.55, "missed_payments": 2, "years_employed": 1},
])
for (_, a), p in zip(applicants.iterrows(), forest.predict_proba(applicants)[:, 1]):
    print(f"income {a.income_k:.0f}k, debt {a.debt_ratio:.0%}, missed {a.missed_payments:.0f}: chance of repaying {p:.0%}")

Expected output

$ python loan_trees.py
   income_k  debt_ratio  missed_payments  years_employed  repaid
0      55.0        0.52                2               9       0
1      31.0        0.27                1               8       0
2      64.0        0.33                0              12       1
3      67.0        0.35                2               6       0
4      15.0        0.10                1               7       0 
Repaid: 44%

The tree's questions:
|--- debt_ratio <= 0.44
|   |--- missed_payments <= 0.50
|   |   |--- income_k <= 36.00
|   |   |   |--- class: 0
|   |   |--- income_k >  36.00
|   |   |   |--- class: 1
|   |--- missed_payments >  0.50
|   |   |--- income_k <= 57.50
|   |   |   |--- class: 0
|   |   |--- income_k >  57.50
|   |   |   |--- class: 1
|--- debt_ratio >  0.44
|   |--- income_k <= 63.50
|   |   |--- missed_payments <= 0.50
|   |   |   |--- class: 0
|   |   |--- missed_payments >  0.50
|   |   |   |--- class: 0
|   |--- income_k >  63.50
|   |   |--- missed_payments <= 0.50
|   |   |   |--- class: 1
|   |   |--- missed_payments >  0.50
|   |   |   |--- class: 0

Tree accuracy on unseen applicants: 80.8%
Unlimited tree: train 100%, test 83.2%
Random forest test accuracy: 86.0%
  debt_ratio       0.38
  income_k         0.31
  missed_payments  0.18
  years_employed   0.12
income 55k, debt 25%, missed 0: chance of repaying 98%
income 42k, debt 55%, missed 2: chance of repaying 0%

Stretch goals

Download p06-loan-trees.zip