Exercise: decision trees

Goal

By the end of this exercise you should be able to:

  • read a decision tree as questions on one feature at a time, and draw the rectangles it cuts the feature space into,
  • find the best split of a small table with the Gini impurity,
  • explain overfitting with training and test error, and choose a depth by cross-validation,
  • fit a small regression tree by hand,
  • (math) prove the basic properties of the impurity measures.

Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.

Background

Idea What it means
Feature space one axis per feature; each pixel or object is a point
Decision tree nodes ask “feature j \le t?”; leaves hold a class (or class shares)
Gini impurity G = 1 - \sum_k p_k^2: chance that two random points of the node have different classes
Entropy H = -\sum_k p_k \log_2 p_k (almost the same splits as Gini)
Impurity decrease \Delta = I(\text{parent}) - \tfrac{n_L}{n}I(L) - \tfrac{n_R}{n}I(R); the best split has the largest \Delta
Overfitting training error keeps falling with depth, test error rises again
Validation / test the validation set chooses settings; the test set is used once, at the end
k-fold cross-validation k rounds, each fold validates once; average the k errors
Regression tree leaves hold the mean; splits reduce the sum of squared errors

The parent’s class shares are the weighted mean of the children’s: p_k = \tfrac{n_L}{n}p_k^L + \tfrac{n_R}{n}p_k^R. Gini and entropy are concave functions of the shares, so (Jensen) I(\text{parent}) \ge \tfrac{n_L}{n}I(L) + \tfrac{n_R}{n}I(R), i.e. \Delta \ge 0. Equality holds when both children have the parent’s shares: such a split is useless.

By hand

B1. Eight pixels with intensity I and local variance V, classes nucleus N and background B:

I 20 35 45 50 60 80 90 110
V 2 3 5 9 12 4 15 11
class B B N B N B N N
  1. Compute the Gini impurity of the whole table.
  2. List the 7 possible thresholds on I and the weighted Gini of the children for each. Which is best?
  3. The same for V. Which question does the root ask?
  4. Is that surprising, if N means nucleus? What does V measure?

B2. A tree on the same two features: the root asks “V \le 6?”. If yes, it asks “I \le 100?” (yes: B, no: N). If no, it asks “I \le 40?” (yes: B, no: N). (a) Draw the four rectangles in the (I, V) plane, for I from 0 to 120 and V from 0 to 16, and colour them. (b) Classify the pixels (I, V) = (30, 10), (120, 3) and (70, 5).

B3. A tree is grown on 200 training pixels with maximum depth 2, and again with maximum depth 20. Predict for each: the training error and the error on new pixels from the same images. Which tree changes more if 10 training pixels are replaced by others?

B4. Five-fold cross-validation for four maximum depths gives these validation errors:

depth fold 1 fold 2 fold 3 fold 4 fold 5
1 0.30 0.28 0.33 0.31 0.29
3 0.20 0.22 0.18 0.21 0.19
6 0.17 0.19 0.16 0.20 0.18
12 0.24 0.21 0.26 0.23 0.22
  1. Which depth do you choose? (b) What do you do next, and when do you use the test set? (c) Why would it be wrong to report 0.18 as the error the method will make on new data, if you had tried 50 depths instead of 4?

B5. The pixels in B1 are measured again, with the intensity now stored as I' = \log(I) instead of I. What happens to the tree of B1? Would a nearest-neighbour classifier also stay the same?

B6. A line profile across a cell edge: positions x = 1, \dots, 6 with intensities y = 10, 12, 11, 30, 32, 31. A regression tree of depth 1 splits between two neighbouring positions. (a) For each of the 5 possible splits, compute the sum of squared errors of the two halves (each predicted by its mean). Which split wins? (b) Draw the fitted step function. What does a depth-2 tree add?

B7. You label 3000 pixels in one image and use a random 20 % of them as validation pixels. The validation error is 1 %. On a second image the error is 12 %. Explain. How should the validation pixels have been chosen?

B1. (a) 4 B and 4 N: G = 1 - 0.5^2 - 0.5^2 = 0.5. (b) Sorted by I the classes read B B N B N B N N. Weighted Gini for each threshold:

threshold left right weighted G
I \le 27.5 B B N B N B N N 0.429
I \le 40 B B N B N B N N 0.333
I \le 47.5 B B N B N B N N 0.467
I \le 55 B B N B N B N N 0.375
I \le 70 B B N B N B N N 0.467
I \le 85 B B N B N B N N 0.333
I \le 100 B B N B N B N N 0.429

For I \le 40: left pure (0), right 2 B + 4 N with G = 1 - (1/3)^2 - (2/3)^2 = 4/9, weighted \tfrac68 \cdot \tfrac49 = 0.333. (c) Sorted by V (2, 3, 4, 5, 9, 11, 12, 15) the classes read B B B N B N N N. The best thresholds are V \le 4.5 (B B B | N B N N N) and V \le 10 (B B B N B | N N N), both with weighted G = \tfrac58 \cdot (1 - 0.8^2 - 0.2^2) = 0.200. The root asks about V. (d) V is the local variance: a texture feature. Nuclei here are textured; the brightness alone overlaps between the classes (B at 80, N at 45). The best question is not necessarily about the feature you would think of first.

B2. (a) Below V = 6: B for I \le 100, N for I > 100. Above V = 6: B for I \le 40, N for I > 40. Four rectangles, split by a horizontal line at V = 6 and two vertical lines that stop at it. (b) (30, 10): V > 6, I \le 40: B. (120, 3): V \le 6, I > 100: N. (70, 5): V \le 6, I \le 100: B.

B3. Depth 2: training error and new-data error both moderate and close to each other. Depth 20: training error near 0 (every pixel ends up in a pure leaf), new-data error higher than the depth-2 tree’s: it has learned the noise of the training pixels. The deep tree changes much more when 10 pixels change: its lower splits depend on single points (high variance).

B4. (a) Means: depth 1: 0.302, depth 3: 0.200, depth 6: 0.180, depth 12: 0.232. Choose depth 6. (b) Grow a depth-6 tree on all the training data (all five folds). Then, once, compute its error on the test set and report that number. (c) The smallest of 50 noisy cross-validation estimates is biased low: some depth wins partly by luck on these folds. The test set, untouched by the choice, gives the honest number.

B5. \log is increasing, so the order of the pixels along I does not change, and every split separates the same pixels as before. The tree is the same, only its thresholds move (I \le 40 becomes I' \le \log 40). Nearest neighbour measures distances, and \log changes them (it squeezes large intensities together), so its decisions can change: it depends on the units and the scaling of the features, a tree does not.

B6. (a) Total SSE around the overall mean 21: 604. The five splits:

split after left right SSE
x = 1 10 12, 11, 30, 32, 31 458.8
x = 2 10, 12 11, 30, 32, 31 304.0
x = 3 10, 12, 11 30, 32, 31 4.0
x = 4 10, 12, 11, 30 32, 31 273.25
x = 5 10, …, 32 31 484.0

The split between x = 3 and x = 4 wins: means 11 and 31. (b) A step from 11 to 31 between positions 3 and 4. A depth-2 tree splits each half again and fits the small wiggles (e.g. 10 | 12, 11): with real noise that is already fitting noise.

B7. The validation pixels are neighbours of training pixels in the same strokes and the same image: near copies. The tree has effectively seen them, so 1 % measures memory, not generalisation. The second image has its own staining, illumination and noise. Validate on whole images (or at least on regions or strokes) that were not used for training.

Math questions

B8. (math) Show that 1 - \sum_k p_k^2 = \sum_{k \ne l} p_k p_l. For two classes with shares p and 1 - p, show that both G and H are largest at p = 1/2, and give their maxima.

B9. (math) Show that the impurity decrease of a split is \ge 0 when the impurity is a concave function of the class shares. When is it exactly 0?

B10. (math) 400 points of class A and 400 of class B. Split 1 gives children (300 A, 100 B) and (100 A, 300 B); split 2 gives (200 A, 400 B) and (200 A, 0 B). Compute the decrease of the misclassification impurity M = 1 - \max_k p_k and of Gini for both. Which split does each prefer, and why is M a poor splitting criterion?

B11. (math) For a regression split of n values into n_L and n_R with means \bar y_L and \bar y_R, show that the decrease in the sum of squared errors is \frac{n_L n_R}{n}(\bar y_L - \bar y_R)^2. Check it on B6.

B8. 1 = (\sum_k p_k)^2 = \sum_k p_k^2 + \sum_{k \ne l} p_k p_l. Two classes: G = 1 - p^2 - (1-p)^2 = 2p(1 - p), derivative 2 - 4p = 0 at p = 1/2, maximum G = 0.5. H = -p\log_2 p - (1-p)\log_2(1-p), derivative \log_2\frac{1-p}{p} = 0 at p = 1/2, maximum H = 1 bit. Both are 0 at p = 0 and p = 1.

B9. With w = n_L/n, the parent’s shares are \mathbf p = w\,\mathbf p^L + (1 - w)\,\mathbf p^R. Concavity of I gives I(\mathbf p) \ge w\,I(\mathbf p^L) + (1-w)\,I(\mathbf p^R), i.e. \Delta \ge 0. For a strictly concave I (Gini, entropy) equality holds only if \mathbf p^L = \mathbf p^R: both children have the parent’s class mix.

B10. Parent: M = 0.5, G = 0.5. Split 1: both children have M = 0.25, so \Delta M = 0.5 - 0.25 = 0.25; G = 2 \cdot 0.75 \cdot 0.25 = 0.375 each, \Delta G = 0.125. Split 2: M(200, 400) = 1/3, M(200, 0) = 0; \Delta M = 0.5 - \tfrac34 \cdot \tfrac13 - 0 = 0.25. G(200, 400) = 4/9, \Delta G = 0.5 - \tfrac34\cdot\tfrac49 = 0.167. M cannot tell them apart; Gini prefers split 2, which makes a pure child that needs no further questions. M is piecewise linear (not strictly concave), so it misses such progress, and in a node where every candidate child keeps the parent’s majority class it gives \Delta M = 0 for every split and the growth stops too early.

B11. Write S = \sum (y_i - \bar y)^2. With \bar y = (n_L\bar y_L + n_R\bar y_R)/n, the split of the total sum of squares gives S_P = S_L + S_R + n_L(\bar y_L - \bar y)^2 + n_R(\bar y_R - \bar y)^2. Since \bar y_L - \bar y = \frac{n_R}{n}(\bar y_L - \bar y_R) and \bar y_R - \bar y = -\frac{n_L}{n}(\bar y_L - \bar y_R), the last two terms are \frac{n_L n_R^2 + n_R n_L^2}{n^2}(\bar y_L - \bar y_R)^2 = \frac{n_L n_R}{n}(\bar y_L - \bar y_R)^2. B6: \frac{3 \cdot 3}{6}(11 - 31)^2 = 600 = 604 - 4.

Explore

Left: points of two or three classes in a square (two features, x and y). Click to add a point of the chosen class, drag points to move them, remove points to delete. The tree’s rectangles are coloured behind the points; the split lines are drawn on top, the last one thicker. next split grows the most useful open node (largest impurity decrease, weighted by its number of points), grow fully grows until the depth or leaf-size limit, reset goes back to the root. Right: the tree (click a node to select it) and either the split scan of the selected node (impurity decrease against the threshold, for a cut along x and along y; click on a curve to force that cut) or the error vs depth curve (each depth grown fully). show test points draws a hidden test set from the same source as open circles and reports the test error.

E1. Preset two blobs: one stump. Which question does the root ask, with which impurity decrease? What is the best cut along y, and why does the tree not use it? How many training points are wrong? Press grow fully: how many leaves, and what happens to the training and test errors (tick show test points)?

E2. Preset XOR: first split looks useless. Read the best impurity decrease along x and y at the root and compare with the decrease in E1. Press next split four times and note the training error after each. What does this say about greedy growth?

E3. Preset diagonal: staircase. How many leaves does the full tree have? Tick show test points: what is the test error? Set min leaf size to 5: leaves and test error now? Why can a tree only approximate this boundary?

E4. Preset one mislabelled point. Find the point of class 2 inside the class-1 cloud. How does the full tree handle it? Set min leaf size to 3. What changes in the picture, in the training error and in the test error?

E5. Preset noisy overlap: error vs depth. Read the training and test errors at depth 1, 3 and 12 from the curve. Which depth would you choose, and how would you choose it without a test set?

E6. Back to two blobs, choose misclass. and press grow fully. How many splits does the tree make now, and why does it stop? Compare with Gini.

E7. Preset regression: a cell edge. Read the leaf means of the depth-2 tree. Using the error-vs-depth curve, give the training and test MSE at depths 1, 2, 3 and 6. Which depth fits the edge best?

E1. The root asks x \le 0.48, with impurity decrease 0.480 (of a possible 0.5: the children are almost pure). The best cut along y is y \le 0.475 with decrease 0.328: the blobs overlap more in y. 1 of 100 training points is wrong. Grown fully: 3 splits, 4 leaves, depth 3, training error 0, but the test error rises from 2.5 % (stump) to 3.5 %: the two extra splits only chase one point.

E2. Root: best decrease 0.024 along x (at 0.453) and 0.013 along y, against 0.48 in E1: no single cut separates a chessboard. Training errors: 47/120 after one split, 20/120 after two, 1/120 after three, 0 after four. A useless-looking first question can be the start of a perfect tree; greedy growth works here only because it keeps going.

E3. 13 leaves (depth 7), training error 0, test error 7.7 %. With min leaf size 5: 7 leaves (depth 4), training error 2.7 %, test error 10.0 %. Each split is horizontal or vertical, so a diagonal line can only be approximated by a staircase; finer steps need many leaves and many points.

E4. The point at (0.27, 0.40) belongs to class 2 but sits among class 1. The full tree (4 leaves, depth 3) cuts a thin horizontal strip around it: training error 0, test error 1.0 %. With min leaf size 3 a leaf may not hold a single point, the strip disappears, the point is simply misclassified (training error 1/81 = 1.2 %), and the test error drops to 0.8 %.

E5. Depth 1: training 22.5 %, test 22.8 %. Depth 3: 17.5 % and 20.9 % (the lowest test error). Depth 12: 0.5 % and 28.9 %. Choose depth 3 (or 4, 21.0 %). Without a test set: cross-validation on the training points, or a separate validation set; the test set is then used once to report the error.

E6. With misclassification the tree stops after 1 split (training error 1/100). The further splits under Gini isolate a single point inside a child where the other class is the large majority; the majority class of each child does not change, so the misclassification impurity does not decrease (\Delta M = 0) and the growth stops. Gini still sees the purer child (as in B10).

E7. Depth 2: four plateaus with means 40, 75, 129 and 158 (left to right). MSE (training / test): depth 1: 262.8 / 264.8; depth 2: 124.7 / 141.4; depth 3: 88.0 / 130.1; depth 6: 31.8 / 224.2. Depth 3 has the lowest test error; deeper trees follow the noise of the training samples.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in randomforest/src/dtree/exercise.rs.

In the code, every point is a list of feature values and a class number (0, 1, …); for B1, feature 0 is I, feature 1 is V, class 0 is B and class 1 is N.

C1. gini(counts): G = 1 - \sum_k p_k^2 from the number of points of each class. The checks are B1 (a) and the nodes of B10.

C2. best_split(points, labels, n_classes, min_leaf): the split with the largest impurity decrease, by sorting and sweeping:

for every feature f:
    sort the points by f
    left = no points;  right = all points            # class counts
    for i = 1 .. n − 1:
        move the i-th point from right to left
        if its value differs from the next one, and both sides have ≥ min_leaf points:
            threshold = halfway between the two values
            decrease = G(all) − (n_left/n) G(left) − (n_right/n) G(right)
            keep the split with the largest decrease

On a tie, keep the first one found. The check is B1: the root asks V \le 4.5, decrease 0.3; on I alone, I \le 40.

C3. grow(points, labels, n_classes, max_depth, min_leaf): recursive partitioning:

grow(points):
    if the points are all of one class, or max_depth is reached,
       or no allowed split lowers the impurity:   return a leaf with the class counts
    find the best split (C2)
    return a node with that question, grow(points with f ≤ t), grow(points with f > t)

The checks: the stump of B1 has the leaves (3 B) and (1 B, 4 N); grown fully it gets every training point right; and B5: with \log I instead of I it makes the same predictions.

C4. predict(tree, x): follow the questions to a leaf and return its majority class. The check is the tree of B2 (b).

C5. regression_stump(xs, ys): the best split of a profile into two steps, each predicted by its mean, by trying every split between two neighbouring positions. The check is B6: the split between x = 3 and x = 4, with sum of squared errors 4.

Then cargo run -p randomforest -- dtree and open the pictures in out/dtree/. The program takes two very noisy synthetic fluorescence images, train-image.png and test-image.png, and computes two features per pixel: the 3 \times 3 mean and the 3 \times 3 local variance (as I and V in B1). It grows trees of increasing depth on 300 random pixels of the training image, and prints the training error and the error on every pixel of the other image. test-depth3.png and test-depth15.png show the test image classified by two of the trees (white = nucleus), next to test-truth.png.

C6. Predict, then check: how do the training error and the test error change as the depth grows from 1 to 15? Which depth would you choose, and how could you choose it without the test image?

C7. Which feature does the root ask about here, and why not the other one? Compare with B1.

The model solution is randomforest/src/dtree/solution.rs in the download.

C6. The training error falls from 3.0 % (depth 1) to 0 % (depth 6 and more, 14 leaves), while the test error on the other image rises from 4.7 % to 6.2 %: the deeper trees learn the noise of the 300 training pixels. Here the best test error is at depth 1 (4.7 %; depth 2 gives 4.8 %). Without a test image: hold back part of the training pixels as a validation set, or use cross-validation, and pick the depth with the lowest validation error; then report the test error of that one tree once. (Better still: validate on pixels from another image, B7.) In the pictures, both trees scatter white specks over the background (547 and 491 wrong pixels), but the depth-15 tree misses more of the nuclei (523 nucleus pixels called background, against 312 at depth 3).

C7. The root asks “mean ≤ 0.521?”: brightness. The noise in this image is the same everywhere, so the local variance is about the same inside and outside the nuclei and does not help. In B1 the nuclei were textured, and texture won.

Where this leads

One deep tree is unstable: small changes of the data give a different tree. The next unit grows many trees on slightly different data and lets them vote: bagging and random forests. Later units use forests on tables of object measurements and on stacks of filtered images. A tree of depth one (a stump) is the weak classifier that boosting combines in the face detector of the integral-images day.