Module 10 · Intermediate · Decision trees

Decision tree from scratch in Python

Build a decision tree classifier from scratch in Python with NumPy: Gini impurity, finding the best split, growing the tree recursively, and checking it against scikit-learn.

By theprogrammers team · · 14 min read

A decision tree feels like magic until you build one. Then it turns out to be three small ideas: a score for how mixed a group is, a search for the question that makes groups less mixed, and a function that asks itself the same thing again for each smaller group. Building a decision tree from scratch in Python takes about 50 lines of NumPy, and afterwards every setting in scikit-learn's DecisionTreeClassifier makes sense.

What you need first: decision trees explained, for Gini impurity and how trees split, and Python functions that call themselves, explained below as they come up.

Key terms

  • Gini impurity: 1 minus the sum of each class's squared share; 0 for a pure group, 0.5 for a 50/50 group of two classes.
  • Candidate threshold: a cut-off worth testing, halfway between two neighbouring values of a feature.
  • Weighted impurity: the impurity of the two groups after a split, each weighted by its size.
  • Recursion: a function that solves a problem by calling itself on smaller pieces of it.
  • Greedy: choosing the best step now, without looking ahead to later steps.

The plan

A tree is built by one function, grow, which receives some rows:

  1. If the rows are pure, or the tree is deep enough, stop and make a leaf that predicts the majority class.
  2. Otherwise, find the best question: the feature and cut-off whose split leaves the least weighted impurity.
  3. Split the rows in two, and call grow again on each half. Those calls do the same thing, until every branch ends in a leaf.

Steps 1 and 2 are ordinary functions. Step 3 is the recursion.

Step 1: Gini impurity

Gini = 1 − (p₁² + p₂² + …)

Read it as "one minus the sum of the squares of each class's share". If a group is 3 survivors and 1 non-survivor, the shares are 0.75 and 0.25, so Gini = 1 − (0.5625 + 0.0625) = 0.375.

import numpy as np

def gini(y):
    _, counts = np.unique(y, return_counts=True)
    shares = counts / len(y)
    return 1 - np.sum(shares ** 2)

print(gini(np.array([1, 1, 1, 0])))
print(gini(np.array([0, 0, 0, 0])))
print(gini(np.array([0, 1, 0, 1])))
0.375
0.0
0.5

np.unique(y, return_counts=True) returns each distinct class and how many times it appears; only the counts are needed, so the classes go into _, Python's name for "a value I don't need". The three results match the hand calculation, a pure group and a 50/50 group.

Step 2: find the best question

To test one question, such as "is hours at most 4.5?", split the labels into a left group (yes) and a right group (no), and average their impurities, weighted by size: a group of 90 rows should count more than a group of 2.

Which cut-offs are worth testing? Between two neighbouring values, every cut-off splits the rows the same way, so only one per gap is needed. Like scikit-learn, the code uses the midpoint of each gap.

def best_split(X, y):
    best = None                                     # (weighted impurity, feature, threshold)
    for feature in range(X.shape[1]):
        values = np.unique(X[:, feature])           # sorted distinct values
        for threshold in (values[:-1] + values[1:]) / 2:
            left = X[:, feature] <= threshold
            n_left, n_right = left.sum(), (~left).sum()
            score = (n_left * gini(y[left]) + n_right * gini(y[~left])) / len(y)
            if best is None or score < best[0]:
                best = (score, feature, threshold)
    return best

(values[:-1] + values[1:]) / 2 adds each value to the next one and halves the result: the midpoints of all the gaps. left is a True/False mask, and ~left flips it to select the other rows.

Predict first: six students, with hours studied and whether they passed. Which cut-off will best_split choose, and what will its weighted impurity be?

hours = np.array([[1], [2], [3], [6], [7], [8]])
passed = np.array([0, 0, 0, 1, 1, 1])
print(best_split(hours, passed))
(np.float64(0.0), 0, np.float64(4.5))

The cut-off 4.5 sits in the gap between 3 and 6 hours and separates the groups perfectly, so the weighted impurity is 0. The output shows NumPy number types, such as np.float64(0.0); they behave like ordinary numbers.

Step 3: grow the tree

A node is stored as a dictionary. A leaf holds its prediction and the class counts; a question node holds the feature, the threshold, and two more nodes: left for "yes" and right for "no". Each of those is again a leaf or a question node, which is what makes a tree.

def grow(X, y, depth=0, max_depth=3, min_samples_leaf=1):
    classes, counts = np.unique(y, return_counts=True)
    leaf = {"predict": classes[np.argmax(counts)], "counts": dict(zip(classes.tolist(), counts.tolist()))}

    if depth == max_depth or len(classes) == 1 or len(y) < 2 * min_samples_leaf:
        return leaf
    split = best_split(X, y)
    if split is None or split[0] >= gini(y):        # no question makes the groups purer
        return leaf

    _, feature, threshold = split
    left = X[:, feature] <= threshold
    if left.sum() < min_samples_leaf or (~left).sum() < min_samples_leaf:
        return leaf
    return {
        "feature": feature,
        "threshold": threshold,
        "left": grow(X[left], y[left], depth + 1, max_depth, min_samples_leaf),
        "right": grow(X[~left], y[~left], depth + 1, max_depth, min_samples_leaf),
    }

Read it top to bottom:

  • np.argmax(counts) finds the position of the biggest count, so classes[...] is the majority class.
  • Three reasons to stop straight away: the tree is deep enough, the rows are all one class, or there are too few rows to make two leaves of min_samples_leaf each.
  • If even the best question doesn't lower the impurity, splitting is pointless, so the node becomes a leaf.
  • Otherwise, grow calls itself for each half, one level deeper. This is recursion. It always ends, because every call either returns a leaf or works on fewer rows.

To predict, start at the root and follow the answers until you reach a leaf:

def predict_one(node, x):
    while "predict" not in node:                    # until we reach a leaf
        node = node["left"] if x[node["feature"]] <= node["threshold"] else node["right"]
    return node["predict"]

def predict(tree, X):
    return np.array([predict_one(tree, x) for x in X])

def show(node, names, indent="", label=""):
    if "predict" in node:
        print(f"{indent}{label}predict {node['predict']}  {node['counts']}")
        return
    print(f"{indent}{label}{names[node['feature']]} <= {node['threshold']:.2f}?")
    show(node["left"], names, indent + "    ", "yes: ")
    show(node["right"], names, indent + "    ", "no:  ")

show prints the tree with the same recursion as grow: print the question, then each branch, indented four spaces further and labelled with the answer that leads to it.

Test it on iris flowers

The 150 iris flowers, with all four measurements:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, test_size=0.3, stratify=iris.target, random_state=0)

my_tree = grow(X_train, y_train, max_depth=2)
show(my_tree, iris.feature_names)
print("test accuracy:", round(np.mean(predict(my_tree, X_test) == y_test), 3))
petal length (cm) <= 2.35?
    yes: predict 0  {0: 35}
    no:  petal width (cm) <= 1.75?
        yes: predict 1  {1: 34, 2: 3}
        no:  predict 2  {1: 1, 2: 32}
test accuracy: 0.956

The classes are numbers: 0 is setosa, 1 versicolor, 2 virginica. The first question is about petal length, and the counts show it separating all 35 setosas (class 0) from the rest.

Check it against scikit-learn

Predict first: will scikit-learn's tree, with the same depth, ask the same questions?

from sklearn.tree import DecisionTreeClassifier, export_text

sk_tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_train, y_train)
print(export_text(sk_tree, feature_names=iris.feature_names))
sk_pred, my_pred = sk_tree.predict(X_test), predict(my_tree, X_test)
print("same prediction for", np.sum(sk_pred == my_pred), "of", len(y_test), "test flowers")
|--- petal width (cm) <= 0.80
|   |--- class: 0
|--- petal width (cm) >  0.80
|   |--- petal width (cm) <= 1.75
|   |   |--- class: 1
|   |--- petal width (cm) >  1.75
|   |   |--- class: 2

same prediction for 45 of 45 test flowers

The questions differ at the root but the predictions are identical. Petal length at most 2.35 and petal width at most 0.8 both separate the setosas perfectly, so they tie on impurity. The code above keeps the first one it finds (score < best[0], strictly smaller), and petal length comes first in the columns. Scikit-learn shuffles the order in which it tries features, controlled by random_state, so it found petal width first. Ties like this are common, which is one reason two trees trained on the same data can look different.

On real data: Titanic

The same features as decision trees explained: class, age, fare, family aboard, and sex as a 0/1 column. .to_numpy() turns the tables into plain arrays, which is what grow expects.

Download the data: titanic.csv (58 KB), or from the original source, the seaborn-data repository on GitHub. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("titanic.csv").

import seaborn as sns

titanic = sns.load_dataset("titanic")
data = titanic[["survived", "pclass", "sex", "age", "fare", "sibsp", "parch"]].copy()
data["is_female"] = (data.pop("sex") == "female").astype(int)
data["age"] = data["age"].fillna(data["age"].median())
names = ["pclass", "age", "fare", "sibsp", "parch", "is_female"]

Xt_train, Xt_test, yt_train, yt_test = train_test_split(
    data[names].to_numpy(), data["survived"].to_numpy(), test_size=0.2,
    stratify=data["survived"], random_state=42)

titanic_tree = grow(Xt_train, yt_train, max_depth=3)
show(titanic_tree, names)
sk_titanic = DecisionTreeClassifier(max_depth=3, random_state=0).fit(Xt_train, yt_train)
print("mine:        ", round(np.mean(predict(titanic_tree, Xt_test) == yt_test), 3))
print("scikit-learn:", round(sk_titanic.score(Xt_test, yt_test), 3))
is_female <= 0.50?
    yes: age <= 3.50?
        yes: sibsp <= 2.50?
            yes: predict 1  {1: 12}
            no:  predict 0  {0: 2, 1: 1}
        no:  pclass <= 1.50?
            yes: predict 0  {0: 58, 1: 33}
            no:  predict 0  {0: 314, 1: 39}
    no:  pclass <= 2.50?
        yes: fare <= 28.86?
            yes: predict 1  {0: 6, 1: 48}
            no:  predict 1  {0: 1, 1: 82}
        no:  fare <= 23.35?
            yes: predict 1  {0: 40, 1: 55}
            no:  predict 0  {0: 18, 1: 3}
mine:         0.81
scikit-learn: 0.81

The from-scratch tree rediscovers the same rules as scikit-learn's ("is the passenger female?", then age for males and class for females) and scores the same on the test passengers. Some branches end in two leaves that predict the same class: the split made the groups purer without changing the majority, exactly as in the scikit-learn tree.

Experiment: how min_samples_leaf changes the tree

min_samples_leaf is the most useful single setting for stopping a tree overfitting. Experiment: grow trees with no depth limit and different minimum leaf sizes, count the leaves, and predict which scores best on passengers it hasn't seen.

The test set has only 179 passengers, so one lucky or unlucky passenger moves its score by half a point. A fairer judge is cross-validation: StratifiedKFold hands out the row positions of 5 folds, and the loop trains your tree on 4 folds and scores it on the fifth.

from sklearn.model_selection import StratifiedKFold

def count_leaves(node):
    return 1 if "predict" in node else count_leaves(node["left"]) + count_leaves(node["right"])

folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for leaf_size in [1, 5, 20, 60]:
    scores = []
    for fit_rows, check_rows in folds.split(Xt_train, yt_train):
        t = grow(Xt_train[fit_rows], yt_train[fit_rows], max_depth=50, min_samples_leaf=leaf_size)
        scores.append(np.mean(predict(t, Xt_train[check_rows]) == yt_train[check_rows]))
    full = grow(Xt_train, yt_train, max_depth=50, min_samples_leaf=leaf_size)
    train_acc = np.mean(predict(full, Xt_train) == yt_train)
    print(f"min_samples_leaf={leaf_size:2}: leaves {count_leaves(full):3}, train {train_acc:.3f}, cross-validated {np.mean(scores):.3f}")
min_samples_leaf= 1: leaves 161, train 0.982, cross-validated 0.777
min_samples_leaf= 5: leaves  21, train 0.865, cross-validated 0.812
min_samples_leaf=20: leaves   6, train 0.813, cross-validated 0.788
min_samples_leaf=60: leaves   3, train 0.789, cross-validated 0.782

folds.split gives the row positions for each round: fit_rows to train on, check_rows to score. With leaves of 1 row, the tree grows 161 leaves and scores 0.982 on its own training data but 0.777 on passengers it hasn't seen: it has memorised individuals. Leaves of 5 cut it to 21 leaves and give the best cross-validated score, 0.812. Leaves of 20 or 60 are too blunt to capture the real patterns. Too flexible and too rigid both lose, which is the bias-variance trade-off in one table.

count_leaves is recursive too: a leaf counts 1, and a question node counts the leaves of both branches. max_depth=50 is effectively "no limit".

See it fail: when greedy isn't enough

A tree picks the best question now, without looking ahead. That's called greedy, and it's usually fine. Here's a case where it isn't. Each point has two features, 0 or 1, and the label is 1 when exactly one of them is 1 (this pattern is called XOR):

X_xor = np.array([[0, 0], [0, 1], [1, 0], [1, 1]] * 10)
y_xor = np.array([0, 1, 1, 0] * 10)

for feature in [0, 1]:
    left = X_xor[:, feature] <= 0.5
    print(f"split on feature {feature}: left {np.bincount(y_xor[left])}, right {np.bincount(y_xor[~left])}")

xor_tree = grow(X_xor, y_xor, max_depth=2)
show(xor_tree, ["a", "b"])
print("scikit-learn depth 2:", DecisionTreeClassifier(max_depth=2).fit(X_xor, y_xor).score(X_xor, y_xor))
split on feature 0: left [10 10], right [10 10]
split on feature 1: left [10 10], right [10 10]
predict 0  {0: 20, 1: 20}
scikit-learn depth 2: 1.0

np.bincount counts the 0s and 1s in each group. Either split alone leaves both groups exactly 50/50, so no single question lowers the impurity, and the from-scratch tree gives up at the root: one leaf, right only half the time. Yet two questions in a row would solve the problem perfectly. Scikit-learn splits even when the impurity doesn't fall (its min_impurity_decrease setting defaults to 0), so it carries on to the second level and reaches 100%. On messier data, greedy choices can still lead a tree down a worse path, which is one reason random forests train many trees on different samples.

What scikit-learn adds

Your versionscikit-learn's DecisionTreeClassifier
Tries every midpoint with a loopSorts each feature once and scans it, written in fast compiled code
Gini onlyGini, entropy or log loss (criterion=)
Stops when no split helpsSplits as long as the impurity doesn't rise (min_impurity_decrease=0)
max_depth, min_samples_leafAlso min_samples_split, max_leaf_nodes, max_features, class_weight, pruning with ccp_alpha
Predicts a classAlso predict_proba: the class shares in the leaf

Use your version to understand trees; use scikit-learn's for real work.

Practice

  1. Without running code: what's the Gini impurity of a group with 8 of one class and 2 of another?
Show the answer

Shares 0.8 and 0.2: 1 − (0.64 + 0.04) = 0.32.

print(round(gini(np.array([0] * 8 + [1] * 2)), 3))
0.32
  1. Why does best_split only test midpoints between neighbouring values, and not every possible number?
Show the answer

Any cut-off between the same two neighbouring values sends exactly the same rows left and right, so it gives the same impurity. Testing one per gap is enough; the midpoint is a sensible choice because it sits furthest from both values, which helps new data that falls in the gap.

  1. Add a predict_proba_one(node, x) function that returns the share of class 1 in the leaf a row lands in. What does it give for the first Titanic test passenger?
Show the answer
def predict_proba_one(node, x):
    while "predict" not in node:
        node = node["left"] if x[node["feature"]] <= node["threshold"] else node["right"]
    counts = node["counts"]
    return counts.get(1, 0) / sum(counts.values())

print(round(predict_proba_one(titanic_tree, Xt_test[0]), 3))
print(sk_titanic.predict_proba(Xt_test[:1]).round(3))
0.11
[[0.89 0.11]]

The second number in scikit-learn's row is the share of survivors in the same leaf.

  1. In grow, what would happen if the line if split is None or split[0] >= gini(y): return leaf were removed, and why does the XOR example care?
Show the answer

The tree would split even when no question helps, like scikit-learn does. On XOR, the root split would then be accepted, and the second level could separate the classes perfectly. The function still ends, because the depth limit and the "all one class" check stop it, and best_split returns None when no feature has two different values.

  1. Why does grow make a leaf when len(y) < 2 * min_samples_leaf?
Show the answer

A split must leave at least min_samples_leaf rows on each side, so it needs at least twice that many rows in total. With fewer, no allowed split exists, so there's no point searching.

Interview questions

How would you implement a decision tree from scratch?

Write an impurity function such as Gini, a search over every feature and candidate threshold (midpoints between sorted unique values) for the split with the lowest size-weighted impurity, and a recursive build function that stops on purity, maximum depth or minimum leaf size and otherwise splits and recurses on both halves. Predict by walking from the root to a leaf.

What is the time complexity of training a decision tree?

Roughly O(n_features × n_samples × log n_samples) per level when each feature is sorted once and scanned, and the depth is about log n for a balanced tree. A naive version that recomputes impurity for every threshold is closer to quadratic in the number of samples per feature.

Why are decision trees called greedy?

At each node they choose the split that is best right now, without considering how it affects later splits. This makes training fast but can miss combinations, such as XOR patterns, where no single split helps but two together separate the classes.

Key takeaways

  • A tree is three pieces: an impurity score, a search for the best split, and a recursive build.
  • Candidate thresholds are midpoints between neighbouring values; each split is scored by size-weighted impurity.
  • Recursion ends at a leaf: when the rows are pure, the tree is deep enough, or no allowed split helps.
  • Ties between equally good questions are common, so trees from different tools can look different but predict the same.
  • Greedy splitting can miss patterns that need two questions together.

Frequently asked questions

Do I need to know how to code a tree from scratch?

Not to use one. But building it once explains every setting, why trees overfit, and why ensembles help, and it's a common interview exercise.

Why is my version so much slower than scikit-learn's?

It recomputes the impurity from scratch for every threshold with Python loops. Scikit-learn sorts each feature once, updates the class counts as it moves the threshold along, and runs in compiled C code.

How would a regression tree differ?

Replace Gini with the variance (or mean squared error) of the target in each group, and make each leaf predict the mean of its rows instead of the majority class.

What to learn next

  1. Put trees to work on a full project in Titanic survival prediction, the next lesson.
  2. Revisit Gini impurity and pruning in decision trees explained.
  3. See how many trees fix one tree's weaknesses in random forest explained.