TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Decision Trees: Splits, Gini and Entropy

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, xj≤tx_j \le t; 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 p1,…,pKp_1, \dots, p_K, the two standard impurity measures are

Gini(p)=1−∑k=1Kpk2,Entropy(p)=−∑k=1Kpklog⁡2pk.\text{Gini}(p) = 1 - \sum_{k=1}^{K} p_k^2, \qquad \text{Entropy}(p) = -\sum_{k=1}^{K} p_k \log_2 p_k .

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 nn examples into nLn_L left and nRn_R right is scored by the weighted impurity of the children, and the tree picks the split with the largest impurity decrease:

Δ=I(parent)−nLnI(left)−nRnI(right)\Delta = I(\text{parent}) - \frac{n_L}{n} I(\text{left}) - \frac{n_R}{n} I(\text{right})

With entropy, Δ\Delta 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:

python · try it yourself
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 t=33t = 33 the left group (18, 22, 25, 31) has labels 0, 0, 1, 0, so its Gini is 1−(0.752+0.252)=0.3751 - (0.75^2 + 0.25^2) = 0.375; the right group is all repaid, Gini 0. Weighted: 0.4⋅0.375+0.6⋅0=0.1500.4 \cdot 0.375 + 0.6 \cdot 0 = 0.150, a decrease of 0.420−0.150=0.270.420 - 0.150 = 0.27. 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.

−2−1012−2−1012feature x₁feature x₂tree on moonsmax depth 3: 5 leavesclass Aclass Bdecision boundaryTraining accuracy72/8090.0 %Test accuracy178/20089.0 %Test set: 200 new points

With scikit-learn

python · try it yourself
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

  1. A node holds 40 examples of class A and 10 of class B. Compute its Gini impurity and entropy.
Answer

p=(0.8,0.2)p = (0.8, 0.2). Gini =1−(0.64+0.04)=0.32= 1 - (0.64 + 0.04) = 0.32. Entropy =−(0.8log⁡20.8+0.2log⁡20.2)=0.8⋅0.322+0.2⋅2.322=0.722= -(0.8 \log_2 0.8 + 0.2 \log_2 0.2) = 0.8 \cdot 0.322 + 0.2 \cdot 2.322 = 0.722 bits.

  1. Why does a tree never need feature scaling?
Answer

A split xj≤tx_j \le t only depends on the order of the values of xjx_j. 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?

  1. 0
  2. 0.25
  3. 0.5
  4. 1

Why are the decision boundaries of a tree made of horizontal and vertical segments in 2-D?

  1. Because of the Gini criterion
  2. Each split tests a single feature against a threshold
  3. Because the data is standardised
  4. Trees always use depth 2

A tree reaches 100 % training accuracy and much lower test accuracy. Which change most directly helps?

  1. Switch from Gini to entropy
  2. Limit max_depth or raise min_samples_leaf
  3. Standardise the features
  4. Add more features