Sub topic 1
Anatomy of a Decision Tree
Prerequisites
This chapter assumes basic Python, supervised learning, features, labels, training and test sets, classification, regression, probability, and averages.
Anatomy of a decision tree
A decision tree predicts an output by asking a sequence of feature-based questions. A node contains training examples. The root is the first node. An internal node applies a test, such as age <= 30. Each result follows a branch to another node. A leaf is the final node that produces a prediction.
For classification, a leaf usually predicts the most common class among its examples. For regression, it usually predicts their mean target value.
A prediction starts at the root and follows exactly one path. The path's final leaf supplies the result.
Building a tree by recursive partitioning
A tree uses recursive partitioning, which repeatedly divides the data into smaller groups:
- Consider candidate feature tests.
- Score each test by how much it improves the child groups.
- Choose the best test and split the node.
- Repeat separately inside each child.
The method is greedy: each split is chosen using the current node, without searching all possible complete trees. Greedy growth is efficient, but an early choice might not produce the globally best tree.
Measuring node purity with Gini and entropy
A node is pure when its examples belong mostly to one class. For class proportions \(p1, \ldots, pk\), two common impurity measures are:
- Gini impurity: \(1 - \sumk pk^2\)
- Entropy: \(-\sumk pk \log2(pk)\)
Both measures are zero when a node contains one class only. They are larger when classes are mixed.
| Node contents | Gini impurity | Entropy |
|---|---|---|
| 4 class-0 examples | 0 | 0 |
| 2 class-0, 2 class-1 | 0.5 | 1 |
import math
def gini(labels):
n = len(labels)
counts = {label: labels.count(label) for label in set(labels)}
return 1 - sum((count / n) ** 2 for count in counts.values())
def entropy(labels):
n = len(labels)
counts = {label: labels.count(label) for label in set(labels)}
return -sum(
(count / n) * math.log2(count / n)
for count in counts.values()
)
print(gini([0, 0, 1, 1])) # 0.5
print(entropy([0, 0, 1, 1])) # 1.0Scoring a split with information gain
A split's child impurity is weighted by each child's size:
\[ I{\text{children}} = \frac{nL}{n}I(L) + \frac{n_R}{n}I(R) \]
Information gain is the parent impurity minus this weighted child impurity:
\[ \text{gain} = I(\text{parent}) - I_{\text{children}} \]
The tree chooses the candidate with the greatest gain. A split that creates pure children has high gain. A split that leaves class mixtures unchanged has little or no gain.
Exercise
A node has four examples: two class-0 and two class-1. A split creates two pure children, each containing two examples. Using Gini impurity, what is the information gain?
Show answer
The parent Gini impurity is 0.5. Both children have impurity 0, so their weighted impurity is 0. The information gain is 0.5.