Reading history

Decision Tree From Scratch in Python: Gini Impurity and Best Splits

7 min read 1 views

Build a decision tree from scratch in Python. Compute Gini impurity, find the best split, grow the tree with recursion and compare it with scikit-learn.

A decision tree asks a chain of yes/no questions, like “Is petal length 2.45 cm or less?”, until it reaches an answer. But how does it choose each question? In this lesson you will build a decision tree from scratch in Python. You will measure how mixed a group is with Gini impurity, test every possible split, and grow the tree one level at a time. Your tree will match scikit-learn’s accuracy on the iris flowers.

In this lesson you will learn

  • What Gini impurity measures and how to compute it
  • How a tree scores every candidate split
  • How recursion grows the tree and when it stops
  • How a new row walks down the tree to get a prediction
  • How your tree compares with DecisionTreeClassifier

You should know decision trees and random forests, basic NumPy and recursion in Python.

Gini Impurity

A good question splits the data into groups that are each mostly one class. To compare questions, we need a number for how mixed a group is. Gini impurity is that number:

gini = 1 − (p₁² + p₂² + …), where each p is the share of one class in the group.

  • A pure group (all one class) has Gini 0.
  • A 50/50 mix of two classes has Gini 1 − (0.25 + 0.25) = 0.5, the worst case for two classes.

Another way to read it: pick two items from the group at random. Gini is the chance they belong to different classes.

Finding the Best Split

We have 8 students, the hours each one studied, and whether they passed. To score a split, we compute the Gini of each side and take a weighted average, so a bigger side counts more. The best split has the lowest weighted Gini.

import numpy as np

def gini(labels):
    """Gini impurity: chance two random picks have different classes."""
    _, counts = np.unique(labels, return_counts=True)
    p = counts / counts.sum()
    return 1 - (p ** 2).sum()

# Hours studied and whether the student passed (1) or failed (0)
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8])
passed = np.array([0, 0, 0, 1, 0, 1, 1, 1])
print(f"gini of all 8 students: {gini(passed):.3f}")

# Try a threshold halfway between each pair of neighbouring values
for t in (hours[:-1] + hours[1:]) / 2:
    left, right = passed[hours <= t], passed[hours > t]
    weighted = (len(left) * gini(left) + len(right) * gini(right)) / len(passed)
    print(f"hours <= {t}: left {left}  right {right}  weighted gini {weighted:.3f}")

Output

gini of all 8 students: 0.500
hours <= 1.5: left [0]  right [0 0 1 0 1 1 1]  weighted gini 0.429
hours <= 2.5: left [0 0]  right [0 1 0 1 1 1]  weighted gini 0.333
hours <= 3.5: left [0 0 0]  right [1 0 1 1 1]  weighted gini 0.200
hours <= 4.5: left [0 0 0 1]  right [0 1 1 1]  weighted gini 0.375
hours <= 5.5: left [0 0 0 1 0]  right [1 1 1]  weighted gini 0.200
hours <= 6.5: left [0 0 0 1 0 1]  right [1 1]  weighted gini 0.333
hours <= 7.5: left [0 0 0 1 0 1 1]  right [1]  weighted gini 0.429
  • We only test thresholds halfway between neighbouring values. Any threshold between 3 and 4 gives the same groups, so 3.5 stands for all of them.
  • Two splits tie at 0.200. At 3.5 the left side is pure (three fails) and the right has one stray fail. At 5.5 the right side is pure and the left has one stray pass.
  • The student who studied 5 hours but failed breaks the pattern. No single split can be perfect, which is why trees keep splitting.
0.00.10.20.30.40.5Threshold (hours studied)Weighted Ginino split: 0.5000.429≤ 1.50.333≤ 2.50.200≤ 3.50.375≤ 4.50.200≤ 5.50.333≤ 6.50.429≤ 7.5Lowest bars (green) are the best splits: 3.5 and 5.5 tie

Growing the Whole Tree

A full tree repeats the search on each side of a split. It stops when it reaches the depth limit or when no split lowers the Gini. Each stop becomes a leaf that predicts the most common class in it. We store a split as a tuple (feature, threshold, left, right) and a leaf as a plain class number.

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

def gini(y):
    p = np.bincount(y) / len(y)
    return 1 - (p ** 2).sum()

def best_split(X, y):
    best = (None, None, gini(y))                 # (feature, threshold, score)
    for f in range(X.shape[1]):
        values = np.unique(X[:, f])
        for t in (values[:-1] + values[1:]) / 2:
            mask = X[:, f] <= t
            score = (mask.sum() * gini(y[mask]) + (~mask).sum() * gini(y[~mask])) / len(y)
            if score < best[2]:
                best = (f, t, score)
    return best

def build(X, y, depth, max_depth):
    f, t, _ = best_split(X, y)
    if depth == max_depth or f is None:          # stop: make a leaf
        return np.bincount(y).argmax()
    mask = X[:, f] <= t
    return (f, t, build(X[mask], y[mask], depth + 1, max_depth),
                  build(X[~mask], y[~mask], depth + 1, max_depth))

def predict_one(node, row):
    while isinstance(node, tuple):               # walk down until a leaf
        f, t, left, right = node
        node = left if row[f] <= t else right
    return node

X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0, stratify=y)
tree = build(X_tr, y_tr, 0, max_depth=3)
print("root split:", load_iris().feature_names[tree[0]], "<=", tree[1])
mine = np.mean([predict_one(tree, r) == t for r, t in zip(X_te, y_te)])
sk = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_tr, y_tr).score(X_te, y_te)
print(f"our tree accuracy    : {mine:.3f}")
print(f"scikit-learn accuracy: {sk:.3f}")

Output

root split: petal length (cm) <= 2.45
our tree accuracy    : 0.947
scikit-learn accuracy: 0.947
  • best_split loops over every column and every halfway threshold. It keeps a split only if it beats the Gini of the group with no split.
  • build calls itself on the left rows and the right rows. This is recursion: the same job on smaller and smaller pieces.
  • The root question is “petal length ≤ 2.45 cm”. That one cut puts every setosa flower on the left, so that side is pure at once.
  • Our tree and scikit-learn’s both reach 94.7% on the 38 test flowers. Scikit-learn uses the same idea, written in fast compiled code with many extra options.

Our Tree Versus scikit-learn

FeatureOur treeDecisionTreeClassifier
Split measureGiniGini, entropy or log loss
Stopping rulesDepth limitDepth, minimum samples, minimum impurity drop and more
SpeedSlow in PythonFast, written in Cython
RegressionNoYes, with DecisionTreeRegressor
Ties between splitsFirst one foundCan depend on random_state

Regression trees

For numbers instead of classes, swap Gini for the variance of the target in each group. A leaf then predicts the mean of its rows. Everything else stays the same.

Common Mistakes

  1. Forgetting to weight by group size. A pure group of 1 row should not count as much as a mixed group of 100.
  2. Testing every raw value instead of midpoints. It works, but a threshold equal to a data value puts that row on an awkward edge. Midpoints are cleaner.
  3. No stopping rule. Without a depth limit, the tree keeps splitting until every leaf is pure and memorises the training data.
  4. Splitting an empty group. Always check that both sides of a split have rows.

Practice Exercises

Exercise 1. Compute by hand the Gini of a group with 6 passes and 2 fails.

Show answer

p(pass) = 0.75 and p(fail) = 0.25, so Gini = 1 − (0.5625 + 0.0625) = 0.375.

Exercise 2. Add a min_samples rule to build: make a leaf if a group has fewer than 5 rows.

Show answer
def build(X, y, depth, max_depth, min_samples=5):
    if len(y) < min_samples or depth == max_depth:
        return np.bincount(y).argmax()
    f, t, _ = best_split(X, y)
    if f is None:
        return np.bincount(y).argmax()
    mask = X[:, f] <= t
    return (f, t, build(X[mask], y[mask], depth + 1, max_depth, min_samples),
                  build(X[~mask], y[~mask], depth + 1, max_depth, min_samples))

Frequently Asked Questions

Is Gini or entropy better?

They almost always choose the same splits. Gini is a little faster because it needs no logarithm, which is why scikit-learn uses it by default.

Why write a tree from scratch if scikit-learn has one?

To understand what the settings do. Once you have written best_split and build, options such as max_depth and min_samples_leaf stop being magic words.

Summary

  • Gini impurity measures how mixed a group is: 0 is pure.
  • The best split has the lowest size-weighted Gini.
  • A tree grows by repeating the search on each side.
  • Depth limits stop the tree from memorising the data.

Next: Backpropagation From Scratch in NumPy.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *