Give two libraries the same budget of 8 leaves and they spend it differently: XGBoost fills a tree level by level, LightGBM keeps splitting the one leaf that gains the most. On 56 stocks the second tree goes 4 levels deep, the first only 3, and the validation error differs in the fourth digit. This topic builds both rules.
Two ways to spend a budget of leaves
Where we are. In the XGBoost skill every tree was grown *level-wise*: all the nodes of one level are split before any node of the next. LightGBM, a library from Microsoft, grows *leaf-wise*. The rest of this skill (histograms, categories, imbalance, tuning, ranking) builds on that one difference, so we start by growing both kinds of tree ourselves.
Split every node of the current level, then every node of the next, until the tree has the chosen depth. The tree is balanced, and its size is limited by max_depth: at most 2^max_depth leaves.
Look at all the current leaves, find the best cut of each, and split the one leaf whose cut gains the most, wherever it is in the tree. Repeat until the tree has num_leaves leaves. The tree can be lopsided: one branch long, another short.
Both rules use the same ingredient: for a group of rows, the best question of the form "is this column <= that threshold?". The question is chosen by its *gain*. The next section shows what the gain counts.
Counting the gain
A leaf answers with the mean of its rows. If a cut sends the rows into two groups, each group answers with its own mean, and the squared error falls. How much it falls is the gain of the cut.
Sort the rows by the column once. Then S_L for every cut is a cumulative sum, and one pass computes the gain of all the cuts of a column. Worked example 1. *Problem:* eight rows, one column x = 0, 1, ..., 7 and the target y = 0, 0, 0, 0, 1, 3, 9, 27. Which cut gains the most? *Plan:* the sums on the left of the seven cuts are a cumulative sum; the counts on the left are 1..7; put them into equation 1. *Steps:* below.
x = np.arange(8.0).reshape(-1, 1)y = np.array([0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 9.0, 27.0])left_sum = np.cumsum(y)[:-1]1left_n = np.arange(1, 8)2gain = left_sum**2 / left_n + (y.sum() - left_sum) ** 2 / (8 - left_n) - y.sum() ** 2 / 83print(left_sum.tolist(), y.sum())print(gain.round(2).tolist())print(best_split(x, y))
[0.0, 0.0, 0.0, 0.0, 1.0, 4.0, 13.0] 40.0 [28.57, 66.67, 120.0, 200.0, 307.2, 450.67, 553.14] (0, 6.5, 553.1428571428571)
- 1The sum of y on the left of each cut: one cumulative sum.
- 2The number of rows on the left of each cut.
- 3Equation 1 for all seven cuts at once.
*Check:* the last cut, between x = 6 and x = 7, wins with a gain of 553.14: it sets the single row 27 apart from the rest. Check by hand: left S_L = 13, n_L = 7; right S_R = 27, n_R = 1; 169/7 + 729/1 − 1600/8 = 24.14 + 729 − 200 = 553.14. The function returns the column (0), the threshold halfway between the two values (6.5) and the gain. *What to notice:* the gain depends on the size of the group as well as on the means. A single extreme row can have a large gain, which is why a minimum number of rows per leaf (min_leaf, in LightGBM min_child_samples) is the first guard against memorising.
Level by level
Level-wise growth is a recursion: cut the node with its best cut, then grow the left and the right group with one level less. A node stays a leaf when the depth is used up, when no cut is allowed (every column constant, or fewer rows than 2 × min_leaf) or when the best gain is not above 0, as with a group that is already pure.
Worked example 2. *Problem:* grow a level-wise tree of depth 2 on the eight rows of example 1. *Plan:* the root cuts at 6.5; the left group has 7 rows and is cut again, the right group is one row and cannot be cut. *Steps:* grow it and print it with a small helper.
def show(node, names, indent=0): pad = " " * indent if "value" in node: print(f"{pad}leaf {node['value']:.3f} ({node['n']} rows)") return print(f"{pad}{names[node['feature']]} <= {node['threshold']:.3f} gain {node['gain']:.2f} ({node['n']} rows)") show(node["left"], names, indent + 1) show(node["right"], names, indent + 1)tree = grow_level_wise(x, y, 2)show(tree, ["x"])print(tree_shape(tree))
x <= 6.500 gain 553.14 (8 rows)
x <= 5.500 gain 59.52 (7 rows)
leaf 0.667 (6 rows)
leaf 9.000 (1 rows)
leaf 27.000 (1 rows)
{'leaves': 3, 'depth': 2, 'smallest_leaf': 1, 'largest_leaf': 6}*Check:* the root cuts at 6.5; its left child (7 rows) cuts at 5.5 into a leaf of 6 rows (mean 0.667) and a leaf of 1 row (9.0); the right child is the single row 27.0. That is 3 leaves, not the 4 that depth 2 allows. *What to notice:* level-wise growth cannot spend the leaf that was never available. Also notice what it did *not* do: it did not try to cut the 6-row leaf 0, 0, 0, 0, 1, 3, where the error is still large.
Leaf by leaf
Leaf-wise growth keeps a small table: for each current leaf, its rows and its best cut with the gain. Each round it picks the largest gain in the table, splits that leaf, and adds a row to the table for each of the two new leaves.
- 1StartOne leaf holding all the rows; compute its best cut.
- 2PickThe leaf with the largest gain in the table. On a tie, the leaf that was created first.
- 3SplitReplace the leaf by a split and two new leaves; compute the best cut of each new leaf.
- 4RepeatUntil there are
num_leavesleaves, or until no leaf has a cut with a gain above 0.
Worked example 3. *Problem:* the same eight rows with a budget of 4 leaves. *Plan:* the root cut gains 553.14; the left group then has a cut that gains 59.52, the right (one row) has none, so the left group is cut; its left part is cut again. *Steps:* grow it leaf-wise and print it.
def show(node, names, indent=0): pad = " " * indent if "value" in node: print(f"{pad}leaf {node['value']:.3f} ({node['n']} rows)") return print(f"{pad}{names[node['feature']]} <= {node['threshold']:.3f} gain {node['gain']:.2f} ({node['n']} rows)") show(node["left"], names, indent + 1) show(node["right"], names, indent + 1)tree = grow_leaf_wise(x, y, 4)show(tree, ["x"])print(tree_shape(tree))
x <= 6.500 gain 553.14 (8 rows)
x <= 5.500 gain 59.52 (7 rows)
x <= 4.500 gain 6.53 (6 rows)
leaf 0.200 (5 rows)
leaf 3.000 (1 rows)
leaf 9.000 (1 rows)
leaf 27.000 (1 rows)
{'leaves': 4, 'depth': 3, 'smallest_leaf': 1, 'largest_leaf': 5}*Check:* after the first two splits, the leaf of six rows 0, 0, 0, 0, 1, 3 is the only one left with a usable cut (gain 6.53), so it is cut next, into five rows with mean 0.2 and the row 3.0. The tree has 4 leaves in a chain of depth 3, with sizes 5, 1, 1, 1. *What to notice:* with the same budget, the leaf-wise tree reduced the error where it was largest; the level-wise tree stopped at 3 leaves. The price is the shape: a chain like this can end in leaves of a single row, which is why LightGBM has the guards min_child_samples and max_depth.
- FunctionQuestion it answers
- best_split(X, y, min_leaf)Which column and threshold gain the most?sort once, cumulative sums
- tree_predict(tree, X)Which leaf does each row reach?equal goes left
- grow_level_wise(X, y, max_depth, min_leaf)What tree do I get with a depth budget?stops on gain 0
- grow_leaf_wise(X, y, num_leaves, min_leaf)What tree do I get with a leaf budget?largest gain first
- tree_shape(tree)How many leaves, how deep, how small?a lone leaf has depth 0
The panel
Worked example 4. *Problem:* on the 56 stocks, grow a leaf-wise tree with 6 leaves to predict the size of next month's move (move = |fwd|) from mom, rev and vol, using the 6,604 rows before 2011 and at least 20 rows per leaf. *Plan:* grow it and print the splits in the shape of the tree. *Steps:* below.
def show(node, names, indent=0): pad = " " * indent if "value" in node: print(f"{pad}leaf {node['value']:.3f} ({node['n']} rows)") return print(f"{pad}{names[node['feature']]} <= {node['threshold']:.3f} gain {node['gain']:.2f} ({node['n']} rows)") show(node["left"], names, indent + 1) show(node["right"], names, indent + 1)panel = build_panel(load_close())fit, valid, test = split_panel(panel)X, y = fit[FEATURES].to_numpy(), fit[TARGET].to_numpy()X_valid, y_valid = valid[FEATURES].to_numpy(), valid[TARGET].to_numpy()tree = grow_leaf_wise(X, y, 6, 20)show(tree, FEATURES)
vol <= 0.120 gain 2.85 (6604 rows)
vol <= 0.069 gain 0.85 (5710 rows)
leaf 0.044 (3456 rows)
mom <= -0.353 gain 0.22 (2254 rows)
leaf 0.105 (151 rows)
leaf 0.066 (2103 rows)
mom <= -0.718 gain 1.03 (894 rows)
leaf 0.280 (36 rows)
mom <= -0.344 gain 0.26 (858 rows)
leaf 0.135 (242 rows)
leaf 0.097 (616 rows)*Check:* the first cut is on the volatility of the last 12 months: vol <= 0.120 puts 894 volatile rows on the right, whose next move averages more than the others. The next cuts follow the gains: mom <= -0.718 on the volatile side (gain 1.03, a leaf of 36 rows after a fall of 72 % or more, whose next move averages 0.280), then vol <= 0.069 on the calm side (0.85), and so on. *What to notice:* the leaf of 36 rows is the extreme case: after a fall of 72 % or more the next move averages 0.280, six times the 0.044 of the calmest 3,456 rows. A level-wise tree has 4 leaves at depth 2 and up to 8 at depth 3, never 6; a leaf-wise tree can stop at any number.
Now the comparison that this topic is about. For budgets of 2, 4, 8 and 16 leaves, a level-wise tree of depth 1 to 4 against a leaf-wise tree with 2^depth leaves, scored on the rows of 2011 to 2014, which neither tree has seen.
for depth in (1, 2, 3, 4): level = grow_level_wise(X, y, depth, 20) leaf = grow_leaf_wise(X, y, 2**depth, 20) a, b = tree_shape(level), tree_shape(leaf) print(f"{2**depth:>2} leaves | level: {a['leaves']:>2} leaves, depth {a['depth']}, valid {rmse(y_valid, tree_predict(level, X_valid)):.5f} | leaf: {b['leaves']:>2} leaves, depth {b['depth']}, valid {rmse(y_valid, tree_predict(leaf, X_valid)):.5f}")
2 leaves | level: 2 leaves, depth 1, valid 0.03995 | leaf: 2 leaves, depth 1, valid 0.03995 4 leaves | level: 4 leaves, depth 2, valid 0.03828 | leaf: 4 leaves, depth 2, valid 0.03828 8 leaves | level: 7 leaves, depth 3, valid 0.03766 | leaf: 8 leaves, depth 4, valid 0.03762 16 leaves | level: 13 leaves, depth 4, valid 0.03700 | leaf: 16 leaves, depth 7, valid 0.03696
*Check:* with 2 and 4 leaves the two trees are the same tree. With a budget of 8, the level-wise tree has 7 leaves (one node had no allowed cut) and an error of 0.03766; the leaf-wise tree has 8 leaves, goes 4 levels deep and reaches 0.03762. With 16, level-wise stops at 13 leaves (0.03700), leaf-wise uses all 16, goes 7 levels deep and reaches 0.03696. *What to notice:* the gain of leaf-wise growth on unseen months is real but small, the fourth digit. Its depth is not: a depth of 7 means some rule asks seven questions in a row, and the leaf at the end holds only 20 rows. On other data, with fewer rows, the same freedom turns into memorising, and this is what the LightGBM documentation warns about.
Last, the check that makes your code trustworthy. LightGBM with one tree, a learning rate of 1 and no regularisation should grow the same tree. Two settings make its search as exact as yours: max_bin=100000 and min_data_in_bin=1 give each distinct value its own bin (the next topic explains bins).
reference = lgb.LGBMRegressor(n_estimators=1, learning_rate=1.0, num_leaves=8, min_child_samples=20, reg_lambda=0, max_bin=100000, min_data_in_bin=1, n_jobs=1, random_state=0, verbose=-1)1reference.fit(X, y)mine = tree_predict(grow_leaf_wise(X, y, 8, 20), X_valid)theirs = reference.predict(X_valid)print(round(rmse(y_valid, mine), 5), round(rmse(y_valid, theirs), 5), f"{np.max(np.abs(mine - theirs)):.1e}")
0.03762 0.03762 1.0e-09
- 1One tree, no shrinkage, no regularisation, exact thresholds, a leaf budget of 8.
*Check:* both trees score 0.03762 on the valid rows, and the largest difference between a prediction of yours and one of LightGBM's is about 1e-09. *What to notice:* the thresholds are not identical (LightGBM puts them at the upper border of a bin, you put them halfway), but they send every row to the same leaf, so the predictions agree. num_leaves really is the leaf budget of a best-first tree.
A level-wise tree of depth d has at most 2^d leaves, so people copy num_leaves = 2^max_depth. For a leaf-wise tree that number is too generous: with num_leaves = 255 the tree can still be 20 levels deep. If you set max_depth as well, keep num_leaves clearly below 2^max_depth.
What you will build
The lab follows the lecture. Task 1 finds the best cut of a group of rows, task 2 applies a tree. Task 3 grows a tree level by level, task 4 leaf by leaf. Task 5 describes a tree in four numbers. Task 6 compares both rules on the real panel and checks yours against LightGBM.
Next topic: the thresholds of this topic came from sorting every column, which is slow when there are many rows. The next topic, Histogram binning and speed, shows how LightGBM replaces the sort by bins, and the trick that halves the work for every pair of children.
Lab · what's graded
6 tasks · 100 pts- The best cut20 pts
- Apply a tree10 pts
- Level-wise growth20 pts
- Leaf-wise growth25 pts
- Describe a tree5 pts
- Level-wise against leaf-wise20 pts