Sub topic 2
Finding the Best Split in a Decision Tree
Prerequisites: basic Python, supervised learning, and the difference between training and validation data. A decision tree grows by repeatedly dividing the current data into smaller groups. Each division is a split.
Finding the best split
For classification, a tree scores a split by measuring how mixed its child nodes are. Gini impurity is one common measure:
\[ Gini = 1 - \sumk pk^2 \]
Here, \(p_k\) is the fraction of samples belonging to class \(k\). A node containing one class has impurity 0.
The tree computes the weighted impurity of the two child nodes:
\[ I{split} = \frac{nL IL + nR IR}{nL+n_R} \]
It chooses the candidate with the smallest \(I_{split}\). Equivalently, it chooses the split with the greatest impurity decrease, sometimes called information gain.
For a numeric feature, candidate thresholds usually lie halfway between consecutive sorted values. The search is greedy: the tree chooses the best split for the current node without checking every possible future tree.
def gini(labels):
counts = {}
for label in labels:
counts[label] = counts.get(label, 0) + 1
n = len(labels)
return 1 - sum((count / n) ** 2 for count in counts.values())
def split_score(left, right):
total = len(left) + len(right)
return (len(left) * gini(left) + len(right) * gini(right)) / total
print(split_score([0, 0], [1, 1])) # 0.0When to stop growing
A tree can stop when a node is pure, when it reaches max_depth, or when it has too few samples to split. A min_samples_leaf setting also prevents very small final groups. min_impurity_decrease requires a split to improve the score by a minimum amount.
These are pre-pruning rules because they limit growth before the full tree is built.
Why deep trees overfit
A deep tree can create narrow regions that match individual training examples, including noise. Its training accuracy may approach 100%, while validation accuracy falls. This is overfitting: the model learns details that do not generalize.
Evaluating a tree with cross-validation
Cross-validation repeatedly divides the training data into folds. Each run trains on some folds and validates on the remaining fold. Average validation performance gives a less fragile estimate for choosing max_depth or pruning strength.
Keep the final test set untouched until model selection is complete.
Exercise
A tree has 98% training accuracy and 72% validation accuracy. What should you investigate first?
Show answer
Investigate overfitting. Try shallower trees, larger leaves, or cost-complexity pruning, and compare them with cross-validation.