Decision Trees: Splits, Gini and Entropy
A loan officer asks: is the income above 33 000? If not, has the applicant defaulted before? Each answer narrows the case down until a decision is clear. A decision tree learns such a sequence of yes/no questions from data. Trees handle numbers and categories, need no scaling, capture interactions on their own, and can be drawn on one page. On their own they overfit easily, but they are the building block of random forests and gradient boosting, the strongest classical models for tabular data. The Machine Learning course trains one with scikit-learn; this lesson explains how a tree chooses its questions.
How a tree predicts
Each internal node tests one feature against a threshold, ; each leaf stores a prediction (the majority class, or class proportions, for classification; the mean target for regression). A new example walks from the root to a leaf. Geometrically, the tree cuts the feature space into axis-aligned boxes and predicts a constant in each.
Measuring impurity
A good question makes the groups it creates purer. For a node whose examples have class proportions , the two standard impurity measures are
Both are 0 for a pure node and largest when the classes are evenly mixed (Gini 0.5 and entropy 1 bit for two classes). Gini is the probability that two examples drawn at random from the node have different labels; entropy is the average number of bits needed to encode a label (Entropy, Cross-Entropy and KL Divergence). A split of examples into left and right is scored by the weighted impurity of the children, and the tree picks the split with the largest impurity decrease:
With entropy, is called the information gain.
A split by hand
Ten loan applicants, their income in thousands and whether they repaid. Candidate thresholds are the midpoints between consecutive incomes:
import numpy as np
def gini(y):
p = np.bincount(y) / len(y)
return 1 - np.sum(p ** 2)
def entropy(y):
p = np.bincount(y) / len(y)
p = p[p > 0]
return -np.sum(p * np.log2(p))
# 10 loan applicants: income in $1000s and whether they repaid (1) or defaulted (0)
income = np.array([18, 22, 25, 31, 35, 42, 48, 55, 61, 70])
repaid = np.array([ 0, 0, 1, 0, 1, 1, 1, 1, 1, 1])
print(f"root: gini {gini(repaid):.3f} entropy {entropy(repaid):.3f}")
best = None
for t in (income[:-1] + income[1:]) / 2: # candidate thresholds: midpoints
left, right = repaid[income <= t], repaid[income > t]
w = len(left) / len(repaid)
g = w * gini(left) + (1 - w) * gini(right)
e = w * entropy(left) + (1 - w) * entropy(right)
print(f"income <= {t:4.1f}: weighted gini {g:.3f} entropy {e:.3f}")
if best is None or g < best[1]:
best = (t, g)
print("best threshold by gini:", best[0], " impurity decrease:", round(gini(repaid) - best[1], 3))root: gini 0.420 entropy 0.881
income <= 20.0: weighted gini 0.311 entropy 0.688
income <= 23.5: weighted gini 0.175 entropy 0.435
income <= 28.0: weighted gini 0.305 entropy 0.690
income <= 33.0: weighted gini 0.150 entropy 0.325
income <= 38.5: weighted gini 0.240 entropy 0.485
income <= 45.0: weighted gini 0.300 entropy 0.600
income <= 51.5: weighted gini 0.343 entropy 0.690
income <= 58.0: weighted gini 0.375 entropy 0.764
income <= 65.5: weighted gini 0.400 entropy 0.826
best threshold by gini: 33.0 impurity decrease: 0.27
Check the winner by hand: with the left group (18, 22, 25, 31) has labels 0, 0, 1, 0, so its Gini is ; the right group is all repaid, Gini 0. Weighted: , a decrease of . Entropy picks the same threshold, which is the usual outcome: the two criteria disagree only rarely. A tree then repeats the search inside each child, over every feature, until a stopping rule fires. The full algorithm is in the next lesson.
Watch a tree carve the plane
In the lab, a CART tree with the Gini criterion classifies two-dimensional data. Every boundary segment is horizontal or vertical, because each question tests one feature. Raise the depth from 1 to 8: training accuracy climbs to 100 %. On these fairly clean moons the test accuracy on 200 new points rises with it (89 % at depth 3, 97.5 % from depth 6), because there is little noise to memorise. Now move the noise to its maximum and step through the depths again: training accuracy still rises steadily, but test accuracy jumps around (86 % at depth 3, 77.5 % at depth 4, 91 % at depth 8) as the boxes wrap individual noisy points. A single tree is unstable, which is the problem the bagging lesson solves. Try the circles data too, where a round boundary needs a staircase of many small boxes.
With scikit-learn
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import cross_val_score
iris = load_iris()
X, y = iris.data, iris.target
tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X, y)
print(export_text(tree, feature_names=[n[:-5] for n in iris.feature_names]))
for depth in [1, 2, 3, 5, None]:
for crit in ["gini", "entropy"]:
s = cross_val_score(DecisionTreeClassifier(max_depth=depth, criterion=crit, random_state=0), X, y, cv=5)
print(f"max_depth {str(depth):4s} {crit:7s} CV accuracy {s.mean():.3f}")|--- petal width <= 0.80
| |--- class: 0
|--- petal width > 0.80
| |--- petal width <= 1.75
| | |--- class: 1
| |--- petal width > 1.75
| | |--- class: 2
max_depth 1 gini CV accuracy 0.667
max_depth 1 entropy CV accuracy 0.667
max_depth 2 gini CV accuracy 0.933
max_depth 2 entropy CV accuracy 0.933
max_depth 3 gini CV accuracy 0.960
max_depth 3 entropy CV accuracy 0.960
max_depth 5 gini CV accuracy 0.960
max_depth 5 entropy CV accuracy 0.953
max_depth None gini CV accuracy 0.960
max_depth None entropy CV accuracy 0.953
Two questions about petal width already separate the three species well: a tree you can read aloud. A depth-1 tree (a stump) can only separate one species from the other two, hence 0.667. Gini and entropy differ by at most one flower per fold here.
Hyperparameters
| Hyperparameter | Effect |
|---|---|
max_depth |
the main brake on overfitting |
min_samples_leaf |
every leaf must hold at least this many examples; smooths predictions |
min_samples_split, min_impurity_decrease |
stop splitting small or barely useful nodes |
max_leaf_nodes |
cap the number of leaves (grown best-first) |
criterion |
"gini" (default), "entropy", "log_loss" |
ccp_alpha |
cost-complexity pruning (Regression Trees and Pruning) |
class_weight |
reweight classes for imbalanced data |
Strengths, weaknesses, when to use it
| Strengths | Weaknesses |
|---|---|
| readable rules; can be printed and checked by experts | high variance: a small change in data can change the whole tree |
| no scaling needed; mixes feature types | axis-aligned boxes approximate diagonal boundaries poorly |
| captures interactions and nonlinearity automatically | greedy: each split is best now, not best overall |
| fast to train and predict | piecewise-constant predictions; no extrapolation beyond the training range |
Use a single shallow tree when the model must be explained as rules, or as a quick look at which features matter. For accuracy, use an ensemble of trees: random forests or gradient boosting.
Pitfalls
- Growing to full depth. An unrestricted tree reaches 100 % training accuracy by memorising noise.
- Reading importance from one tree. Which of two correlated features a tree picks can flip with the data.
- Expecting smooth outputs. Predictions jump at thresholds; a price model built from one tree has steps.
Practice
- A node holds 40 examples of class A and 10 of class B. Compute its Gini impurity and entropy.
Answer
. Gini . Entropy bits.
- Why does a tree never need feature scaling?
Answer
A split only depends on the order of the values of . Any increasing transformation (multiplying by 1000, taking a logarithm) keeps the order, so the same partition is found with a transformed threshold.
Test yourself
What is the Gini impurity of a node with two classes in equal proportion?
- 0
- 0.25
- 0.5
- 1
Why are the decision boundaries of a tree made of horizontal and vertical segments in 2-D?
- Because of the Gini criterion
- Each split tests a single feature against a threshold
- Because the data is standardised
- Trees always use depth 2
A tree reaches 100 % training accuracy and much lower test accuracy. Which change most directly helps?
- Switch from Gini to entropy
- Limit
max_depthor raisemin_samples_leaf - Standardise the features
- Add more features