A leaf made of 2 rows can answer 0.033 when every one of them says 0.05, while a leaf of 200 rows answers 0.0498. A penalty of one number makes the first leaf modest and barely touches the second, and that is most of regularisation.
Penalties on leaves and splits
Where we are. The last topic chose the depth, the learning rate and the number of trees by looking at the validation years. But inside a tree, every leaf still answers with the plain average of its residuals, however few rows it holds. A leaf of two rows that happen to be large will say "large" with full confidence. Regularisation adds a price to that confidence.
Take the residuals of the rows in a node: the truth minus what the model predicted so far. Let n be their count and S their sum. For a squared error the best answer for a leaf is the mean, S / n. XGBoost adds a number to the count, called lambda (reg_lambda), and the answer becomes the following.
Anything that makes a model less eager to follow the training rows: shrinking the answers of small leaves (lambda), refusing splits that gain too little (gamma), demanding a minimum of rows in a leaf (min_child_weight), or training each tree on a random part of the rows and columns (subsample, colsample).
Worked example 1. *Problem:* three leaves hold 2, 20 and 200 rows, and every row has the residual 0.05. What does each leaf answer with lambda = 1, and with lambda = 10? *Plan:* the plain mean is 0.05 in all three; the answer is S / (n + λ) with S = 0.05 n. *Steps:* compute the six answers.
for n in (2, 20, 200): rows = np.full(n, 0.05) print(n, round(leaf_weight(rows, 0.0), 4), round(leaf_weight(rows, 1.0), 4), round(leaf_weight(rows, 10.0), 4))1
2 0.05 0.0333 0.0083 20 0.05 0.0476 0.0333 200 0.05 0.0498 0.0476
- 1The answer with lambda 0, 1 and 10.
*Check:* with lambda = 1 the leaf of 2 rows answers 0.0333 (two thirds of 0.05) and the leaf of 200 rows answers 0.0498; with lambda = 10 the small leaf answers 0.0083 and the big one 0.0476. *What to notice:* the penalty is a fixed number added to a count, so it matters a lot to small leaves and hardly at all to big ones. It acts as a vote of doubt that fades with evidence. The simple method, using the mean, treats two rows and two hundred rows alike.
A split is judged the same way. Before the split the node has the sum S and the count n; after it, two nodes with their own. The gain measures how much better the two parts describe the residuals than the parent did.
Worked example 2. *Problem:* a node holds four rows with the residuals 1, 1, -1, -1. A split puts the two positive ones on the left and the two negative ones on the right. What is the gain for lambda = 0 and for lambda = 2, and which values of gamma keep the split? *Plan:* the sums are 2 and -2, the counts 2 and 2, and the parent has sum 0 and count 4. *Steps:* compute.
left, right = [1.0, 1.0], [-1.0, -1.0]for lam in (0.0, 2.0): print(lam, split_gain(left, right, lam))print(keeps_split(left, right, 0.0, 3.9), keeps_split(left, right, 0.0, 4.0), keeps_split(left, right, 2.0, 1.9))
0.0 4.0 2.0 2.0 True False True
*Check:* with lambda = 0 the gain is 2²/2 + 2²/2 − 0 = 4; with lambda = 2 it is 4/4 + 4/4 − 0 = 2. A split with gamma 3.9 is kept, with gamma 4.0 it is not (equal is not enough), and with lambda = 2 a gamma of 1.9 keeps it. *What to notice:* the penalty lambda makes every split look less valuable, and gamma sets the minimum gain for a split to be kept. Together they decide whether a branch is grown at all: a split that does not pay for itself is never made.
Reading a fitted tree
XGBoost records the numbers behind every node of a fitted tree. That makes the formulas checkable: they must reproduce what the library stored. Worked example 3. *Problem:* fit a single stump on the fit years with a learning rate of 1 and read its top question, its gain and its two leaves. Then recompute the gain with your formula from the residuals on each side. *Plan:* stump_summary reads the tree; the rows on each side are the ones whose value is below the threshold or not.
panel = build_panel(load_close())fit = split_by_date(panel, "1900-01-01", "2011-01-01")valid = split_by_date(panel, "2011-01-01", "2015-01-01")test = split_by_date(panel, "2015-01-01")residuals = (fit[TARGET] - fit[TARGET].mean()).to_numpy()for lam in (0.0, 1.0, 50.0): top = stump_summary(fit_model(fit, 1, 1, 1.0, reg_lambda=lam))1 yes = fit[top["feature"]].to_numpy() < top["threshold"]2 print(lam, top["feature"], round(top["threshold"], 3), round(top["gain"], 3), round(split_gain(residuals[yes], residuals[~yes], lam), 3), top["left_cover"], top["right_cover"], round(top["left_leaf"], 4), round(top["right_leaf"], 4))
0.0 vol 0.119 2.832 2.832 5700.0 904.0 -0.0082 0.052 1.0 vol 0.119 2.83 2.83 5700.0 904.0 -0.0082 0.0519 50.0 vol 0.119 2.701 2.701 5700.0 904.0 -0.0082 0.0493
- 1The top question of the first tree, read from the model.
- 2The same gain computed from the formula.
*Check:* the top question is "is vol < 0.119?" for all three values of lambda. The gain XGBoost recorded and the gain from the formula agree: 2.832, 2.830 and 2.701. The two leaves hold 5,700 and 904 rows and answer -0.0082 and 0.052 (for lambda 0), moving only in the third decimal. *What to notice:* at the top of a tree, where the leaves are big, even lambda = 50 changes little. The penalty bites lower in the tree, where the nodes are small.
What each setting does
The settings that XGBoost exposes are different ways to say "be less sure". reg_lambda shrinks the answers, as above. gamma drops splits whose gain is too small. min_child_weight refuses a split that would leave fewer than that many rows in a child (for a squared error each row has weight 1). subsample trains each tree on a random share of the rows, and colsample_bytree on a random share of the columns, so that no tree can lean on one lucky row or one column.
Worked example 4. *Problem:* which of these settings generalises best on the validation years, for 60 deep trees (depth 6, rate 0.1)? *Plan:* settings_table fits one model per setting and reports its total leaves and its errors on the fit and the validation years. *Steps:* below.
grid = [{"reg_lambda": 0.0}, {}, {"reg_lambda": 50.0}, {"min_child_weight": 50}, {"gamma": 0.05}, {"subsample": 0.7, "colsample_bytree": 0.7}]for row in settings_table(fit, valid, grid): print(str(row["settings"]).ljust(46), row["leaves"], round(row["rmse_fit"], 5), round(row["rmse_valid"], 5))
{'reg_lambda': 0.0} 3170 0.04468 0.03739
{} 3065 0.04589 0.03722
{'reg_lambda': 50.0} 2412 0.05253 0.03681
{'min_child_weight': 50} 1056 0.05352 0.03693
{'gamma': 0.05} 245 0.05458 0.03694
{'subsample': 0.7, 'colsample_bytree': 0.7} 2831 0.04749 0.03738*Check:* with no penalty at all (reg_lambda 0) the 60 trees have 3,170 leaves, fit the fit years best (0.04468) and score 0.03739 on the validation years. Every penalty trims the leaves and raises the fit error, and most of them lower the validation error: lambda 50 gives 0.03681, a minimum of 50 rows per leaf 0.03693, a gamma of 0.05 0.03694 with only 245 leaves. Sampling rows and columns changes little here (0.03738). *What to notice:* the fit error goes up and the validation error goes down: the model gives up some detail of the fit years to keep what repeats. The gamma of 0.05 cuts the leaves from 3,065 (the default) to 245 for a similar validation error: a much smaller model that is as good.
- SettingWhat it does
- reg_lambdaShrinks every leaf answer; more for small leaves.default 1
- gammaThe minimum gain for a split to be kept.default 0
- min_child_weightThe minimum weight (rows, for a squared error) in a child.default 1
- subsample / colsample_bytreeTrain each tree on a random part of the rows / columns.random_state fixes it
- early_stopping_roundsStop when the validation error has not improved for this many trees.needs an eval_set
Early stopping: let validation say when
The last topic found the number of trees by reading a curve by hand. XGBoost can do it while it trains: give it a validation set and a patience. After every tree it scores the validation rows; when the score has not improved for patience trees in a row, it stops. The model keeps the position of the best tree.
Worked example 5. *Problem:* train with room for 500 trees and a patience of 20, and see where it stops. *Plan:* use fit_early_stopping with the defaults (depth 4, rate 0.05). *Steps:* below.
stopped = fit_early_stopping(fit, valid)print(stopped["best_trees"], stopped["trees_run"])print(round(float(stopped["model"].best_score), 5))
70 90 0.03677
*Check:* the best number of trees is 70 and 90 were trained: 20 more than the best, the patience. The best validation score is 0.03677. *What to notice:* model.best_iteration counts from 0 (it is 69), so the number of trees is one more; the trees after the best are trained only to prove that nothing better was coming. When you score new rows, use the first best_trees trees.
Early stopping chooses the best moment on the validation years, so the validation score is a little optimistic: it is the best of many looks. That is why the test years stay untouched until the end.
Choose a setting, stop early, judge once
Worked example 6. *Problem:* put it together. *Plan:* choose the regularisation setting by the validation error of the table, train with it and stop early, then score on the test years once. *Steps:* study.
result = study(panel)print(result["best_settings"], result["best_trees"], result["trees_run"])print(round(result["rmse_valid"], 5), round(result["rmse_test"], 5), round(result["rmse_test_baseline"], 5))
{'reg_lambda': 50.0} 142 162
0.0367 0.05192 0.05453*Check:* the best setting is a lambda of 50, early stopping keeps 142 trees (162 were trained), the validation score is 0.0367 and the test score 0.05192, against 0.05453 for the plain average. *What to notice:* the regularised, early-stopped model is about 5 % better than the average on the test years, the same as the model of the last topic (0.05199). The settings changed the way the model gets there, with a smoother fit and fewer leaves per tree, and not the accuracy: the features hold a limited amount of signal and several routes reach it.
What you will build
The lab follows the lecture. Task 1 is the answer of a leaf with the penalty and task 2 the gain of a split; task 3 decides whether a split is kept. Task 4 reads the top of a fitted tree, task 5 stops a model early and task 6 compares regularisation settings. Task 7 chooses a setting on the validation years, stops early with it and judges the result once on the test years.
Next topic: so far every feature column was complete. The next topic, Missing values and categorical features, gives XGBoost columns with holes and a column of sectors, and shows what the trees do with them.
Lab · what's graded
7 tasks · 100 pts- A leaf with a penalty10 pts
- The gain of a split15 pts
- Is the split kept10 pts
- Read a fitted tree15 pts
- Early stopping20 pts
- Compare the settings15 pts
- Choose, stop early, judge once15 pts