← MAIN
LAB // DECISION TREES

TREE LAB

Paint points on a plane and watch a decision tree cut it into regions. A random forest averages many trees into one boundary.
LEAVES 0 TRAIN — TEST — STATUS READY

HOW TO USE

The goal is to see how a decision tree divides the plane into regions, and how a random forest smooths those regions. Paint points in two to four classes, or load a preset such as XOR.

Press STEP to make one split, or PLAY to let the tree grow on its own. Switch to RANDOM FOREST to train many trees on random samples. The forest retrains whenever a setting changes, and TRAIN FOREST retrains it on demand.

Hover the plane, or a box in the tree diagram, to see the region it covers. The accuracy chart shows where deeper trees start to overfit.

Paint points below, or load a preset. Hover the plane or a tree node to see the region it covers.
TREE DIAGRAM
100%
Paint at least two classes to grow a tree.
Box: split rule, impurity, rows, class bars. Pure leaves glow; dashed boxes are queued.
ACCURACY VS DEPTH
train test
Deeper trees fit the training rows better. Test accuracy stops improving, then falls: that gap is overfitting.
DATA
PRESET
SPLITTING
IMPURITY
MAX DEPTH
TREE
More settings
SEED (same seed, same points)
TEST SHARE
MIN SAMPLES PER LEAF
PRUNE α
Cost-complexity pruning: raise α to collapse the weakest splits first.
READOUT

HOW IT WORKS

A **decision tree** is a classifier that answers a chain of yes/no questions about a point's features. Each question is a **split** of the form x < t on one feature, and the answer sends the point down one of two branches. A **random forest** trains many such trees on random samples of the data and averages their predictions. The page runs a JavaScript port of the Python package in `treelab/`, which builds the same tree node for node from the same seed1.

Tree structure and prediction

Each **internal node** stores a feature and a **threshold**. A point goes to the left child when its value on that feature is less than the threshold, and to the right child otherwise. A node with no children is a **leaf**. Each leaf predicts from the training rows that reached it. Its class distribution is the share of each class among those rows, and its label is the most frequent class, with ties going to the lowest class index23.

\hat p_k = \frac{n_k}{n}, \qquad \text{label} = \arg\max_k n_k
4

Here n_k is the number of training rows of class k that reached the leaf, and n is the leaf's total. The label is the class with the largest n_k.

Impurity: Gini and entropy

**Impurity** measures how mixed the classes in a node are. It is zero for a pure node and largest when the classes are evenly mixed. The lab offers two measures. **Gini impurity** is the chance that two rows drawn at random from the node, with replacement, have different classes. **Entropy** is the average number of bits needed to name the class of a random row from the node56.

G = 1 - \sum_{k=1}^{K} p_k^{2}, \qquad H = -\sum_{k:\,p_k > 0} p_k \log_2 p_k, \qquad p_k = \frac{n_k}{n}
789

Here K is the number of classes, n_k the rows of class k in the node, n the node's total, and p_k the class share. The code returns 0 for an empty or pure node. In the entropy sum a term with p_k = 0 is skipped, since p \log_2 p tends to 0 as p tends to 0. Gini needs no logarithm, so it is cheaper to evaluate for every candidate threshold, and it is the default.

Example. A node with 6 rows of class A and 2 of class B has p = (0.75,\ 0.25). Its Gini impurity is 1 - (0.5625 + 0.0625) = 0.375, and its entropy is -(0.75 \log_2 0.75 + 0.25 \log_2 0.25) \approx 0.811 bits.

Information gain

A split is scored by its **information gain**, the drop in impurity that it buys. The two children are weighted by their share of the rows, so a split does not win just by sending a few rows somewhere1011.

\Delta = I(S) - \frac{n_L}{n}\, I(S_L) - \frac{n_R}{n}\, I(S_R)
1011

Here S is the set of rows at the node, I is the chosen impurity, and n = |S|. The split sends S_L left and S_R right, with n_L and n_R rows. The code calls these m, nl and nr.

Example. A split that sends the six A rows left and the two B rows right leaves both children pure. Its gain is the whole parent impurity: 0.375 with Gini.

Finding the best split

**Greedy** search means the best split at the current node is taken and never reconsidered. The search tries every split on each candidate feature. The rows are sorted on that feature, and a candidate threshold sits at the midpoint of each pair of neighbouring distinct values. A row goes left when its value is strictly less than the threshold. Candidates that leave a child with fewer rows than the **minimum samples per leaf** are skipped1213.

The midpoint is t = (v_i + v_{i+1}) / 2 for neighbouring sorted values v_i < v_{i+1}. If rounding makes t no greater than v_i, the code uses v_{i+1}, so the left side is exactly the rows at or below v_i1415. Within one feature, the first candidate within \varepsilon = 10^{-12} of the largest gain wins. Across features, a later feature replaces the best so far only if its gain is larger by more than \varepsilon. So a tie keeps the earlier feature and the smaller threshold1617.

1819
function BEST-SPLIT(rows, features):
    parent ← IMPURITY(class counts of rows)
    best ← none
    for each feature f in features:
        sort rows by their value on f
        for each pair of neighbouring rows with different values:
            t ← midpoint of the two values
            gain ← parent − (n_L / n) · IMPURITY(left) − (n_R / n) · IMPURITY(right)
            if both sides have at least min leaf rows, record (gain, t) for f
        keep the threshold with the largest gain on f
        if the gain beats best by more than ε:
            best ← (f, t, gain)
    return best

The **stable sort** keeps rows with equal values in the order they came in, so the result is the same for any sort that is stable. The check v_i < v_{i+1} skips pairs with equal values, since no threshold can separate them. The **EPS** test makes floating-point rounding count as a tie, so tiny differences in arithmetic do not change which split is chosen2021.

Growing the tree

The **builder** is breadth-first. A first-in, first-out queue holds the **frontier**, the nodes not yet decided. Each step takes the node at the front of the queue. It either makes that node a leaf, or splits it and appends its two children to the back. Growing to the end gives the same tree as recursion, but one split at a time lets the lab animate the growth. A node becomes a leaf when it is pure, when it is at the maximum depth, when it has fewer than twice the minimum leaf size in rows, or when no split beats EPS2223.

2425
function GROW-TREE(rows, depth):
    if rows are pure or depth = max depth or too few rows:
        return a leaf with the majority class
    split ← BEST-SPLIT(rows, all features)
    if split is none:
        return a leaf with the majority class
    left ← rows with x[feature] < threshold
    right ← the other rows
    return a node holding the split, with GROW-TREE(left, depth + 1)
        and GROW-TREE(right, depth + 1) as children

The full version is the loop that grow() runs: each pass through the loop splits at most one node, and the loop ends when the queue is empty. The feature subset is drawn only when a limit is set, so a plain tree draws no random numbers. Each of the first m positions is filled by a uniform random choice among the features not yet placed, so the subset is uniform2627.

Accuracy against depth and overfitting

**Overfitting** means a model fits the noise in its training rows, so its accuracy on new rows falls below its accuracy on the training rows. The lab measures it with a **train/test split** (see Data). For each depth from 1 to 12, it grows a tree on the training rows with the current impurity and minimum leaf size, then records accuracy on both sets28. Training accuracy cannot fall as depth grows, because a split can only keep or raise the number of training rows that a node gets right. Test accuracy rises, peaks, and then tends to fall. The readout reports overfitting when training accuracy beats test accuracy by more than 12 percentage points29.

Cost-complexity pruning

**Cost-complexity pruning** removes splits that do not pay for themselves. The **risk** R(t) of a node is the number of training rows its majority vote gets wrong, divided by the number of rows at the root3031. A subtree T_t has the risk of its leaves added together. The **link strength** of an internal node measures how much risk the subtree removes per extra leaf. Collapsing the subtree raises the risk by R(t) - R(T_t), and that rise is shared over the leaves it removes3233.

g(t) = \frac{R(t) - R(T_t)}{\lvert \text{leaves}(T_t) \rvert - 1}, \qquad R(t) = \frac{n(t) - \max_k n_k(t)}{N}
3435

Here N is the number of rows at the root, n(t) the rows at node t, and R(T_t) the sum of the risks of the leaves of T_t. The denominator counts the splits in the subtree. The **weakest link** is the internal node with the smallest g(t). When two nodes tie, the one earlier in pre-order wins3637.

The parameter \alpha (PRUNE α) sets the price of a leaf. While the weakest link has g(t) \le \alpha, its subtree is replaced by a leaf. Larger \alpha removes more splits, so the number of leaves never rises as \alpha rises. The diagram shows a pruned copy, and the full tree stays grown underneath38. SWEEP α animates \alpha from 0 up to the larger of 0.005 and 1.05 times the largest link strength of the full tree, so the diagram shrinks step by step39.

4041
function PRUNE(tree, α):
    while true:
        t ← the internal node with the smallest link strength g(t)
        if there is no such node or g(t) > α:
            return tree
        replace t by a leaf, dropping its subtree

The input is copied first, so the tree that the page keeps growing is never changed. Each pass rescans the pruned copy, because collapsing one link changes the risks above it. The loop stops at the first pass where no link is weak enough4243.

Bagging and bootstrap samples

**Bagging** (bootstrap aggregating) trains each tree on a **bootstrap sample**: n rows drawn with replacement from the n training rows, so some rows appear twice and others not at all. The rows a tree never draws are its **out-of-bag** rows. Each tree gets its own seed from one master stream, and it draws its bootstrap rows before its first split4445.

P(\text{row not drawn}) = \Bigl(1 - \frac{1}{n}\Bigr)^{n} \;\longrightarrow\; e^{-1} \approx 0.368
4647

Here n is the number of training rows. Each draw misses a given row with probability 1 - 1/n, and the n draws are independent. So about 37% of rows are out of bag for each tree. Without bootstrap, every tree sees all rows, and the trees then differ only in their feature subsets.

Random forests and out-of-bag accuracy

A **random forest** adds a second source of variety: at each split, the tree may test only a random subset of m features. The default is m = \max(1, \lfloor \sqrt{p} \rfloor), where p is the number of features. With the extra features on, p = 4 and m = 2. Without them, p = 2 and m = 14849.

The forest predicts by averaging the leaf distributions of its T trees, and it labels a point with the class of largest average. In the boundary drawing, the faint lines are single trees and the glowing region is the average5051.

\bar p_k(x) = \frac{1}{T} \sum_{t=1}^{T} \hat p^{(t)}_k(x)
5051

Here \hat p^{(t)}_k(x) is the leaf distribution of tree t for the point x. The out-of-bag accuracy scores each row only with the trees that did not train on it. Let O_i be the trees whose bootstrap sample left row i out.

\hat y_i = \arg\max_k \frac{1}{\lvert O_i \rvert} \sum_{t \in O_i} \hat p^{(t)}_k(x_i), \qquad \text{OOB} = \frac{1}{\lvert \mathcal{S} \rvert} \sum_{i \in \mathcal{S}} \mathbf{1}[\hat y_i = y_i]
5253

Here \mathcal{S} is the set of rows left out by at least one tree, and \mathbf{1}[\cdot] is 1 when the statement is true and 0 otherwise. Rows that every tree drew are skipped. The out-of-bag accuracy is a free estimate of test accuracy, obtained without a separate test set.

5455
function FIT-FOREST(X, y, T, seed):
    master ← a random stream seeded with seed
    repeat T times:
        tree-stream ← a random stream seeded from master
        rows ← n indices drawn with replacement
        tree ← GROW-TREE(rows, using m random features per split)
        keep tree and which rows it drew
    oob ← out-of-bag accuracy over the trees
    importance ← mean feature importance over the trees
    return the forest

The **in-bag** rows of a tree are the ones it drew, so the out-of-bag list is their complement. Each tree's stream is seeded from the master stream, so the forest is reproducible from one seed. One seed therefore reproduces the whole forest5657.

Feature importance

The **feature importance** of a feature is the total impurity decrease that it buys over a tree's splits, each split weighted by the number of training rows that reached it. Each tree's values are normalised to sum to 1, and the forest reports their mean5859.

I_t(f) = \sum_{v \,\in\, \text{splits on } f} n(v)\, \Delta(v), \qquad \text{importance}(f) = \frac{1}{T} \sum_{t=1}^{T} \frac{I_t(f)}{\sum_{g} I_t(g)}
5859

Here n(v) is the number of training rows, bootstrap copies included, that reached node v, and \Delta(v) is its gain from the information gain formula above60. If a tree has no splits, its total is zero and its raw values, all zero, are used as they are.

Data, presets and the train/test split

Every random draw, from the presets to the bootstrap samples, comes from **mulberry32**, a generator with a single 32-bit integer state. The Python and browser builds use the same constants6162. Each preset is 240 points in the unit square, drawn from that generator. The label rules are as follows6364.

XOR labels a point 1 when x and y lie on different sides of 0.5, and 0 otherwise65.

Checkerboard cuts the plane into a 4 × 4 board and labels the squares alternately, by the parity of the square's column plus row index66.

Noisy diagonal labels 1 when x > y, and then flips each label with probability 0.156768.

Nested rings label each point by its squared distance d^2 = (x - 0.5)^2 + (y - 0.5)^2 from the centre: class 0 if d^2 < 0.04, class 1 if d^2 < 0.13, and class 2 otherwise69.

Blobs draw each class from a disc of radius 0.16 around its centre, at (0.25, 0.3), (0.7, 0.35) and (0.5, 0.75). Points are chosen by rejection sampling, so no trigonometry is needed7071.

Spirals place the two arms along a curve of parameter t in [0, 1):

\theta = 3.5\pi t + a\pi, \quad r = 0.04 + 0.4\,t, \quad (x, y) = \bigl(0.5 + r\cos\theta + j_x,\ 0.5 + r\sin\theta + j_y\bigr)
7273

Here a \in \{0, 1\} is the arm, and j_x and j_y are independent jitters, each drawn uniformly from [-0.02, 0.02]. The label is the arm.

The **features** the trees split on are the plane's coordinates, optionally with two derived ones. When extra features are on, each point becomes \phi(x, y) = (x,\ y,\ xy,\ x^2 + y^2). The derived features let an axis-aligned split draw a curved boundary7475.

The **train/test split** holds out a share f of the rows. A seeded Fisher-Yates shuffle orders the row indices, and the first n_{\text{test}} = \lfloor f\,n + 0.5 \rfloor of them form the test set, with the rest used for training. The split always uses seed 1, so changing the preset seed does not change which rows are held out767778.

Parameters, defaults and why

The defaults below are the page's starting values79.

ParameterDefaultWhy
ImpurityGiniIn most cases ranks candidate splits much like entropy, and needs no logarithm for each threshold. Switch to entropy to see the difference.
Max depth5Deep enough to show the structure of blobs and XOR, and shallow enough that the diagram stays readable. The accuracy-vs-depth chart shows where going deeper stops helping.
Min samples per leaf3A leaf of one or two rows is a single noisy point. Three rows keep each region backed by several neighbours.
Test share0.3A common split: enough held-out rows to see the train/test gap, while most of the data still trains the model.
Extra featuresOnx·y and x²+y² let an axis-aligned tree draw curved boundaries. Without them, XOR and rings need many small steps.
Features tried per split√pWith extra features on, that is 2 of the 4 features at each split.
Prune α0No pruning until asked. Pruning changes only the displayed tree; the full tree stays grown underneath.
Trees25Enough votes that the averaged boundary is smooth. The slider goes to 100 to compare.
Bootstrap rowsOnEach tree gets a different sample, and the out-of-bag rows give an accuracy estimate. Off means every tree sees the same rows.

Reading the numbers: Train accuracy only goes up as the tree deepens. Test accuracy rises, peaks, and falls. The forest's out-of-bag accuracy is a free estimate of its test accuracy, not an exact one. The noisy diagonal flips 15% of its labels, so the rule x > y scores about 85% on new rows and no model can do much better. On that preset the forest is usually ahead of a single deep tree, though not on every seed8068.