Homework · Runs in your browser
A decision tree from scratch in pure Python
Build the pieces of a decision tree with nothing but the standard library: Gini impurity, the gain of a split, the best threshold for one feature, and a depth-limited tree that you can train and use for prediction. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest.
Hints:
- Gini of a list of labels is 1 minus the sum of the squared label proportions. An empty list has impurity 0.
- Gain is the parent impurity minus the size-weighted impurity of the two children.
- Candidate thresholds are the midpoints between consecutive distinct sorted values of the feature. Keep the first threshold with the largest gain, and return (threshold, gain). Return (None, 0.0) if the feature has a single value.
- A tree is either a label (a leaf) or a tuple (feature, threshold, left, right) where left holds rows with x[feature] <= threshold. A leaf predicts the most common label; on a tie, the smallest label.
- Grow recursively: stop at max_depth, when the node is pure, or when no split leaves at least min_leaf rows on each side. Otherwise take the best split over all features (first feature wins ties) even if its gain is 0, as the XOR test needs.
- Lesson checks: the split (5 positive, 5 negative) into (4, 1) and (1, 4) has gain 0.18; (6, 4) into (5, 0) and (1, 4) has gain 0.32. On XOR no single split has gain, but a depth-2 tree is perfect.
Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.
Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.
Show a solution
Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.
from collections import Counter
def gini(labels):
"""Gini impurity: 1 - sum of squared label proportions. An empty list gives 0.0."""
n = len(labels)
if n == 0:
return 0.0
return 1.0 - sum((c / n) ** 2 for c in Counter(labels).values())
def split_gain(parent, left, right):
"""Gini(parent) minus the size-weighted Gini of left and right (three lists of labels)."""
n = len(left) + len(right)
weighted = (len(left) * gini(left) + len(right) * gini(right)) / n
return gini(parent) - weighted
def best_threshold(xs, ys):
"""Best split of one feature: (threshold, gain), or (None, 0.0) for a constant feature."""
values = sorted(set(xs))
best = (None, 0.0)
best_gain = None
for a, b in zip(values, values[1:]):
t = (a + b) / 2
left = [y for x, y in zip(xs, ys) if x <= t]
right = [y for x, y in zip(xs, ys) if x > t]
g = split_gain(ys, left, right)
if best_gain is None or g > best_gain + 1e-12:
best, best_gain = (t, g), g
return best
def _majority(y):
counts = Counter(y)
top = max(counts.values())
return min(label for label, c in counts.items() if c == top)
def fit_tree(X, y, max_depth, min_leaf=1):
"""Grow a classification tree: a leaf label or (feature, threshold, left, right)."""
if max_depth == 0 or len(set(y)) == 1:
return _majority(y)
best = None
for f in range(len(X[0])):
xs = [row[f] for row in X]
values = sorted(set(xs))
for a, b in zip(values, values[1:]):
t = (a + b) / 2
left = [lab for v, lab in zip(xs, y) if v <= t]
right = [lab for v, lab in zip(xs, y) if v > t]
if len(left) < min_leaf or len(right) < min_leaf:
continue
g = split_gain(y, left, right)
if best is None or g > best[0] + 1e-12:
best = (g, f, t)
if best is None:
return _majority(y)
_, f, t = best
li = [i for i, row in enumerate(X) if row[f] <= t]
ri = [i for i, row in enumerate(X) if row[f] > t]
return (f, t,
fit_tree([X[i] for i in li], [y[i] for i in li], max_depth - 1, min_leaf),
fit_tree([X[i] for i in ri], [y[i] for i in ri], max_depth - 1, min_leaf))
def predict(tree, x):
"""Follow the tree for one row x and return the leaf's label."""
while isinstance(tree, tuple):
f, t, left, right = tree
tree = left if x[f] <= t else right
return tree
Show the tests (test_starter.py)
import math
from starter import best_threshold, fit_tree, gini, predict, split_gain
XOR_X = [[a, b] for a in (0, 1) for b in (0, 1) for _ in range(5)]
XOR_Y = [int(a != b) for a, b in XOR_X]
def accuracy(tree, X, y):
return sum(predict(tree, row) == lab for row, lab in zip(X, y)) / len(y)
def test_gini_values():
assert gini([1] * 5 + [0] * 5) == 0.5, "a 50/50 node has Gini 0.5"
assert gini([1, 1, 1]) == 0.0, "a pure node has Gini 0"
assert math.isclose(gini([1] * 8 + [0] * 2), 0.32), "1 - (0.8^2 + 0.2^2) = 0.32"
assert gini([]) == 0.0, "an empty node has impurity 0"
def test_gain_from_the_lesson():
parent = [1] * 5 + [0] * 5
left, right = [1] * 4 + [0], [1] + [0] * 4
assert math.isclose(split_gain(parent, left, right), 0.18), "0.5 - 0.32 = 0.18"
def test_gain_with_a_pure_child():
parent = [1] * 6 + [0] * 4
left, right = [1] * 5, [1] + [0] * 4
assert math.isclose(split_gain(parent, left, right), 0.32), "0.48 - 0.5 * 0.32 = 0.32"
def test_best_threshold_on_a_clean_split():
t, g = best_threshold([1, 2, 3, 4, 5, 6], [0, 0, 0, 1, 1, 1])
assert t == 3.5 and math.isclose(g, 0.5), "the midpoint between 3 and 4 separates the classes"
def test_best_threshold_ignores_row_order():
t, g = best_threshold([1, 3, 2, 4, 6, 5, 8, 7], [0, 0, 0, 0, 1, 1, 1, 1])
assert t == 4.5 and math.isclose(g, 0.5), "sort by feature value before choosing thresholds"
def test_constant_feature_has_no_split():
assert best_threshold([2, 2, 2], [0, 1, 0]) == (None, 0.0)
def test_xor_has_no_single_split_gain():
for f in (0, 1):
t, g = best_threshold([row[f] for row in XOR_X], XOR_Y)
assert math.isclose(g, 0.0, abs_tol=1e-12), "on XOR, any one split leaves both children 50/50"
def test_stump_predictions():
tree = fit_tree([[1], [2], [3], [4], [5], [6]], [0, 0, 0, 1, 1, 1], max_depth=1)
assert predict(tree, [2]) == 0 and predict(tree, [5]) == 1
def test_xor_needs_two_levels():
shallow = fit_tree(XOR_X, XOR_Y, max_depth=1)
deep = fit_tree(XOR_X, XOR_Y, max_depth=2)
assert accuracy(shallow, XOR_X, XOR_Y) == 0.5, "one split cannot separate XOR"
assert accuracy(deep, XOR_X, XOR_Y) == 1.0, "two splits are perfect, so split even at zero gain"
def test_unlimited_depth_memorises_noisy_labels():
X = [[i] for i in range(1, 9)]
y = [0, 1, 0, 0, 1, 1, 0, 1]
assert accuracy(fit_tree(X, y, max_depth=1), X, y) < 1.0
assert accuracy(fit_tree(X, y, max_depth=10), X, y) == 1.0, "enough depth reaches pure leaves"
def test_min_leaf_blocks_tiny_leaves():
X = [[i] for i in range(1, 9)]
y = [0, 0, 0, 0, 0, 0, 0, 1]
tree = fit_tree(X, y, max_depth=5, min_leaf=2)
assert predict(tree, [8]) == 0, "a leaf for the single positive row would have only 1 row"
assert predict(fit_tree(X, y, max_depth=5, min_leaf=1), [8]) == 1, "without the limit the lone positive row gets its own leaf"
def test_majority_ties_go_to_the_smallest_label():
tree = fit_tree([[1], [1]], [1, 0], max_depth=3)
assert tree == 0, "no split is possible, and a 1-1 tie goes to label 0"
def test_predict_follows_the_tuple_layout():
tree = (0, 2.5, 0, (1, 0.5, 1, 0))
assert predict(tree, [1.0, 9.0]) == 0
assert predict(tree, [3.0, 0.2]) == 1
assert predict(tree, [3.0, 0.9]) == 0
def test_gain_weights_children_by_size():
parent = [1] * 4 + [0] * 4
left, right = [1] * 3, [1] + [0] * 4
assert math.isclose(split_gain(parent, left, right), 0.3), "0.5 - (3/8) x 0 - (5/8) x 0.32 = 0.3, not an unweighted average"
def test_best_threshold_keeps_the_first_of_a_tie():
t, g = best_threshold([1, 2, 3, 4], [0, 1, 0, 1])
assert t == 1.5 and math.isclose(g, 1 / 6), "thresholds 1.5 and 3.5 tie; the first one wins"
def test_first_feature_wins_a_tie():
tree = fit_tree([[1, 1], [2, 2], [3, 3], [4, 4]], [0, 0, 1, 1], max_depth=1)
assert tree == (0, 2.5, 0, 1), "both features give the same gain, so split on feature 0"