Cut a column into just 4 bins and the best split you can still make has 88% of the gain of the best split among all the midpoints. With 256 bins it has 99.7%. That is why XGBoost can afford to look at every column in every node.
Why looking at every cut is slow
Where we are. The last topic made the validation honest. The last question of the skill about a single model is cost: the time it takes to train and the space it takes to store. Both come from the same source, the search for splits.
To grow a tree XGBoost must find the best cut in every node. The exact method sorts the rows by each column and tries every midpoint between two neighbouring values, as in the boosting-loop topic. For n rows that is n cuts per column per node, repeated for every node of every tree. With millions of rows this is the slowest part of training.
Group the values of each column into a limited number of bins once, before training. Then, in every node, add up the residuals and count the rows in each bin (one pass over the rows), and look at the cuts between bins only. There are at most max_bin of them, instead of one per row.
The trade is clear: a fraction of the exact cuts, a speed-up of the search, and a small loss when the best exact cut falls in the middle of a bin. This topic builds the pieces and measures the loss.
Edges and bin numbers
The bins should hold about the same number of rows, so the borders are quantiles of the column: with 4 bins, the 25th, 50th and 75th percentiles. These borders are the edges: a column cut into max_bin bins has max_bin - 1 of them. The bin number of a value is how many edges are at or below it.
Worked example 1. *Problem:* bin the numbers 1, 2, ..., 10 into 5 bins, and say where 4, 4.5 and 9 fall. *Plan:* the edges are the quantiles at 20 %, 40 %, 60 % and 80 %; then count the edges at or below each value. *Steps:* bin_edges and bin_index.
x = np.arange(1.0, 11.0)edges = bin_edges(x, 5)1print(edges.tolist())print(bin_index(x, edges).tolist())2print(bin_index([4.0, 4.5, 9.0], edges).tolist())
[2.8, 4.6, 6.4, 8.2] [0, 0, 1, 1, 2, 2, 3, 3, 4, 4] [1, 1, 4]
- 1The quantiles at 20, 40, 60 and 80 percent.
- 2The bin number of every value of x.
*Check:* the edges are 2.8, 4.6, 6.4, 8.2, and the bin numbers of 1 to 10 are 0, 0, 1, 1, 2, 2, 3, 3, 4, 4: two rows per bin. The value 4 falls in bin 1, 4.5 also in bin 1 and 9 in bin 4. *What to notice:* a value exactly equal to an edge goes to the bin on its right, so the bins are half-open intervals. Repeated values collapse edges: a column with a single repeated number cannot have more than one bin.
Two numbers per bin
For the search of the best cut, a node needs from each bin only two numbers: the sum of the residuals and the number of rows. With them, the cuts between bins can be evaluated with cumulative sums, exactly as in the boosting-loop topic, but over a handful of bins instead of thousands of rows.
Worked example 2. *Problem:* four bins hold the residual sums -3, -3, 4, 2 and 2 rows each. Which cut is best? *Plan:* the gain of a cut after bin k is S_L²/n_L + S_R²/n_R. Compute it for the three cuts. *Steps:* below.
sums = np.array([-3.0, -3.0, 4.0, 2.0])counts = np.array([2.0, 2.0, 2.0, 2.0])for k in range(3): left_sum, left_n = sums[: k + 1].sum(), counts[: k + 1].sum() right_sum, right_n = sums[k + 1 :].sum(), counts[k + 1 :].sum() print(k, round(left_sum**2 / left_n + right_sum**2 / right_n, 3))print(best_bin_split(sums, counts))
0 6.0 1 18.0 2 2.667 (1, 18.0)
*Check:* the gains are 6.0, 18.0 and 2.667; the best cut is after bin 1, with a gain of 18.0: the two negative bins go to the left, the two positive ones to the right. *What to notice:* the function best_bin_split does the same with cumulative sums in one pass, and refuses a cut that would leave a side without rows.
Worked example 3. *Problem:* from a column and its residuals to the sums per bin. *Plan:* make the edges, the bin numbers and bin_sums. Use the real vol column with 4 bins and the residuals of move (the target minus its mean). *Steps:* below.
panel = build_panel(load_close())fit = split_by_date(panel, "1900-01-01", "2011-01-01")residual = (fit[TARGET] - fit[TARGET].mean()).to_numpy()edges = bin_edges(fit["vol"], 4)bins = bin_index(fit["vol"], edges)sums, counts = bin_sums(bins, residual, len(edges) + 1)print(edges.round(4).tolist(), counts.tolist(), sums.round(2).tolist())print(best_bin_split(sums, counts))
[0.0483, 0.0675, 0.0962] [1651.0, 1651.0, 1651.0, 1651.0] [-39.45, -21.38, 5.0, 55.83] (2, 2.5175766081971496)
*Check:* the edges of vol are 0.0483, 0.0675, 0.0962, the four bins hold 1,651 rows each (6,604 rows in total), and the residual sums rise from -39.45 in the calmest bin to +55.83 in the wildest. The best cut is after bin 2, between the third and the fourth bin, at the edge 0.0962, with a gain of 2.52. *What to notice:* four numbers of each kind are all the search needed; the 6,604 rows have been summarised.
What the bins cost
The bins are an approximation. The best exact cut may fall inside a bin, and the histogram cannot see it. Measure the loss as a share of the best gain: 1 - (gain found by the bins) / (best exact gain).
Worked example 4. *Problem:* how much of the best split of vol do 4, 16, 64 and 256 bins find? *Plan:* hist_gain_loss, with the given best_exact_gain as the reference. *Steps:* below.
print(round(best_exact_gain(fit["vol"].to_numpy(), residual), 3))for max_bin in (2, 4, 16, 64, 256): print(max_bin, round(hist_gain_loss(fit["vol"].to_numpy(), residual, max_bin), 4))
2.85 2 0.2135 4 0.1166 16 0.0556 64 0.0244 256 0.0032
*Check:* the best exact gain is 2.85. With 2 bins the loss is 0.2135, with 4 bins 0.1166, with 16 0.0556, with 64 0.0244 and with 256 0.0032. *What to notice:* the loss falls fast: 256 bins find 99.7 % of the best gain. XGBoost's default max_bin is 256 for this reason. And a tree does not have to make its best cut: boosting corrects the errors of earlier trees, so a slightly worse cut costs very little.
The loss in the quality of one cut does not mean a loss in the quality of the model. Worked example 5. *Problem:* does the test error of the model suffer when the bins are few? *Plan:* fit the same 100 trees of depth 4 with 4, 16, 64 and 256 bins, and with the exact method, and compare the errors on the years from 2015. *Steps:* study.
result = study(panel)for key, row in result["models"].items(): print(str(key).ljust(6), round(row["rmse_test"], 5), row["nodes"], row["bytes"])
4 0.0526 2998 168436 16 0.0523 3066 170748 64 0.05203 3038 169796 256 0.05198 2954 166940 exact 0.05205 2640 156264
*Check:* the test error is 0.0526 with 4 bins, 0.0523 with 16, 0.05203 with 64, 0.05198 with 256 and 0.05205 with the exact method. *What to notice:* 4 bins cost half a percent of error, 16 bins cost almost nothing, and the exact method is not better than 256 bins on new data (the difference of 0.00007 is noise). For speed, bins are a bargain.
What the model costs to keep
A trained model is a list of trees, and each tree is a list of nodes: questions and leaves. Its size in storage grows with the number of nodes, and the nodes grow with the number of trees and with the depth. A tree of depth d has at most 2^(d+1) - 1 nodes.
Worked example 6. *Problem:* how many bytes does a model take, and how does it grow with trees and depth? *Plan:* fit models with different settings and read their sizes with model_size. *Steps:* below.
for n_trees, depth in ((50, 4), (100, 4), (100, 6), (300, 6)): size = model_size(fit_model(fit, n_trees, depth, 0.05)) print(n_trees, depth, size["nodes"], size["leaves"], size["bytes"], round(size["bytes"] / size["nodes"], 1))
50 4 1478 764 83905 56.8 100 4 2954 1527 166940 56.5 100 6 9788 4944 399337 40.8 300 6 29130 14715 1188805 40.8
*Check:* 50 trees of depth 4 take 83,905 bytes and have 1,478 nodes; 100 trees of depth 4 take 166,940 bytes, twice as much; 100 trees of depth 6 take 399,337 bytes, 9,788 nodes; 300 trees of depth 6 take 1,188,805 bytes. A node costs about 57 bytes at depth 4 and 41 at depth 6 (deeper trees have more leaves, which are cheaper to store). *What to notice:* size is proportional to the number of trees and grows steeply with depth. A model that is two-thirds of a megabyte is small, but a service that loads a thousand of them, one per asset or per day, feels it. This is another reason to prefer shallow trees and early stopping.
The histogram method is the one XGBoost runs on a graphics card (device="cuda" in recent versions): summing residuals per bin is exactly the kind of work a GPU does well. This lab does not need one; the idea is the same.
What you will build
The lab follows the lecture. Task 1 computes the edges of the bins and task 2 the bin number of each value. Task 3 adds up the residuals and the rows per bin and task 4 finds the best cut among the bins. Task 5 measures how much of the best gain the bins lose. Task 6 reads the size of a trained model, and task 7 compares models with 4 to 256 bins and the exact method on the real panel.
Next topic: the capstone. It puts everything of the skill together, features with holes, a ranking objective, a prior, an honest validation, importance and a model that is small enough to keep, and asks whether a ranker built from price data can order the stocks of next month.
Lab · what's graded
7 tasks · 100 pts- The edges of the bins15 pts
- The bin of every value10 pts
- Two numbers per bin10 pts
- The best cut among bins20 pts
- What the bins cost10 pts
- The size of a model10 pts
- How few bins25 pts