A tree with 31 leaves on 6,604 rows reads 41,726 rows if every child is scanned, and 14,191 if each split scans only its smaller child. Same tree, a third of the work. This topic builds the two ideas behind that number: bins instead of sorting, and the child you get for free.
Bins instead of sorting
Where we are. The previous topic found every cut by sorting a column and walking along it. Do that in every node of every tree, and a model with a million rows spends most of its time sorting. LightGBM turns the problem around: it replaces each column by a handful of integers once, before the first tree, and from then on it only ever works with those integers.
A range of values of one column, such as "vol between 0.058 and 0.068". The column is replaced by the number of the bin each row falls in. LightGBM keeps at most max_bin bins per column (255 by default, so a bin number fits in one byte).
Where to put the borders? LightGBM wants bins that hold about the same number of rows, so that no cut is wasted on an empty range. The simple rule: if a column has at most max_bin distinct values, give each its own bin, with the borders at the midpoints (that is the exact search of the last topic). Otherwise put the borders at the quantiles.
Worked example 1. *Problem:* the 12-month volatility vol of the 6,604 rows before 2011 is very skewed: most stocks sit near 0.06, a few at 0.4. Compare 8 bins of equal width with 8 bins at the quantiles. *Plan:* build both sets of borders and count the rows per bin. *Steps:* below.
vol = fit["vol"].to_numpy()equal_width = np.linspace(vol.min(), vol.max(), 9)[1:-1]1quantile = bin_edges(vol, 8)2print("equal width", equal_width.round(3).tolist(), np.bincount(bin_index(vol, equal_width)).tolist())print("quantiles ", quantile.round(3).tolist(), np.bincount(bin_index(vol, quantile)).tolist())
equal width [0.065, 0.114, 0.162, 0.211, 0.259, 0.307, 0.356] [3120, 2458, 677, 213, 43, 60, 18, 15] quantiles [0.04, 0.048, 0.058, 0.068, 0.08, 0.096, 0.125] [826, 825, 826, 825, 825, 826, 825, 826]
- 1Eight bins of the same width.
- 2Eight bins with the same number of rows.
*Check:* equal-width bins put 3,120 rows in the first bin and 15 in the last, and the last four bins hold only 136 rows between them, so most cuts between them say nothing. Quantile bins hold 825 or 826 rows each, so every cut moves about an eighth of the data. *What to notice:* the inner borders of the quantile version sit between 0.040 and 0.125, where the rows are; the large values share the last bin. The price of bins is that a cut inside a bin is no longer possible: with 8 bins, the algorithm cannot separate vol = 0.13 from vol = 0.40.
To put a value into its bin, count the borders below it. A value equal to a border goes to the bin on its left, the rule x <= threshold of the last topic. np.searchsorted(edges, x, side="left") does it for a whole column at once. The borders are computed on the fit rows only; new rows, from a later date, are put into those same bins.
A histogram is two arrays
For one node and one column, the whole search needs only two numbers per bin. The rows of a node are summarised by a histogram: the sum of the target and the number of rows, for each bin.
Worked example 2. *Problem:* eight rows in four bins, bin = 0, 0, 1, 1, 2, 2, 3, 3 with the targets 1, 2, 1, 2, 8, 9, 8, 9. Build the histogram and find the best cut. *Plan:* np.bincount with weights adds up the targets per bin; the cumulative sums of the two arrays are S_L and n_L of every cut; equation 1 of the last topic gives the gain. *Steps:* below.
bin_ids = np.array([0, 0, 1, 1, 2, 2, 3, 3])target = np.array([1.0, 2.0, 1.0, 2.0, 8.0, 9.0, 8.0, 9.0])parent = histogram(bin_ids, target, 4)1print(parent[0].tolist(), parent[1].tolist())print(best_bin_split(parent))
[3.0, 3.0, 17.0, 17.0] [2, 2, 2, 2] (1, 98.0)
- 1The whole node, summarised in 8 numbers.
*Check:* the sums are 3, 3, 17, 17 and the counts 2, 2, 2, 2. The cut after bin 1 sends 4 rows with a sum of 6 to the left and 4 rows with a sum of 34 to the right: 6²/4 + 34²/4 − 40²/8 = 9 + 289 − 200 = 98. The cuts after bin 0 and bin 2 gain 32.67 each. *What to notice:* the function never saw the rows again. Its cost is the number of bins, n_bins − 1 cuts, not the number of rows. A histogram has 255 entries whether the node holds 300 rows or 3,000,000.
A bin with no rows makes the cut after it equal to the cut before it. Both have the same gain, and the rule "the smaller bin on a tie" picks the first, so the answer does not depend on how many empty bins there are.
The free child: histogram subtraction
Building a histogram costs one pass over the rows of the node. A split makes two children, so it seems to need two passes. It does not. Every row of the parent is in exactly one child, so adding the two children's histograms gives the parent's histogram, bin by bin.
So scan the smaller child, and get the other one by subtraction: right = parent − left. The work of a split falls from "all the rows of the node" to "the rows of the smaller child", which is at most half of them. Worked example 3. *Problem:* split the node of example 2 after bin 1 and build the histogram of the right child without looking at its rows. *Plan:* scan the left child, subtract it from the parent, and check against a real scan of the right rows. *Steps:* below.
goes_left = bin_ids <= 1left = histogram(bin_ids[goes_left], target[goes_left], 4)right = subtract(parent, left)scanned = histogram(bin_ids[~goes_left], target[~goes_left], 4)print(left[0].tolist(), left[1].tolist())print(right[0].tolist(), right[1].tolist())print(scanned[0].tolist(), scanned[1].tolist())
[3.0, 3.0, 0.0, 0.0] [2, 2, 0, 0] [0.0, 0.0, 17.0, 17.0] [0, 0, 2, 2] [0.0, 0.0, 17.0, 17.0] [0, 0, 2, 2]
*Check:* the left child holds the bins 0 and 1 (sums 3, 3, counts 2, 2); the parent minus the left child is 0, 0, 17, 17 and 0, 0, 2, 2, exactly what scanning the four right rows gives. *What to notice:* the subtraction touches n_bins numbers, not rows. Only rows of the smaller child were read.
How much does this save over a whole tree? Count the rows scanned. The root reads all n rows. After that, each split reads the rows of the smaller child, or, without the trick, of both children. For a tree with several splits:
The tree from histograms
Now the pieces fit together into the tree of the last topic. Each leaf carries its histograms (one per column) and its best cut. When a leaf is split, the smaller child is scanned, the larger child's histograms are the parent's minus the smaller child's, and each child's best cut is found from its histograms.
- 1RootScan all the rows into one histogram per column; find the best cut over the columns.
- 2PickThe leaf with the largest gain, as before (the first created on a tie).
- 3Scan the smaller childCount its rows as scanned. Build its histogram for every column.
- 4SubtractThe other child's histograms are the parent's minus the scanned child's. No rows are read.
- 5Cuts
best_bin_spliton the histograms of both children; repeat untilnum_leaves.
- FunctionQuestion it answers
- bin_edges(x, max_bin)Where are the borders between bins?quantiles, duplicates dropped
- bin_index(x, edges)Which bin is each value in?equal goes left
- histogram(bin_ids, y, n_bins)What does a node look like?sums and counts
- subtract(parent, child)What does the other child look like?no rows read
- best_bin_split(hist, min_leaf)Which cut gains the most?cumulative sums
- grow_hist_tree(bins, y, num_leaves, subtraction, min_leaf)Which tree, and how many rows were read?returns the count
The panel
Worked example 4. *Problem:* on the 56 stocks, how much does the number of bins change the quality of an 8-leaf tree for the size of next month's move? *Plan:* compute borders on the fit rows, put the fit and valid rows into bins with those borders, grow the tree from histograms and score the valid rows (2011 to 2014). *Steps:* below.
def binned(max_bin): edges = [bin_edges(fit[column], max_bin) for column in FEATURES]1 fit_bins = np.column_stack([bin_index(fit[column], e) for column, e in zip(FEATURES, edges)]) valid_bins = np.column_stack([bin_index(valid[column], e) for column, e in zip(FEATURES, edges)]) return fit_bins, valid_binsfor max_bin in (4, 16, 64, 255, 100000): fit_bins, valid_bins = binned(max_bin) tree, scanned = grow_hist_tree(fit_bins, y, 8, True, 20)2 print(f"max_bin {max_bin:>6} | {fit_bins.max() + 1:>4} bins | valid rmse {rmse(y_valid, tree_predict(tree, valid_bins)):.5f} | rows scanned {scanned}")
max_bin 4 | 4 bins | valid rmse 0.03745 | rows scanned 13285 max_bin 16 | 16 bins | valid rmse 0.03726 | rows scanned 12368 max_bin 64 | 64 bins | valid rmse 0.03774 | rows scanned 11453 max_bin 255 | 255 bins | valid rmse 0.03717 | rows scanned 12155 max_bin 100000 | 6604 bins | valid rmse 0.03762 | rows scanned 11655
- 1Borders from the fit rows only; the valid rows are put into the same bins.
- 2A tree with 8 leaves grown from histograms.
*Check:* with max_bin=100000 every distinct value has its own bin (6,604 bins in the largest column) and the error is 0.03762, the same as the exact 8-leaf tree of the last topic. With 255 bins it is 0.03717, with 16 bins 0.03726, with 4 bins 0.03745, and with 64 bins 0.03774. *What to notice:* the differences are in the fourth digit and do not follow the number of bins; coarse bins are not much worse, and sometimes they are better. A border at a quantile cannot isolate one lucky stock-month, so the tree has fewer ways to memorise. Bins are a mild regulariser, and max_bin is a setting to tune, not a quality dial.
Now the speed. Grow a tree with 31 leaves (the default of LightGBM) on the 255-bin version, once with the trick and once without, and compare the rows scanned and the trees.
fit_bins, valid_bins = binned(255)with_trick, scanned_with = grow_hist_tree(fit_bins, y, 31, True, 20)without, scanned_without = grow_hist_tree(fit_bins, y, 31, False, 20)print(len(y), scanned_without, scanned_with, f"{scanned_with / scanned_without:.0%}")print(np.allclose(tree_predict(with_trick, fit_bins), tree_predict(without, fit_bins)))
6604 41726 14191 34% True
*Check:* the tree has 30 splits. Without the trick the histograms are built from 41,726 row reads, about 6.3 passes over the data (the root plus both children of every split); with it, from 14,191, about 2.1 passes, 34 % of the work, and the two trees predict the same. *What to notice:* the saving is more than half because the smaller child is often much smaller than the larger one: a cut that isolates a few extreme stock-months scans just those. The more lopsided the splits, the larger the saving. LightGBM adds one more trick on top: it never builds the histogram of a column a tree does not use (feature_fraction).
And the check that makes the code trustworthy: the exact version should be the tree LightGBM grows with the same settings.
fit_bins, valid_bins = binned(100000)tree, _ = grow_hist_tree(fit_bins, y, 8, True, 20)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(fit[FEATURES].to_numpy(), y)theirs = reference.predict(valid[FEATURES].to_numpy())print(round(rmse(y_valid, tree_predict(tree, valid_bins)), 5), round(rmse(y_valid, theirs), 5), f"{np.max(np.abs(tree_predict(tree, valid_bins) - theirs)):.1e}")
0.03762 0.03762 1.0e-09
- 1LightGBM's own bins: the same settings as in the last topic.
*Check:* both give 0.03762 and the largest difference between a prediction of yours and one of LightGBM's is about 1e-09. *What to notice:* with one bin per distinct value, histograms lose nothing. LightGBM's default of 255 bins builds its borders in a slightly different way from the quantiles above (it also respects min_data_in_bin, 3 by default), so with 255 bins the trees would be similar but not identical.
A smaller max_bin (63, 31) makes training faster and uses less memory and is often as accurate; a larger one helps only when a column needs fine cuts, such as a price level. Always judge it on later months, as in the table above, not on the rows the model was fitted on.
What you will build
The lab follows the lecture. Task 1 chooses the borders, task 2 puts values into bins. Task 3 builds a histogram and task 4 subtracts one. Task 5 finds the best cut from a histogram. Task 6 grows a leaf-wise tree from histograms and counts the rows it scans. Task 7 runs it on the real panel and checks it against LightGBM.
Next topic: so far every column was a number. The next topic, Categorical features, shows how LightGBM cuts a column of labels, such as the ticker, without turning it into dozens of 0/1 columns.
Lab · what's graded
7 tasks · 100 pts- The bin borders15 pts
- Values into bins10 pts
- A histogram10 pts
- The free child10 pts
- The best cut of a histogram20 pts
- A tree from histograms20 pts
- Bins and speed on the panel15 pts