Skip to content

MLDay 23 of 50Trees and Ensembles

Decision Trees

How a Split Is Chosen, and When to Stop

9 min read

A card issuer wants to flag customers who may miss next month's payment, and its risk team must be able to read the rule. "Two months behind on the last bill? Then high risk" is a rule anyone can check. A decision tree learns a stack of questions like that from the data.

The idea

A decision tree predicts by asking yes/no questions, one after another. Each question is a split: "is this feature ≤ some threshold?" Rows that answer yes go left, the rest go right. A node is a group of rows waiting at one point in the tree. A leaf is a node with no more questions. It predicts the class most of its training rows had, and its share of class 1 is the predicted probability.

To grow a tree, start with every row in one node. Try each feature, and each threshold halfway between two neighbouring values. Keep the split whose two sides are purest: each side as close to one class as it can get. Then do the same on each side.

Left alone, a tree keeps splitting until every leaf is pure, even a leaf with one customer in it. That tree has memorized its training rows: it overfits (D10). Two settings stop it sooner:

  • max_depth: the most questions on any path from the top to a leaf.
  • min_samples_leaf: the fewest training rows a leaf may hold.

A split only compares a value with a threshold, so trees need no feature scaling. Multiply a column by 1,000 and the threshold grows with it, but every row lands in the same leaf. To predict a number instead, a regression tree gives each leaf the mean of its rows, and picks the split that most shrinks the squared error around those means.

A tiny example

Eight customers: the share of their credit limit they used, and whether they defaulted next month.

Used (%) 10 20 30 40 50 60 75 90
Defaulted no no no yes no no yes yes

Five paid and three defaulted. The candidate thresholds are the 7 midpoints: 15, 25, 35, 45, 55, 67.5 and 82.5. Compare two of them:

  • Used ≤ 45? Left: 10, 20, 30, 40, so 3 paid and 1 default. Right: 2 paid and 2 defaults, a coin flip.
  • Used ≤ 67.5? Left: the first six, so 5 paid and 1 default. Right: 75 and 90, both defaults. That side is pure.

The second question sorts the customers better. One question deep, the tree is:

The formula

Gini impurity puts a number on how mixed a node is:

G=1−∑kpk2G = 1 - \sum_k p_k^2
Symbol Meaning
GG the node's Gini impurity: 0 when pure, 0.5 at worst for two classes
kk a class (here: paid, default)
pkp_k the share of the node's rows in class kk

Worked: the left side of "used ≤ 45" holds 3 paid and 1 default, so G=1−(0.752+0.252)=0.375G = 1 - (0.75^2 + 0.25^2) = 0.375. A pure side has G=1−12=0G = 1 - 1^2 = 0, and 2 against 2 gives 0.5.

A split is scored by its two sides' impurity, each weighted by its share of the rows:

Gsplit=nLn GL+nRn GRG_{\text{split}} = \frac{n_L}{n}\, G_L + \frac{n_R}{n}\, G_R
Symbol Meaning
nn rows in the node being split
nLn_L, nRn_R rows sent left and right
GLG_L, GRG_R the Gini impurity of each side

Worked: "used ≤ 45" scores 48(0.375)+48(0.5)=0.438\frac{4}{8}(0.375) + \frac{4}{8}(0.5) = 0.438. "Used ≤ 67.5" scores 68(0.278)+28(0)=0.208\frac{6}{8}(0.278) + \frac{2}{8}(0) = 0.208, since 5 against 1 gives 1−(56)2−(16)2=0.2781 - (\frac{5}{6})^2 - (\frac{1}{6})^2 = 0.278. Before any split, 5 against 3 gives 0.469.

Try it

Find the purest split for the eight customers

Top row: defaulted. Bottom row: paid. Move the threshold until each side is as close to one class as you can get it, and watch the weighted Gini fall.

050100-0.500.511.5share of the limit used (%)classleft: x ≤ 45right: x > 45x = 10, paid, goes leftx = 20, paid, goes leftx = 30, paid, goes leftx = 40, defaulted, goes leftx = 50, paid, goes rightx = 60, paid, goes rightx = 75, defaulted, goes rightx = 90, defaulted, goes right
left (x ≤ 45): 3 × paid, 1 × defaultedGini 0.375
right (x > 45): 2 × paid, 2 × defaultedGini 0.5
weighted: (4·0.375 + 4·0.5) / 8Gini 0.438

before splitting: Gini 0.469Gini = 1 − Σ (share of each class)²: 0 is pure, 0.5 is a 50/50 mix.

The threshold starts at 45, with a weighted Gini of 0.438. Slide it to find a lower score, then press Best split: it tries all 7 midpoints and lands on x ≤ 67.5 (0.208). Notice that x ≤ 35 comes second (0.3): its left side is pure too, but it leaves a mixed 2-against-3 on the right.

In code

scikit-learn's DecisionTreeClassifier runs the same search (Gini is its default criterion). With max_depth=1 it may ask one question, and export_text prints the tree it grew:

# script_id: day_023_decision_trees/eight_rows
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text

X = pd.DataFrame({"used_pct": [10, 20, 30, 40, 50, 60, 75, 90]})  # share of the credit limit used
y = [0, 0, 0, 1, 0, 0, 1, 1]                                       # 1 = defaulted next month

stump = DecisionTreeClassifier(max_depth=1, random_state=42).fit(X, y)
print(export_text(stump, feature_names=["used_pct"], show_weights=True))
new = pd.DataFrame({"used_pct": [50, 80]})
print("p(default) at 50% and 80%:", stump.predict_proba(new)[:, 1].round(2))
|--- used_pct <= 67.50
|   |--- weights: [5.00, 1.00] class: 0
|--- used_pct >  67.50
|   |--- weights: [0.00, 2.00] class: 1

p(default) at 50% and 80%: [0.17 1.  ]

The weights are the class counts in each leaf: paid, then default. It found the same 67.5 threshold.

Now 30,000 real customers from Taiwan, with the split, settings and test score shared by all of Phase 3. The score is ROC AUC on the test rows (D13): 0.5 is guessing and 1 is perfect. The loop grows trees of rising depth:

# script_id: day_023_decision_trees/credit_depth
import os
from pathlib import Path

import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

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_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)


def auc(tree, X, y):
    return roc_auc_score(y, tree.predict_proba(X)[:, 1])


for depth in [2, 4, 6, 10, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=42).fit(X_tr, y_tr)
    print(f"max_depth={str(depth):4}  leaves {tree.get_n_leaves():4d}  "
          f"train AUC {auc(tree, X_tr, y_tr):.3f}  test AUC {auc(tree, X_te, y_te):.3f}")
tree = DecisionTreeClassifier(min_samples_leaf=100, random_state=42).fit(X_tr, y_tr)
print(f"min_samples_leaf=100: depth {tree.get_depth()}, leaves {tree.get_n_leaves()}, "
      f"test AUC {auc(tree, X_te, y_te):.3f}\n")
shallow = DecisionTreeClassifier(max_depth=2, random_state=42).fit(X_tr, y_tr)
print(export_text(shallow, feature_names=list(X.columns), show_weights=True))
max_depth=2     leaves    4  train AUC 0.694  test AUC 0.690
max_depth=4     leaves   16  train AUC 0.749  test AUC 0.735
max_depth=6     leaves   55  train AUC 0.776  test AUC 0.745
max_depth=10    leaves  306  train AUC 0.823  test AUC 0.721
max_depth=None  leaves 3782  train AUC 1.000  test AUC 0.608
min_samples_leaf=100: depth 20, leaves 183, test AUC 0.751

|--- PAY_0 <= 1.50
|   |--- PAY_2 <= 1.50
|   |   |--- weights: [16868.00, 2804.00] class: 0
|   |--- PAY_2 >  1.50
|   |   |--- weights: [1067.00, 767.00] class: 0
|--- PAY_0 >  1.50
|   |--- BILL_AMT1 <= 2207.50
|   |   |--- weights: [114.00, 106.00] class: 0
|   |--- BILL_AMT1 >  2207.50
|   |   |--- weights: [642.00, 1632.00] class: 1

The depth-2 tree's first question is PAY_0 ≤ 1.5. PAY_0 is last month's repayment status, where 2 means two months late, so this is the risk team's rule from the top of the page. Test AUC climbs to about 0.745 by depth 6, holds there to depth 8, then falls. With no limit, the tree grows 3,782 leaves, about 6 training rows each. It scores a perfect 1.000 on those rows and 0.608 on new ones: it memorized them. min_samples_leaf=100 lets the tree grow 20 levels deep but keeps every leaf at 100 customers or more, and scores 0.751. A scaled logistic regression on this split scores 0.708.

The same loop over every depth from 1 to 20 draws the chart:

# script_id: day_023_decision_trees/credit_depth
import matplotlib.pyplot as plt

FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
depths = range(1, 21)
trees = [DecisionTreeClassifier(max_depth=d, random_state=42).fit(X_tr, y_tr) for d in depths]
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(depths, [auc(t, X_tr, y_tr) for t in trees], color="#2a78d6", marker="o", ms=4, label="train")
ax.plot(depths, [auc(t, X_te, y_te) for t in trees], color="#eb6834", marker="o", ms=4, label="test")
ax.set(title="Train AUC keeps rising; test AUC peaks near depth 6 to 8",
       xlabel="max_depth", ylabel="ROC AUC", xticks=[1, 5, 10, 15, 20])
ax.legend()
fig.tight_layout()
fig.savefig(FIG_DIR / "depth_vs_auc.png", dpi=120)

Train AUC keeps rising; test AUC peaks near depth 6 to 8

Quick check

Quick check

1. A leaf holds 2 paid and 2 defaulted customers. What is its Gini impurity?

2. With no depth limit, a tree scores train AUC 1.000 and test AUC 0.608. What happened?

3. You multiply the LIMIT_BAL column by 1,000 and refit. What happens to the tree?

Next

One tree changes a lot when its training rows change; D24 grows hundreds of trees on different samples and averages them into a random forest.

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 24 · 7 minBagging and Random Forests← Previous: Day 22 · Project 2: an SMS Spam Filter
Not tapped yet